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/blitter.h"
15 #include "sound/sound_driver.hpp"
16 #include "music/music_driver.hpp"
17 #include "video/video_driver.hpp"
24 #include "base_media_base.h"
25 #include "saveload/saveload.h"
26 #include "company_func.h"
27 #include "command_func.h"
28 #include "news_func.h"
34 #include "console_func.h"
35 #include "screenshot.h"
36 #include "network/network.h"
37 #include "network/network_func.h"
39 #include "ai/ai_config.hpp"
40 #include "settings_func.h"
43 #include "strings_func.h"
44 #include "date_func.h"
45 #include "vehicle_func.h"
47 #include "animated_tile_func.h"
48 #include "roadstop_base.h"
49 #include "elrail_func.h"
51 #include "highscore.h"
52 #include "station_base.h"
54 #include "engine_func.h"
55 #include "core/random_func.hpp"
57 #include "core/backup_type.hpp"
60 #include "misc/getoptdata.h"
61 #include "game/game.hpp"
62 #include "game/game_config.hpp"
64 #include "subsidy_func.h"
65 #include "gfx_layout.h"
68 #include "linkgraph/linkgraphschedule.h"
72 void CallLandscapeTick();
74 void DoPaletteAnimations();
77 void CallWindowTickEvent();
78 bool HandleBootstrap();
80 extern Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
);
81 extern void ShowOSErrorBox(const char *buf
, bool system
);
82 extern char *_config_file
;
85 * Error handling for fatal user errors.
86 * @param s the string to print.
87 * @note Does NEVER return.
89 void CDECL
usererror(const char *s
, ...)
95 bstrvfmt (buf
, s
, va
);
98 ShowOSErrorBox(buf
, false);
99 if (VideoDriver::GetActiveDriver() != NULL
) VideoDriver::GetActiveDriver()->Stop();
105 * Error handling for fatal non-user errors.
106 * @param s the string to print.
107 * @note Does NEVER return.
109 void CDECL
error(const char *s
, ...)
115 bstrvfmt (buf
, s
, va
);
118 ShowOSErrorBox(buf
, true);
120 /* Set the error message for the crash log and then invoke it. */
121 CrashLog::SetErrorMessage(buf
);
126 * Shows some information on the console/a popup box depending on the OS.
127 * @param str the text to show.
129 void CDECL
ShowInfoF(const char *str
, ...)
134 bstrvfmt (buf
, str
, va
);
140 * Show the help message when someone passed a wrong parameter.
142 static void ShowHelp()
146 buf
.fmt ("OpenTTD %s\n", _openttd_revision
);
150 "Command line options:\n"
151 " -v drv = Set video driver (see below)\n"
152 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
153 " -m drv = Set music driver (see below)\n"
154 " -b drv = Set the blitter to use (see below)\n"
155 " -r res = Set resolution (for instance 800x600)\n"
156 " -h = Display this help text\n"
157 " -t year = Set starting year\n"
158 " -d [[fac=]lvl[,...]]= Debug mode\n"
159 " -e = Start Editor\n"
160 " -g [savegame] = Start new/save game immediately\n"
161 " -G seed = Set random seed\n"
162 #if defined(ENABLE_NETWORK)
163 " -n [ip:port#company]= Join network game\n"
164 " -p password = Password to join server\n"
165 " -P password = Password to join company\n"
166 " -D [ip][:port] = Start dedicated server\n"
167 " -l ip[:port] = Redirect DEBUG()\n"
168 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
169 " -f = Fork into the background (dedicated only)\n"
171 #endif /* ENABLE_NETWORK */
172 " -I graphics_set = Force the graphics set (see below)\n"
173 " -S sounds_set = Force the sounds set (see below)\n"
174 " -M music_set = Force the music set (see below)\n"
175 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
176 " -x = Do not automatically save to config file on exit\n"
177 " -q savegame = Write some information about the savegame and exit\n"
181 /* List the graphics packs */
182 BaseGraphics::GetSetsList (&buf
);
184 /* List the sounds packs */
185 BaseSounds::GetSetsList (&buf
);
187 /* List the music packs */
188 BaseMusic::GetSetsList (&buf
);
190 /* List the drivers */
191 MusicDriver::GetDriversInfo (&buf
);
192 SoundDriver::GetDriversInfo (&buf
);
193 VideoDriver::GetDriversInfo (&buf
);
195 /* List the blitters */
196 Blitter::list (&buf
);
198 /* List the debug facilities. */
199 DumpDebugFacilityNames (&buf
);
201 /* We need to initialize the AI, so it finds the AIs */
203 AI::GetConsoleList (&buf
, true);
204 AI::Uninitialize(true);
206 /* We need to initialize the GameScript, so it finds the GSs */
208 Game::GetConsoleList (&buf
, true);
209 Game::Uninitialize(true);
211 /* ShowInfo put output to stderr, but version information should go
212 * to stdout; this is the only exception */
213 #if !defined(WIN32) && !defined(WIN64)
214 printf("%s\n", buf
.c_str());
216 ShowInfo(buf
.c_str());
220 static void WriteSavegameInfo(const char *name
)
222 uint32 last_ottd_rev
= 0;
223 byte ever_modified
= 0;
224 bool removed_newgrfs
= false;
226 GamelogInfo(&_load_check_data
.gamelog
, &last_ottd_rev
, &ever_modified
, &removed_newgrfs
);
229 buf
.append_fmt ("Name: %s\n", name
);
230 buf
.append_fmt ("Savegame ver: %c%d\n", _load_check_data
.sl_version
.type
== SGT_FTTD
? 'F' : 'O', _load_check_data
.sl_version
.fttd
.version
);
231 buf
.append_fmt ("NewGRF ver: 0x%08X\n", last_ottd_rev
);
232 buf
.append_fmt ("Modified: %d\n", ever_modified
);
234 if (removed_newgrfs
) {
235 buf
.append ("NewGRFs have been removed\n");
238 buf
.append ("NewGRFs:\n");
239 if (_load_check_data
.HasNewGrfs()) {
240 for (GRFConfig
*c
= _load_check_data
.grfconfig
; c
!= NULL
; c
= c
->next
) {
242 md5sumToString (md5sum
, HasBit(c
->flags
, GCF_COMPATIBLE
) ? c
->original_md5sum
: c
->ident
.md5sum
);
243 buf
.append_fmt ("%08X %s %s\n", c
->ident
.grfid
, md5sum
, c
->filename
);
247 /* ShowInfo put output to stderr, but version information should go
248 * to stdout; this is the only exception */
249 #if !defined(WIN32) && !defined(WIN64)
250 printf("%s\n", buf
.c_str());
252 ShowInfo(buf
.c_str());
258 * Extract the resolution from the given string and store
259 * it in the 'res' parameter.
260 * @param res variable to store the resolution in.
261 * @param s the string to decompose.
263 static void ParseResolution(Dimension
*res
, const char *s
)
265 const char *t
= strchr(s
, 'x');
267 ShowInfoF("Invalid resolution '%s'", s
);
271 res
->width
= max(strtoul(s
, NULL
, 0), 64UL);
272 res
->height
= max(strtoul(t
+ 1, NULL
, 0), 64UL);
277 * Unitializes drivers, frees allocated memory, cleans pools, ...
278 * Generally, prepares the game for shutting down
280 static void ShutdownGame()
284 if (_network_available
) NetworkShutDown(); // Shut down the network and close any open connections
286 MusicDriver::ShutdownDriver();
287 SoundDriver::ShutdownDriver();
288 VideoDriver::ShutdownDriver();
290 UnInitWindowSystem();
292 /* stop the scripts */
293 AI::Uninitialize(false);
294 Game::Uninitialize(false);
296 /* Uninitialize variables that are allocated dynamically */
299 #ifdef ENABLE_NETWORK
303 LinkGraphSchedule::Clear();
304 PoolBase::Clean(PT_ALL
);
306 /* No NewGRFs were loaded when it was still bootstrapping. */
307 if (_game_mode
!= GM_BOOTSTRAP
) ResetNewGRFData();
309 /* Close all and any open filehandles */
314 * Load the introduction game.
315 * @param load_newgrfs Whether to load the NewGRFs or not.
317 static void LoadIntroGame(bool load_newgrfs
= true)
319 _game_mode
= GM_MENU
;
321 if (load_newgrfs
) ResetGRFConfig(false);
323 /* Setup main window */
325 SetupColoursAndInitialWindow();
327 /* Load the default opening screen savegame */
328 if (!LoadGame ("opntitle.dat", false, false, BASESET_DIR
)) {
329 GenerateWorld(GWM_EMPTY
, 64, 64); // if failed loading, make empty world.
330 WaitTillGeneratedWorld();
331 SetLocalCompany(COMPANY_SPECTATOR
);
333 SetLocalCompany(COMPANY_FIRST
);
336 _pause_mode
= PM_UNPAUSED
;
337 _cursor
.fix_at
= false;
339 CheckForMissingGlyphs();
341 /* Play main theme */
342 if (MusicDriver::GetActiveDriver()->IsSongPlaying()) ResetMusic();
345 void MakeNewgameSettingsLive()
347 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
348 if (_settings_game
.ai_config
[c
] != NULL
) {
349 delete _settings_game
.ai_config
[c
];
352 if (_settings_game
.game_config
!= NULL
) {
353 delete _settings_game
.game_config
;
356 /* Copy newgame settings to active settings.
357 * Also initialise old settings needed for savegame conversion. */
358 _settings_game
= _settings_newgame
;
359 _old_vds
= _settings_client
.company
.vehicle
;
360 _old_no_servicing_if_no_breakdowns
= true;
362 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
363 _settings_game
.ai_config
[c
] = NULL
;
364 if (_settings_newgame
.ai_config
[c
] != NULL
) {
365 _settings_game
.ai_config
[c
] = new AIConfig(_settings_newgame
.ai_config
[c
]);
368 _settings_game
.game_config
= NULL
;
369 if (_settings_newgame
.game_config
!= NULL
) {
370 _settings_game
.game_config
= new GameConfig(_settings_newgame
.game_config
);
374 void OpenBrowser(const char *url
)
376 /* Make sure we only accept urls that are sure to open a browser. */
377 if (strstr(url
, "http://") != url
&& strstr(url
, "https://") != url
) return;
379 extern void OSOpenBrowser(const char *url
);
383 /** Callback structure of statements to be executed after the NewGRF scan. */
384 struct AfterNewGRFScan
: NewGRFScanCallback
{
385 Year startyear
; ///< The start year.
386 uint generation_seed
; ///< Seed for the new game.
387 char *dedicated_host
; ///< Hostname for the dedicated server.
388 uint16 dedicated_port
; ///< Port for the dedicated server.
389 char *network_conn
; ///< Information about the server to connect to, or NULL.
390 const char *join_server_password
; ///< The password to join the server with.
391 const char *join_company_password
; ///< The password to join the company with.
392 bool *save_config_ptr
; ///< The pointer to the save config setting.
393 bool save_config
; ///< The save config setting.
396 * Create a new callback.
397 * @param save_config_ptr Pointer to the save_config local variable which
398 * decides whether to save of exit or not.
400 AfterNewGRFScan(bool *save_config_ptr
) :
401 startyear(INVALID_YEAR
), generation_seed(GENERATE_NEW_SEED
),
402 dedicated_host(NULL
), dedicated_port(0), network_conn(NULL
),
403 join_server_password(NULL
), join_company_password(NULL
),
404 save_config_ptr(save_config_ptr
), save_config(true)
408 virtual void OnNewGRFsScanned()
410 ResetGRFConfig(false);
412 TarScanner::DoScan(TarScanner::SCENARIO
);
417 /* We want the new (correct) NewGRF count to survive the loading. */
418 uint last_newgrf_count
= _settings_client
.gui
.last_newgrf_count
;
420 _settings_client
.gui
.last_newgrf_count
= last_newgrf_count
;
421 /* Since the default for the palette might have changed due to
422 * reading the configuration file, recalculate that now. */
423 UpdateNewGRFConfigPalette();
425 Game::Uninitialize(true);
426 AI::Uninitialize(true);
429 LoadHotkeysFromConfig();
430 WindowDesc::LoadFromConfig();
432 /* We have loaded the config, so we may possibly save it. */
433 *save_config_ptr
= save_config
;
435 /* restore saved music volume */
436 MusicDriver::GetActiveDriver()->SetVolume(_settings_client
.music
.music_vol
);
438 if (startyear
!= INVALID_YEAR
) _settings_newgame
.game_creation
.starting_year
= startyear
;
439 if (generation_seed
!= GENERATE_NEW_SEED
) _settings_newgame
.game_creation
.generation_seed
= generation_seed
;
441 #if defined(ENABLE_NETWORK)
442 if (dedicated_host
!= NULL
) {
443 _network_bind_list
.Clear();
444 *_network_bind_list
.Append() = xstrdup(dedicated_host
);
446 if (dedicated_port
!= 0) _settings_client
.network
.server_port
= dedicated_port
;
447 #endif /* ENABLE_NETWORK */
449 /* initialize the ingame console */
452 IConsoleCmdExec("exec scripts/autoexec.scr 0");
454 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
455 if (_switch_mode
!= SM_NONE
) MakeNewgameSettingsLive();
457 #ifdef ENABLE_NETWORK
458 if (_network_available
&& network_conn
!= NULL
) {
459 const char *port
= NULL
;
460 const char *company
= NULL
;
461 uint16 rport
= NETWORK_DEFAULT_PORT
;
462 CompanyID join_as
= COMPANY_NEW_COMPANY
;
464 ParseConnectionString(&company
, &port
, network_conn
);
466 if (company
!= NULL
) {
467 join_as
= (CompanyID
)atoi(company
);
469 if (join_as
!= COMPANY_SPECTATOR
) {
471 if (join_as
>= MAX_COMPANIES
) {
477 if (port
!= NULL
) rport
= atoi(port
);
480 _switch_mode
= SM_NONE
;
481 NetworkClientConnectGame(NetworkAddress(network_conn
, rport
), join_as
, join_server_password
, join_company_password
);
483 #endif /* ENABLE_NETWORK */
485 /* After the scan we're not used anymore. */
490 #if defined(UNIX) && !defined(__MORPHOS__)
491 extern void DedicatedFork();
494 /** Options of OpenTTD. */
495 static const OptionData _options
[] = {
496 GETOPT_SHORT_VALUE('I'),
497 GETOPT_SHORT_VALUE('S'),
498 GETOPT_SHORT_VALUE('M'),
499 GETOPT_SHORT_VALUE('m'),
500 GETOPT_SHORT_VALUE('s'),
501 GETOPT_SHORT_VALUE('v'),
502 GETOPT_SHORT_VALUE('b'),
503 #if defined(ENABLE_NETWORK)
504 GETOPT_SHORT_OPTVAL('D'),
505 GETOPT_SHORT_OPTVAL('n'),
506 GETOPT_SHORT_VALUE('l'),
507 GETOPT_SHORT_VALUE('p'),
508 GETOPT_SHORT_VALUE('P'),
509 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
510 GETOPT_SHORT_NOVAL('f'),
512 #endif /* ENABLE_NETWORK */
513 GETOPT_SHORT_VALUE('r'),
514 GETOPT_SHORT_VALUE('t'),
515 GETOPT_SHORT_OPTVAL('d'),
516 GETOPT_SHORT_NOVAL('e'),
517 GETOPT_SHORT_OPTVAL('g'),
518 GETOPT_SHORT_VALUE('G'),
519 GETOPT_SHORT_VALUE('c'),
520 GETOPT_SHORT_NOVAL('x'),
521 GETOPT_SHORT_VALUE('q'),
522 GETOPT_SHORT_NOVAL('h'),
527 * Main entry point for this lovely game.
528 * @param argc The number of arguments passed to this game.
529 * @param argv The values of the arguments.
530 * @return 0 when there is no error.
532 int openttd_main(int argc
, char *argv
[])
534 char *musicdriver
= NULL
;
535 char *sounddriver
= NULL
;
536 char *videodriver
= NULL
;
537 char *blitter
= NULL
;
538 char *graphics_set
= NULL
;
539 char *sounds_set
= NULL
;
540 char *music_set
= NULL
;
541 Dimension resolution
= {0, 0};
542 /* AfterNewGRFScan sets save_config to true after scanning completed. */
543 bool save_config
= false;
544 AfterNewGRFScan
*scanner
= new AfterNewGRFScan(&save_config
);
545 #if defined(ENABLE_NETWORK)
546 bool dedicated
= false;
547 char *debuglog_conn
= NULL
;
549 extern bool _dedicated_forks
;
550 _dedicated_forks
= false;
551 #endif /* ENABLE_NETWORK */
553 _game_mode
= GM_MENU
;
554 _switch_mode
= SM_MENU
;
557 GetOptData
mgo(argc
- 1, argv
+ 1, _options
);
561 while ((i
= mgo
.GetOpt()) != -1) {
563 case 'I': free(graphics_set
); graphics_set
= xstrdup(mgo
.opt
); break;
564 case 'S': free(sounds_set
); sounds_set
= xstrdup(mgo
.opt
); break;
565 case 'M': free(music_set
); music_set
= xstrdup(mgo
.opt
); break;
566 case 'm': free(musicdriver
); musicdriver
= xstrdup(mgo
.opt
); break;
567 case 's': free(sounddriver
); sounddriver
= xstrdup(mgo
.opt
); break;
568 case 'v': free(videodriver
); videodriver
= xstrdup(mgo
.opt
); break;
569 case 'b': free(blitter
); blitter
= xstrdup(mgo
.opt
); break;
570 #if defined(ENABLE_NETWORK)
576 musicdriver
= xstrdup("null");
577 sounddriver
= xstrdup("null");
578 videodriver
= xstrdup("dedicated");
579 blitter
= xstrdup("null");
581 SetDebugString("net=6");
582 if (mgo
.opt
!= NULL
) {
583 /* Use the existing method for parsing (openttd -n).
584 * However, we do ignore the #company part. */
585 const char *temp
= NULL
;
586 const char *port
= NULL
;
587 ParseConnectionString(&temp
, &port
, mgo
.opt
);
588 if (!StrEmpty(mgo
.opt
)) scanner
->dedicated_host
= mgo
.opt
;
589 if (port
!= NULL
) scanner
->dedicated_port
= atoi(port
);
592 case 'f': _dedicated_forks
= true; break;
594 scanner
->network_conn
= mgo
.opt
; // optional IP parameter, NULL if unset
597 debuglog_conn
= mgo
.opt
;
600 scanner
->join_server_password
= mgo
.opt
;
603 scanner
->join_company_password
= mgo
.opt
;
605 #endif /* ENABLE_NETWORK */
606 case 'r': ParseResolution(&resolution
, mgo
.opt
); break;
607 case 't': scanner
->startyear
= atoi(mgo
.opt
); break;
612 if (mgo
.opt
!= NULL
) SetDebugString(mgo
.opt
);
615 case 'e': _switch_mode
= (_switch_mode
== SM_LOAD_GAME
|| _switch_mode
== SM_LOAD_SCENARIO
? SM_LOAD_SCENARIO
: SM_EDITOR
); break;
617 if (mgo
.opt
!= NULL
) {
618 _file_to_saveload
.SetName(mgo
.opt
);
619 bool is_scenario
= _switch_mode
== SM_EDITOR
|| _switch_mode
== SM_LOAD_SCENARIO
;
620 _switch_mode
= is_scenario
? SM_LOAD_SCENARIO
: SM_LOAD_GAME
;
621 _file_to_saveload
.SetMode(SLO_LOAD
, is_scenario
? FT_SCENARIO
: FT_SAVEGAME
, DFT_GAME_FILE
);
623 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
624 const char *t
= strrchr(_file_to_saveload
.name
, '.');
626 FiosType ft
= FiosGetSavegameListCallback(SLO_LOAD
, _file_to_saveload
.name
, t
);
627 if (ft
!= FIOS_TYPE_INVALID
) _file_to_saveload
.SetMode(ft
);
633 _switch_mode
= SM_NEWGAME
;
634 /* Give a random map if no seed has been given */
635 if (scanner
->generation_seed
== GENERATE_NEW_SEED
) {
636 scanner
->generation_seed
= InteractiveRandom();
640 DeterminePaths(argv
[0]);
641 if (StrEmpty(mgo
.opt
)) {
643 goto exit_noshutdown
;
647 FiosGetSavegameListCallback (SLO_LOAD
, mgo
.opt
, strrchr(mgo
.opt
, '.'), &title
);
649 _load_check_data
.Clear();
650 bool res
= LoadGame (mgo
.opt
, true, false, SAVE_DIR
);
651 if (!res
|| _load_check_data
.HasErrors()) {
652 fprintf(stderr
, "Failed to open savegame\n");
653 if (_load_check_data
.HasErrors()) {
655 SetDParamStr(0, _load_check_data
.error
.data
);
656 GetString (buf
, _load_check_data
.error
.str
);
657 fprintf(stderr
, "%s\n", buf
);
659 goto exit_noshutdown
;
662 WriteSavegameInfo (title
.c_str());
664 goto exit_noshutdown
;
666 case 'G': scanner
->generation_seed
= atoi(mgo
.opt
); break;
667 case 'c': free(_config_file
); _config_file
= xstrdup(mgo
.opt
); break;
668 case 'x': scanner
->save_config
= false; break;
670 i
= -2; // Force printing of help.
676 if (i
== -2 || mgo
.numleft
> 0) {
677 /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
678 * In all cases, print the help, and exit.
680 * The next two functions are needed to list the graphics sets. We can't do them earlier
681 * because then we cannot show it on the debug console as that hasn't been configured yet. */
682 DeterminePaths(argv
[0]);
683 TarScanner::DoScan(TarScanner::BASESET
);
684 BaseGraphics::FindSets();
685 BaseSounds::FindSets();
686 BaseMusic::FindSets();
689 goto exit_noshutdown
;
692 #if defined(WINCE) && defined(_DEBUG)
693 /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
697 DeterminePaths(argv
[0]);
698 TarScanner::DoScan(TarScanner::BASESET
);
700 #if defined(ENABLE_NETWORK)
701 if (dedicated
) DEBUG(net
, 0, "Starting dedicated version %s", _openttd_revision
);
702 if (_dedicated_forks
&& !dedicated
) _dedicated_forks
= false;
704 #if defined(UNIX) && !defined(__MORPHOS__)
705 /* We must fork here, or we'll end up without some resources we need (like sockets) */
706 if (_dedicated_forks
) DedicatedFork();
710 LoadFromConfig(true);
712 if (resolution
.width
!= 0) _cur_resolution
= resolution
;
715 * The width and height must be at least 1 pixel and width times
716 * height times bytes per pixel must still fit within a 32 bits
717 * integer, even for 32 bpp video modes. This way all internal
718 * drawing routines work correctly.
720 _cur_resolution
.width
= ClampU(_cur_resolution
.width
, 1, UINT16_MAX
/ 2);
721 _cur_resolution
.height
= ClampU(_cur_resolution
.height
, 1, UINT16_MAX
/ 2);
723 /* Assume the cursor starts within the game as not all video drivers
724 * get an event that the cursor is within the window when it is opened.
725 * Saying the cursor is there makes no visible difference as it would
726 * just be out of the bounds of the window. */
727 _cursor
.in_window
= true;
729 /* enumerate language files */
730 InitializeLanguagePacks();
732 /* Initialize the regular font for FreeType */
735 /* This must be done early, since functions use the SetWindowDirty* calls */
738 BaseGraphics::FindSets();
740 const char *sel
= (graphics_set
!= NULL
) ? graphics_set
: BaseGraphics::ini_set
;
741 if (!BaseGraphics::SetSet (sel
) && !StrEmpty (sel
)) {
742 BaseGraphics::SetSet(NULL
);
744 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND
);
745 msg
.SetDParamStr (0, sel
);
746 ScheduleErrorMessage(msg
);
751 /* Initialize game palette */
754 DEBUG(misc
, 1, "Loading blitter...");
756 const char *sel
= (blitter
!= NULL
) ? blitter
: Blitter::ini
;
757 bool autodetect
= StrEmpty (sel
);
758 Blitter::autodetected
= autodetect
;
759 /* Activate the initial blitter.
760 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
761 * - Never guess anything, if the user specified a blitter. (Blitter::autodetected)
762 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
763 * - Use 8bpp blitter otherwise.
769 bool use_32bpp
= (_support8bpp
== S8BPP_NONE
)
770 || (BaseGraphics::GetUsedSet() != NULL
&& BaseGraphics::GetUsedSet()->blitter
!= BLT_8BPP
);
772 /* Some people reported lack of fullscreen support in
773 * 8 bpp mode. While we prefer 8 bpp since it's
774 * faster, we will still have to test for support. */
775 bool QZ_CanDisplay8bpp();
776 if (!use_32bpp
&& !QZ_CanDisplay8bpp()) {
777 /* The main display can't go to 8 bpp fullscreen mode.
778 * We will have to switch to 32 bpp by default. */
781 #endif /* WITH_COCOA */
782 sel
= use_32bpp
? "32bpp-anim" : "8bpp-optimized";
783 #endif /* DEDICATED */
784 DEBUG(driver
, 1, "Probing blitter %s", sel
);
787 const Blitter::Info
*blitter
= Blitter::find (sel
);
788 if (blitter
== NULL
) {
789 assert (!autodetect
);
790 usererror ("Failed to select requested blitter '%s'; does it exist?", sel
);
792 Blitter::select (blitter
);
796 VideoDriver::SelectDriver ((videodriver
!= NULL
) ? videodriver
: VideoDriver::ini
);
799 NetworkStartUp(); // initialize network-core
801 #if defined(ENABLE_NETWORK)
802 if (debuglog_conn
!= NULL
&& _network_available
) {
803 const char *not_used
= NULL
;
804 const char *port
= NULL
;
807 rport
= NETWORK_DEFAULT_DEBUGLOG_PORT
;
809 ParseConnectionString(¬_used
, &port
, debuglog_conn
);
810 if (port
!= NULL
) rport
= atoi(port
);
812 NetworkStartDebugLog(NetworkAddress(debuglog_conn
, rport
));
814 #endif /* ENABLE_NETWORK */
816 if (!HandleBootstrap()) {
822 VideoDriver::GetActiveDriver()->ClaimMousePointer();
824 /* initialize screenshot formats */
825 InitializeScreenshotFormats();
827 BaseSounds::FindSets();
829 const char *sel
= (sounds_set
!= NULL
) ? sounds_set
: BaseSounds::ini_set
;
830 if (!BaseSounds::SetSet (sel
)) {
831 if (StrEmpty (sel
) || !BaseSounds::SetSet (NULL
)) {
832 usererror ("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
834 ErrorMessageData
msg (STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND
);
835 msg
.SetDParamStr (0, sel
);
836 ScheduleErrorMessage (msg
);
842 BaseMusic::FindSets();
844 const char *sel
= (music_set
!= NULL
) ? music_set
: BaseMusic::ini_set
;
845 if (!BaseMusic::SetSet (sel
)) {
846 if (StrEmpty (sel
) || !BaseMusic::SetSet (NULL
)) {
847 usererror ("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
849 ErrorMessageData
msg (STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND
);
850 msg
.SetDParamStr (0, sel
);
851 ScheduleErrorMessage (msg
);
857 SoundDriver::SelectDriver ((sounddriver
!= NULL
) ? sounddriver
: SoundDriver::ini
);
860 MusicDriver::SelectDriver ((musicdriver
!= NULL
) ? musicdriver
: MusicDriver::ini
);
863 /* Take our initial lock on whatever we might want to do! */
864 _modal_progress_paint_mutex
->BeginCritical();
865 _modal_progress_work_mutex
->BeginCritical();
867 GenerateWorld(GWM_EMPTY
, 64, 64); // Make the viewport initialization happy
868 WaitTillGeneratedWorld();
870 LoadIntroGame(false);
872 CheckForMissingGlyphs();
874 /* ScanNewGRFFiles now has control over the scanner. */
875 ScanNewGRFFiles(scanner
);
878 if (IsExperimentalSavegameVersion()) {
879 ErrorMessageData
msg(STR_WARNING_EXPERIMENTAL_SAVEGAME_VERSION_1
, STR_WARNING_EXPERIMENTAL_SAVEGAME_VERSION_2
);
880 ScheduleErrorMessage(msg
);
883 VideoDriver::GetActiveDriver()->MainLoop();
887 /* only save config if we have to */
890 SaveHotkeysToConfig();
891 WindowDesc::SaveToConfig();
895 /* Reset windowing system, stop drivers, free used memory, ... */
900 /* These three are normally freed before bootstrap. */
906 /* These are normally freed before exit, but after bootstrap. */
913 free(BaseGraphics::ini_set
);
914 free(BaseSounds::ini_set
);
915 free(BaseMusic::ini_set
);
917 free (MusicDriver::ini
);
918 free (SoundDriver::ini
);
919 free (VideoDriver::ini
);
924 #ifdef ENABLE_NETWORK
925 extern FILE *_log_fd
;
926 if (_log_fd
!= NULL
) {
929 #endif /* ENABLE_NETWORK */
934 void HandleExitGameRequest()
936 if (_game_mode
== GM_MENU
|| _game_mode
== GM_BOOTSTRAP
) { // do not ask to quit on the main screen
938 } else if (_settings_client
.gui
.autosave_on_exit
) {
946 static void MakeNewGameDone()
948 SettingsDisableElrail(_settings_game
.vehicle
.disable_elrails
);
950 /* In a dedicated server, the server does not play */
951 if (!VideoDriver::GetActiveDriver()->HasGUI()) {
952 SetLocalCompany(COMPANY_SPECTATOR
);
953 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
954 IConsoleCmdExec("exec scripts/game_start.scr 0");
958 /* Create a single company */
959 DoStartupNewCompany(false);
961 Company
*c
= Company::Get(COMPANY_FIRST
);
962 c
->settings
= _settings_client
.company
;
964 IConsoleCmdExec("exec scripts/game_start.scr 0");
966 SetLocalCompany(COMPANY_FIRST
);
970 #ifdef ENABLE_NETWORK
971 /* We are the server, we start a new company (not dedicated),
972 * so set the default password *if* needed. */
973 if (_network_server
&& !StrEmpty(_settings_client
.network
.default_company_pass
)) {
974 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
976 #endif /* ENABLE_NETWORK */
978 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
982 MarkWholeScreenDirty();
985 static void MakeNewGame(bool from_heightmap
, bool reset_settings
)
987 _game_mode
= GM_NORMAL
;
989 ResetGRFConfig(true);
991 GenerateWorldSetCallback(&MakeNewGameDone
);
992 GenerateWorld(from_heightmap
? GWM_HEIGHTMAP
: GWM_NEWGAME
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
, reset_settings
);
995 static void MakeNewEditorWorldDone()
997 SetLocalCompany(OWNER_NONE
);
1000 static void MakeNewEditorWorld()
1002 _game_mode
= GM_EDITOR
;
1004 ResetGRFConfig(true);
1006 GenerateWorldSetCallback(&MakeNewEditorWorldDone
);
1007 GenerateWorld(GWM_EMPTY
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1011 * Load the specified savegame but on error do different things.
1012 * If loading fails due to corrupt savegame, bad version, etc. go back to
1013 * a previous correct state. In the menu for example load the intro game again.
1014 * @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
1015 * @param newgm switch to this mode of loading fails due to some unknown error
1016 * @param filename file to be loaded
1017 * @param subdir default directory to look for filename, set to 0 if not needed
1018 * @param lf Load filter to use, if NULL: use filename + subdir.
1020 bool SafeLoad (const char *filename
, DetailedFileType dft
, GameMode newgm
, Subdirectory subdir
, struct LoadFilter
*lf
= NULL
)
1022 assert(dft
== DFT_GAME_FILE
|| (lf
== NULL
&& dft
== DFT_OLD_GAME_FILE
));
1023 GameMode ogm
= _game_mode
;
1027 if (lf
== NULL
? LoadGame (filename
, false, dft
== DFT_OLD_GAME_FILE
, subdir
) : LoadWithFilter (lf
)) {
1030 #ifdef ENABLE_NETWORK
1031 if (_network_dedicated
) {
1033 * We need to reinit a network map...
1034 * We can't simply load the intro game here as that game has many
1035 * special cases which make clients desync immediately. So we fall
1036 * back to just generating a new game with the current settings.
1038 DEBUG(net
, 0, "Loading game failed, so a new (random) game will be started!");
1039 MakeNewGame(false, true);
1042 if (_network_server
) {
1043 /* We can't load the intro game as server, so disconnect first. */
1044 NetworkDisconnect();
1046 #endif /* ENABLE_NETWORK */
1050 case GM_MENU
: LoadIntroGame(); break;
1051 case GM_EDITOR
: MakeNewEditorWorld(); break;
1057 void SwitchToMode(SwitchMode new_mode
)
1059 #ifdef ENABLE_NETWORK
1060 /* If we are saving something, the network stays in his current state */
1061 if (new_mode
!= SM_SAVE_GAME
) {
1062 /* If the network is active, make it not-active */
1064 if (_network_server
&& (new_mode
== SM_LOAD_GAME
|| new_mode
== SM_NEWGAME
|| new_mode
== SM_RESTARTGAME
)) {
1067 NetworkDisconnect();
1071 /* If we are a server, we restart the server */
1072 if (_is_network_server
) {
1073 /* But not if we are going to the menu */
1074 if (new_mode
!= SM_MENU
) {
1075 /* check if we should reload the config */
1076 if (_settings_client
.network
.reload_cfg
) {
1078 MakeNewgameSettingsLive();
1079 ResetGRFConfig(false);
1081 NetworkServerStart();
1083 /* This client no longer wants to be a network-server */
1084 _is_network_server
= false;
1088 #endif /* ENABLE_NETWORK */
1089 /* Make sure all AI controllers are gone at quitting game */
1090 if (new_mode
!= SM_SAVE_GAME
) AI::KillAll();
1093 case SM_EDITOR
: // Switch to scenario editor
1094 MakeNewEditorWorld();
1097 case SM_RESTARTGAME
: // Restart --> 'Random game' with current settings
1098 case SM_NEWGAME
: // New Game --> 'Random game'
1099 #ifdef ENABLE_NETWORK
1100 if (_network_server
) {
1101 bstrcpy (_network_game_info
.map_name
, "Random Map");
1103 #endif /* ENABLE_NETWORK */
1104 MakeNewGame(false, new_mode
== SM_NEWGAME
);
1107 case SM_LOAD_GAME
: { // Load game, Play Scenario
1108 ResetGRFConfig(true);
1109 ResetWindowSystem();
1111 assert (_file_to_saveload
.file_op
== SLO_LOAD
);
1112 if (!SafeLoad (_file_to_saveload
.name
, _file_to_saveload
.detail_ftype
, GM_NORMAL
, NO_DIRECTORY
)) {
1113 ShowSaveLoadErrorMessage (false);
1115 if (_file_to_saveload
.abstract_ftype
== FT_SCENARIO
) {
1116 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1117 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1119 /* Update the local company for a loaded game. It is either always
1120 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1121 SetLocalCompany(_network_dedicated
? COMPANY_SPECTATOR
: COMPANY_FIRST
);
1122 /* Execute the game-start script */
1123 IConsoleCmdExec("exec scripts/game_start.scr 0");
1124 /* Decrease pause counter (was increased from opening load dialog) */
1125 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1126 #ifdef ENABLE_NETWORK
1127 if (_network_server
) {
1128 bstrfmt (_network_game_info
.map_name
, "%s (Loaded game)", _file_to_saveload
.title
);
1130 #endif /* ENABLE_NETWORK */
1135 case SM_START_HEIGHTMAP
: // Load a heightmap and start a new game from it
1136 #ifdef ENABLE_NETWORK
1137 if (_network_server
) {
1138 bstrfmt (_network_game_info
.map_name
, "%s (Heightmap)", _file_to_saveload
.title
);
1140 #endif /* ENABLE_NETWORK */
1141 MakeNewGame(true, true);
1144 case SM_LOAD_HEIGHTMAP
: // Load heightmap from scenario editor
1145 SetLocalCompany(OWNER_NONE
);
1147 GenerateWorld(GWM_HEIGHTMAP
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1148 MarkWholeScreenDirty();
1151 case SM_LOAD_SCENARIO
: { // Load scenario from scenario editor
1152 assert (_file_to_saveload
.file_op
== SLO_LOAD
);
1153 if (SafeLoad (_file_to_saveload
.name
, _file_to_saveload
.detail_ftype
, GM_EDITOR
, NO_DIRECTORY
)) {
1154 SetLocalCompany(OWNER_NONE
);
1155 _settings_newgame
.game_creation
.starting_year
= _cur_year
;
1156 /* Cancel the saveload pausing */
1157 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1159 ShowSaveLoadErrorMessage (false);
1164 case SM_MENU
: // Switch to game intro menu
1166 if (BaseSounds::ini_set
== NULL
&& BaseSounds::GetUsedSet()->fallback
) {
1167 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET
, INVALID_STRING_ID
, WL_CRITICAL
);
1168 BaseSounds::ini_set
= xstrdup(BaseSounds::GetUsedSet()->get_name());
1172 case SM_SAVE_GAME
: // Save game.
1173 /* Make network saved games on pause compatible to singleplayer */
1174 if (!SaveGame(_file_to_saveload
.name
, NO_DIRECTORY
)) {
1175 ShowSaveLoadErrorMessage (true);
1177 DeleteWindowById(WC_SAVELOAD
, 0);
1181 case SM_SAVE_HEIGHTMAP
: // Save heightmap.
1182 MakeHeightmapScreenshot(_file_to_saveload
.name
);
1183 DeleteWindowById(WC_SAVELOAD
, 0);
1186 case SM_GENRANDLAND
: // Generate random land within scenario editor
1187 SetLocalCompany(OWNER_NONE
);
1188 GenerateWorld(GWM_RANDOM
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1190 MarkWholeScreenDirty();
1193 default: NOT_REACHED();
1199 * Check the validity of some of the caches.
1200 * Especially in the sense of desyncs between
1201 * the cached value and what the value would
1202 * be when calculated from the 'base' data.
1204 static void CheckCaches()
1206 /* Return here so it is easy to add checks that are run
1207 * always to aid testing of caches. */
1208 if (_debug_desync_level
<= 1) return;
1210 /* Check the town caches. */
1211 SmallVector
<TownCache
, 4> old_town_caches
;
1214 MemCpyT(old_town_caches
.Append(), &t
->cache
);
1217 extern void RebuildTownCaches();
1218 RebuildTownCaches();
1219 RebuildSubsidisedSourceAndDestinationCache();
1223 if (MemCmpT(old_town_caches
.Get(i
), &t
->cache
) != 0) {
1224 DEBUG(desync
, 2, "town cache mismatch: town %i", (int)t
->index
);
1229 /* Check company infrastructure cache. */
1230 SmallVector
<CompanyInfrastructure
, 4> old_infrastructure
;
1232 FOR_ALL_COMPANIES(c
) MemCpyT(old_infrastructure
.Append(), &c
->infrastructure
);
1234 extern void AfterLoadCompanyStats();
1235 AfterLoadCompanyStats();
1238 FOR_ALL_COMPANIES(c
) {
1239 if (MemCmpT(old_infrastructure
.Get(i
), &c
->infrastructure
) != 0) {
1240 DEBUG(desync
, 2, "infrastructure cache mismatch: company %i", (int)c
->index
);
1245 /* Strict checking of the road stop cache entries */
1247 FOR_ALL_ROADSTOPS(rs
) {
1248 if (!IsStandardRoadStopTile(rs
->xy
)) rs
->CheckIntegrity();
1252 FOR_ALL_VEHICLES(v
) {
1253 extern void FillNewGRFVehicleCache(const Vehicle
*v
);
1254 if (v
!= v
->First() || v
->vehstatus
& VS_CRASHED
|| !v
->IsPrimaryVehicle()) continue;
1257 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) length
++;
1259 NewGRFCache
*grf_cache
= xcalloct
<NewGRFCache
>(length
);
1260 VehicleCache
*veh_cache
= xcalloct
<VehicleCache
>(length
);
1261 GroundVehicleCache
*gro_cache
= xcalloct
<GroundVehicleCache
>(length
);
1262 TrainCache
*tra_cache
= xcalloct
<TrainCache
>(length
);
1265 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
1266 FillNewGRFVehicleCache(u
);
1267 grf_cache
[length
] = u
->grf_cache
;
1268 veh_cache
[length
] = u
->vcache
;
1271 gro_cache
[length
] = Train::From(u
)->gcache
;
1272 tra_cache
[length
] = Train::From(u
)->tcache
;
1275 gro_cache
[length
] = RoadVehicle::From(u
)->gcache
;
1284 case VEH_TRAIN
: Train::From(v
)->ConsistChanged(CCF_TRACK
); break;
1285 case VEH_ROAD
: RoadVehUpdateCache(RoadVehicle::From(v
)); break;
1286 case VEH_AIRCRAFT
: UpdateAircraftCache(Aircraft::From(v
)); break;
1287 case VEH_SHIP
: Ship::From(v
)->UpdateCache(); break;
1292 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
1293 FillNewGRFVehicleCache(u
);
1294 if (memcmp(&grf_cache
[length
], &u
->grf_cache
, sizeof(NewGRFCache
)) != 0) {
1295 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
);
1297 if (memcmp(&veh_cache
[length
], &u
->vcache
, sizeof(VehicleCache
)) != 0) {
1298 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
);
1302 if (memcmp(&gro_cache
[length
], &Train::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1303 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
);
1305 if (memcmp(&tra_cache
[length
], &Train::From(u
)->tcache
, sizeof(TrainCache
)) != 0) {
1306 DEBUG(desync
, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1310 if (memcmp(&gro_cache
[length
], &RoadVehicle::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1311 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
);
1326 /* Check whether the caches are still valid */
1327 FOR_ALL_VEHICLES(v
) {
1328 byte buff
[sizeof(VehicleCargoList
)];
1329 memcpy(buff
, &v
->cargo
, sizeof(VehicleCargoList
));
1330 v
->cargo
.InvalidateCache();
1331 assert(memcmp(&v
->cargo
, buff
, sizeof(VehicleCargoList
)) == 0);
1335 FOR_ALL_STATIONS(st
) {
1336 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
1337 byte buff
[sizeof(StationCargoList
)];
1338 memcpy(buff
, &st
->goods
[c
].cargo
, sizeof(StationCargoList
));
1339 st
->goods
[c
].cargo
.InvalidateCache();
1340 assert(memcmp(&st
->goods
[c
].cargo
, buff
, sizeof(StationCargoList
)) == 0);
1346 * State controlling game loop.
1347 * The state must not be changed from anywhere but here.
1348 * That check is enforced in DoCommand.
1350 void StateGameLoop()
1352 /* don't execute the state loop during pause */
1353 if (_pause_mode
!= PM_UNPAUSED
) {
1354 UpdateLandscapingLimits();
1355 #ifndef DEBUG_DUMP_COMMANDS
1358 CallWindowTickEvent();
1361 if (HasModalProgress()) return;
1363 Layouter::ReduceLineCache();
1365 if (_game_mode
== GM_EDITOR
) {
1366 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1369 CallLandscapeTick();
1370 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1371 UpdateLandscapingLimits();
1373 CallWindowTickEvent();
1376 if (_debug_desync_level
> 2 && _date_fract
== 0 && (_date
& 0x1F) == 0) {
1377 /* Save the desync savegame if needed. */
1378 char name
[MAX_PATH
];
1379 bstrfmt (name
, "dmp_cmds_%08x_%08x.sav", _settings_game
.game_creation
.generation_seed
, _date
);
1380 SaveGame(name
, AUTOSAVE_DIR
, false);
1385 /* All these actions has to be done from OWNER_NONE
1386 * for multiplayer compatibility */
1387 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
1389 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1390 AnimateAnimatedTiles();
1394 CallLandscapeTick();
1395 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1397 #ifndef DEBUG_DUMP_COMMANDS
1401 UpdateLandscapingLimits();
1403 CallWindowTickEvent();
1405 cur_company
.Restore();
1408 assert(IsLocalCompany());
1412 * Create an autosave. The default name is "autosave#.sav". However with
1413 * the setting 'keep_all_autosave' the name defaults to company-name + date
1415 static void DoAutosave()
1417 sstring
<MAX_PATH
> buf
;
1420 /* Autosaving in networking is too time expensive for the PSP */
1421 if (_networking
) return;
1424 if (_settings_client
.gui
.keep_all_autosave
) {
1425 GenerateDefaultSaveName (&buf
);
1426 buf
.append (".sav");
1428 static int _autosave_ctr
= 0;
1430 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1431 buf
.fmt ("autosave%d.sav", _autosave_ctr
);
1433 if (++_autosave_ctr
>= _settings_client
.gui
.max_num_autosaves
) _autosave_ctr
= 0;
1436 DEBUG(sl
, 2, "Autosaving to '%s'", buf
.c_str());
1437 if (!SaveGame(buf
.c_str(), AUTOSAVE_DIR
)) {
1438 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED
, INVALID_STRING_ID
, WL_ERROR
);
1444 if (_game_mode
== GM_BOOTSTRAP
) {
1445 #ifdef ENABLE_NETWORK
1446 /* Check for UDP stuff */
1447 if (_network_available
) NetworkBackgroundLoop();
1453 ProcessAsyncSaveFinish();
1455 /* autosave game? */
1458 _do_autosave
= false;
1459 SetWindowDirty(WC_STATUS_BAR
, 0);
1462 /* switch game mode? */
1463 if (_switch_mode
!= SM_NONE
&& !HasModalProgress()) {
1464 SwitchToMode(_switch_mode
);
1465 _switch_mode
= SM_NONE
;
1468 IncreaseSpriteLRU();
1469 InteractiveRandom();
1471 extern int _caret_timer
;
1475 #ifdef ENABLE_NETWORK
1476 /* Check for UDP stuff */
1477 if (_network_available
) NetworkBackgroundLoop();
1479 if (_networking
&& !HasModalProgress()) {
1483 if (_network_reconnect
> 0 && --_network_reconnect
== 0) {
1484 /* This means that we want to reconnect to the last host
1485 * We do this here, because it means that the network is really closed */
1486 NetworkClientConnectGame(NetworkAddress(_settings_client
.network
.last_host
, _settings_client
.network
.last_port
), COMPANY_SPECTATOR
);
1492 /* Check chat messages roughly once a second. */
1493 static uint check_message
= 0;
1494 if (++check_message
> 1000 / MILLISECONDS_PER_TICK
) {
1496 NetworkChatMessageLoop();
1500 #endif /* ENABLE_NETWORK */
1502 if (!_pause_mode
&& HasBit(_display_opt
, DO_FULL_ANIMATION
)) DoPaletteAnimations();
1504 if (!_pause_mode
|| _game_mode
== GM_EDITOR
|| _settings_game
.construction
.command_pause_level
> CMDPL_NO_CONSTRUCTION
) MoveAllTextEffects();
1508 SoundDriver::GetActiveDriver()->MainLoop();