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 void CallLandscapeTick();
73 void DoPaletteAnimations();
76 void CallWindowTickEvent();
77 bool HandleBootstrap();
79 extern Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
);
80 extern void ShowOSErrorBox(const char *buf
, bool system
);
81 extern char *_config_file
;
84 * Error handling for fatal user errors.
85 * @param s the string to print.
86 * @note Does NEVER return.
88 void CDECL
usererror(const char *s
, ...)
94 vsnprintf(buf
, lengthof(buf
), s
, va
);
97 ShowOSErrorBox(buf
, false);
98 if (_video_driver
!= NULL
) _video_driver
->Stop();
104 * Error handling for fatal non-user errors.
105 * @param s the string to print.
106 * @note Does NEVER return.
108 void CDECL
error(const char *s
, ...)
114 vsnprintf(buf
, lengthof(buf
), s
, va
);
117 ShowOSErrorBox(buf
, true);
119 /* Set the error message for the crash log and then invoke it. */
120 CrashLog::SetErrorMessage(buf
);
125 * Shows some information on the console/a popup box depending on the OS.
126 * @param str the text to show.
128 void CDECL
ShowInfoF(const char *str
, ...)
133 vsnprintf(buf
, lengthof(buf
), str
, va
);
139 * Show the help message when someone passed a wrong parameter.
141 static void ShowHelp()
146 p
+= seprintf(p
, lastof(buf
), "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"
182 /* List the graphics packs */
183 p
= BaseGraphics::GetSetsList(p
, lastof(buf
));
185 /* List the sounds packs */
186 p
= BaseSounds::GetSetsList(p
, lastof(buf
));
188 /* List the music packs */
189 p
= BaseMusic::GetSetsList(p
, lastof(buf
));
191 /* List the drivers */
192 p
= DriverFactoryBase::GetDriversInfo(p
, lastof(buf
));
194 /* List the blitters */
195 p
= BlitterFactory::GetBlittersInfo(p
, lastof(buf
));
197 /* List the debug facilities. */
198 p
= DumpDebugFacilityNames(p
, lastof(buf
));
200 /* We need to initialize the AI, so it finds the AIs */
202 p
= AI::GetConsoleList(p
, lastof(buf
), true);
203 AI::Uninitialize(true);
205 /* We need to initialize the GameScript, so it finds the GSs */
207 p
= Game::GetConsoleList(p
, lastof(buf
), true);
208 Game::Uninitialize(true);
210 /* ShowInfo put output to stderr, but version information should go
211 * to stdout; this is the only exception */
212 #if !defined(WIN32) && !defined(WIN64)
219 static void WriteSavegameInfo(const char *name
)
221 uint32 last_ottd_rev
= 0;
222 byte ever_modified
= 0;
223 bool removed_newgrfs
= false;
225 GamelogInfo(&_load_check_data
.gamelog
, &last_ottd_rev
, &ever_modified
, &removed_newgrfs
);
229 p
+= seprintf(p
, lastof(buf
), "Name: %s\n", name
);
230 p
+= seprintf(p
, lastof(buf
), "Savegame ver: %c%d\n", _load_check_data
.sl_version
.type
== SGT_FTTD
? 'F' : 'O', _load_check_data
.sl_version
.fttd
.version
);
231 p
+= seprintf(p
, lastof(buf
), "NewGRF ver: 0x%08X\n", last_ottd_rev
);
232 p
+= seprintf(p
, lastof(buf
), "Modified: %d\n", ever_modified
);
234 if (removed_newgrfs
) {
235 p
+= seprintf(p
, lastof(buf
), "NewGRFs have been removed\n");
238 p
= strecpy(p
, "NewGRFs:\n", lastof(buf
));
239 if (_load_check_data
.HasNewGrfs()) {
240 for (GRFConfig
*c
= _load_check_data
.grfconfig
; c
!= NULL
; c
= c
->next
) {
242 md5sumToString(md5sum
, lastof(md5sum
), HasBit(c
->flags
, GCF_COMPATIBLE
) ? c
->original_md5sum
: c
->ident
.md5sum
);
243 p
+= seprintf(p
, lastof(buf
), "%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)
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 DriverFactoryBase::ShutdownDrivers();
288 UnInitWindowSystem();
290 /* stop the scripts */
291 AI::Uninitialize(false);
292 Game::Uninitialize(false);
294 /* Uninitialize variables that are allocated dynamically */
297 #ifdef ENABLE_NETWORK
301 LinkGraphSchedule::Clear();
302 PoolBase::Clean(PT_ALL
);
304 /* No NewGRFs were loaded when it was still bootstrapping. */
305 if (_game_mode
!= GM_BOOTSTRAP
) ResetNewGRFData();
307 /* 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", SL_LOAD
, 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 if (load_newgrfs
) CheckForMissingSprites();
340 CheckForMissingGlyphs();
342 /* Play main theme */
343 if (_music_driver
->IsSongPlaying()) ResetMusic();
346 void MakeNewgameSettingsLive()
348 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
349 if (_settings_game
.ai_config
[c
] != NULL
) {
350 delete _settings_game
.ai_config
[c
];
353 if (_settings_game
.game_config
!= NULL
) {
354 delete _settings_game
.game_config
;
357 /* Copy newgame settings to active settings.
358 * Also initialise old settings needed for savegame conversion. */
359 _settings_game
= _settings_newgame
;
360 _old_vds
= _settings_client
.company
.vehicle
;
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 _music_driver
->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() = strdup(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
= strdup(mgo
.opt
); break;
564 case 'S': free(sounds_set
); sounds_set
= strdup(mgo
.opt
); break;
565 case 'M': free(music_set
); music_set
= strdup(mgo
.opt
); break;
566 case 'm': free(musicdriver
); musicdriver
= strdup(mgo
.opt
); break;
567 case 's': free(sounddriver
); sounddriver
= strdup(mgo
.opt
); break;
568 case 'v': free(videodriver
); videodriver
= strdup(mgo
.opt
); break;
569 case 'b': free(blitter
); blitter
= strdup(mgo
.opt
); break;
570 #if defined(ENABLE_NETWORK)
576 musicdriver
= strdup("null");
577 sounddriver
= strdup("null");
578 videodriver
= strdup("dedicated");
579 blitter
= strdup("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 strecpy(_file_to_saveload
.name
, mgo
.opt
, lastof(_file_to_saveload
.name
));
619 _switch_mode
= (_switch_mode
== SM_EDITOR
|| _switch_mode
== SM_LOAD_SCENARIO
? SM_LOAD_SCENARIO
: SM_LOAD_GAME
);
620 _file_to_saveload
.mode
= SL_LOAD
;
622 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
623 const char *t
= strrchr(_file_to_saveload
.name
, '.');
625 FiosType ft
= FiosGetSavegameListCallback(SLD_LOAD_GAME
, _file_to_saveload
.name
, t
, NULL
, NULL
);
626 if (ft
!= FIOS_TYPE_INVALID
) SetFiosType(ft
);
632 _switch_mode
= SM_NEWGAME
;
633 /* Give a random map if no seed has been given */
634 if (scanner
->generation_seed
== GENERATE_NEW_SEED
) {
635 scanner
->generation_seed
= InteractiveRandom();
639 DeterminePaths(argv
[0]);
640 if (StrEmpty(mgo
.opt
)) {
642 goto exit_noshutdown
;
647 FiosGetSavegameListCallback(SLD_LOAD_GAME
, mgo
.opt
, strrchr(mgo
.opt
, '.'), title
, lastof(title
));
649 _load_check_data
.Clear();
650 bool res
= LoadGame(mgo
.opt
, SL_LOAD_CHECK
, 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
, lastof(buf
));
657 fprintf(stderr
, "%s\n", buf
);
659 goto exit_noshutdown
;
662 WriteSavegameInfo(title
);
664 goto exit_noshutdown
;
666 case 'G': scanner
->generation_seed
= atoi(mgo
.opt
); break;
667 case 'c': _config_file
= strdup(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();
739 if (graphics_set
== NULL
&& BaseGraphics::ini_set
!= NULL
) graphics_set
= strdup(BaseGraphics::ini_set
);
740 if (!BaseGraphics::SetSet(graphics_set
)) {
741 if (!StrEmpty(graphics_set
)) {
742 BaseGraphics::SetSet(NULL
);
744 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND
);
745 msg
.SetDParamStr(0, graphics_set
);
746 ScheduleErrorMessage(msg
);
751 /* Initialize game palette */
754 DEBUG(misc
, 1, "Loading blitter...");
755 if (blitter
== NULL
&& _ini_blitter
!= NULL
) blitter
= strdup(_ini_blitter
);
756 _blitter_autodetected
= StrEmpty(blitter
);
757 /* If we have a 32 bpp base set, try to select the 32 bpp blitter first, but only if we autoprobe the blitter. */
758 if (!_blitter_autodetected
|| BaseGraphics::GetUsedSet() == NULL
|| BaseGraphics::GetUsedSet()->blitter
== BLT_8BPP
|| BlitterFactory::SelectBlitter("32bpp-anim") == NULL
) {
759 if (BlitterFactory::SelectBlitter(blitter
) == NULL
) {
761 usererror("Failed to autoprobe blitter") :
762 usererror("Failed to select requested blitter '%s'; does it exist?", blitter
);
767 if (videodriver
== NULL
&& _ini_videodriver
!= NULL
) videodriver
= strdup(_ini_videodriver
);
768 _video_driver
= (VideoDriver
*)DriverFactoryBase::SelectDriver(videodriver
, Driver::DT_VIDEO
);
769 if (_video_driver
== NULL
) {
770 StrEmpty(videodriver
) ?
771 usererror("Failed to autoprobe video driver") :
772 usererror("Failed to select requested video driver '%s'", videodriver
);
776 InitializeSpriteSorter();
778 /* Initialize the zoom level of the screen to normal */
779 _screen
.zoom
= ZOOM_LVL_NORMAL
;
781 NetworkStartUp(); // initialize network-core
783 #if defined(ENABLE_NETWORK)
784 if (debuglog_conn
!= NULL
&& _network_available
) {
785 const char *not_used
= NULL
;
786 const char *port
= NULL
;
789 rport
= NETWORK_DEFAULT_DEBUGLOG_PORT
;
791 ParseConnectionString(¬_used
, &port
, debuglog_conn
);
792 if (port
!= NULL
) rport
= atoi(port
);
794 NetworkStartDebugLog(NetworkAddress(debuglog_conn
, rport
));
796 #endif /* ENABLE_NETWORK */
798 if (!HandleBootstrap()) {
804 _video_driver
->ClaimMousePointer();
806 /* initialize screenshot formats */
807 InitializeScreenshotFormats();
809 BaseSounds::FindSets();
810 if (sounds_set
== NULL
&& BaseSounds::ini_set
!= NULL
) sounds_set
= strdup(BaseSounds::ini_set
);
811 if (!BaseSounds::SetSet(sounds_set
)) {
812 if (StrEmpty(sounds_set
) || !BaseSounds::SetSet(NULL
)) {
813 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
815 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND
);
816 msg
.SetDParamStr(0, sounds_set
);
817 ScheduleErrorMessage(msg
);
822 BaseMusic::FindSets();
823 if (music_set
== NULL
&& BaseMusic::ini_set
!= NULL
) music_set
= strdup(BaseMusic::ini_set
);
824 if (!BaseMusic::SetSet(music_set
)) {
825 if (StrEmpty(music_set
) || !BaseMusic::SetSet(NULL
)) {
826 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
828 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND
);
829 msg
.SetDParamStr(0, music_set
);
830 ScheduleErrorMessage(msg
);
835 if (sounddriver
== NULL
&& _ini_sounddriver
!= NULL
) sounddriver
= strdup(_ini_sounddriver
);
836 _sound_driver
= (SoundDriver
*)DriverFactoryBase::SelectDriver(sounddriver
, Driver::DT_SOUND
);
837 if (_sound_driver
== NULL
) {
838 StrEmpty(sounddriver
) ?
839 usererror("Failed to autoprobe sound driver") :
840 usererror("Failed to select requested sound driver '%s'", sounddriver
);
844 if (musicdriver
== NULL
&& _ini_musicdriver
!= NULL
) musicdriver
= strdup(_ini_musicdriver
);
845 _music_driver
= (MusicDriver
*)DriverFactoryBase::SelectDriver(musicdriver
, Driver::DT_MUSIC
);
846 if (_music_driver
== NULL
) {
847 StrEmpty(musicdriver
) ?
848 usererror("Failed to autoprobe music driver") :
849 usererror("Failed to select requested music driver '%s'", musicdriver
);
853 /* Take our initial lock on whatever we might want to do! */
854 _modal_progress_paint_mutex
->BeginCritical();
855 _modal_progress_work_mutex
->BeginCritical();
857 GenerateWorld(GWM_EMPTY
, 64, 64); // Make the viewport initialization happy
858 WaitTillGeneratedWorld();
860 LoadIntroGame(false);
862 CheckForMissingGlyphs();
864 /* ScanNewGRFFiles now has control over the scanner. */
865 ScanNewGRFFiles(scanner
);
868 if (IsExperimentalSavegameVersion()) {
869 ErrorMessageData
msg(STR_WARNING_EXPERIMENTAL_SAVEGAME_VERSION_1
, STR_WARNING_EXPERIMENTAL_SAVEGAME_VERSION_2
);
870 ScheduleErrorMessage(msg
);
873 _video_driver
->MainLoop();
877 /* only save config if we have to */
880 SaveHotkeysToConfig();
881 WindowDesc::SaveToConfig();
885 /* Reset windowing system, stop drivers, free used memory, ... */
890 /* These three are normally freed before bootstrap. */
896 /* These are normally freed before exit, but after bootstrap. */
903 free(BaseGraphics::ini_set
);
904 free(BaseSounds::ini_set
);
905 free(BaseMusic::ini_set
);
907 free(_ini_musicdriver
);
908 free(_ini_sounddriver
);
909 free(_ini_videodriver
);
914 #ifdef ENABLE_NETWORK
915 extern FILE *_log_fd
;
916 if (_log_fd
!= NULL
) {
919 #endif /* ENABLE_NETWORK */
924 void HandleExitGameRequest()
926 if (_game_mode
== GM_MENU
|| _game_mode
== GM_BOOTSTRAP
) { // do not ask to quit on the main screen
928 } else if (_settings_client
.gui
.autosave_on_exit
) {
936 static void MakeNewGameDone()
938 SettingsDisableElrail(_settings_game
.vehicle
.disable_elrails
);
940 /* In a dedicated server, the server does not play */
941 if (!_video_driver
->HasGUI()) {
942 SetLocalCompany(COMPANY_SPECTATOR
);
943 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
944 IConsoleCmdExec("exec scripts/game_start.scr 0");
948 /* Create a single company */
949 DoStartupNewCompany(false);
951 Company
*c
= Company::Get(COMPANY_FIRST
);
952 c
->settings
= _settings_client
.company
;
954 IConsoleCmdExec("exec scripts/game_start.scr 0");
956 SetLocalCompany(COMPANY_FIRST
);
960 #ifdef ENABLE_NETWORK
961 /* We are the server, we start a new company (not dedicated),
962 * so set the default password *if* needed. */
963 if (_network_server
&& !StrEmpty(_settings_client
.network
.default_company_pass
)) {
964 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
966 #endif /* ENABLE_NETWORK */
968 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
971 MarkWholeScreenDirty();
974 static void MakeNewGame(bool from_heightmap
, bool reset_settings
)
976 _game_mode
= GM_NORMAL
;
978 ResetGRFConfig(true);
980 GenerateWorldSetCallback(&MakeNewGameDone
);
981 GenerateWorld(from_heightmap
? GWM_HEIGHTMAP
: GWM_NEWGAME
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
, reset_settings
);
984 static void MakeNewEditorWorldDone()
986 SetLocalCompany(OWNER_NONE
);
989 static void MakeNewEditorWorld()
991 _game_mode
= GM_EDITOR
;
993 ResetGRFConfig(true);
995 GenerateWorldSetCallback(&MakeNewEditorWorldDone
);
996 GenerateWorld(GWM_EMPTY
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1000 * Load the specified savegame but on error do different things.
1001 * If loading fails due to corrupt savegame, bad version, etc. go back to
1002 * a previous correct state. In the menu for example load the intro game again.
1003 * @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
1004 * @param newgm switch to this mode of loading fails due to some unknown error
1005 * @param filename file to be loaded
1006 * @param subdir default directory to look for filename, set to 0 if not needed
1007 * @param lf Load filter to use, if NULL: use filename + subdir.
1009 bool SafeLoad(const char *filename
, int mode
, GameMode newgm
, Subdirectory subdir
, struct LoadFilter
*lf
= NULL
)
1011 assert(mode
== SL_LOAD
|| (lf
== NULL
&& mode
== SL_OLD_LOAD
));
1012 GameMode ogm
= _game_mode
;
1016 if (lf
== NULL
? LoadGame(filename
, mode
, subdir
) : LoadWithFilter(lf
)) {
1019 #ifdef ENABLE_NETWORK
1020 if (_network_dedicated
) {
1022 * We need to reinit a network map...
1023 * We can't simply load the intro game here as that game has many
1024 * special cases which make clients desync immediately. So we fall
1025 * back to just generating a new game with the current settings.
1027 DEBUG(net
, 0, "Loading game failed, so a new (random) game will be started!");
1028 MakeNewGame(false, true);
1031 if (_network_server
) {
1032 /* We can't load the intro game as server, so disconnect first. */
1033 NetworkDisconnect();
1035 #endif /* ENABLE_NETWORK */
1039 case GM_MENU
: LoadIntroGame(); break;
1040 case GM_EDITOR
: MakeNewEditorWorld(); break;
1046 void SwitchToMode(SwitchMode new_mode
)
1048 #ifdef ENABLE_NETWORK
1049 /* If we are saving something, the network stays in his current state */
1050 if (new_mode
!= SM_SAVE_GAME
) {
1051 /* If the network is active, make it not-active */
1053 if (_network_server
&& (new_mode
== SM_LOAD_GAME
|| new_mode
== SM_NEWGAME
|| new_mode
== SM_RESTARTGAME
)) {
1056 NetworkDisconnect();
1060 /* If we are a server, we restart the server */
1061 if (_is_network_server
) {
1062 /* But not if we are going to the menu */
1063 if (new_mode
!= SM_MENU
) {
1064 /* check if we should reload the config */
1065 if (_settings_client
.network
.reload_cfg
) {
1067 MakeNewgameSettingsLive();
1068 ResetGRFConfig(false);
1070 NetworkServerStart();
1072 /* This client no longer wants to be a network-server */
1073 _is_network_server
= false;
1077 #endif /* ENABLE_NETWORK */
1078 /* Make sure all AI controllers are gone at quitting game */
1079 if (new_mode
!= SM_SAVE_GAME
) AI::KillAll();
1082 case SM_EDITOR
: // Switch to scenario editor
1083 MakeNewEditorWorld();
1086 case SM_RESTARTGAME
: // Restart --> 'Random game' with current settings
1087 case SM_NEWGAME
: // New Game --> 'Random game'
1088 #ifdef ENABLE_NETWORK
1089 if (_network_server
) {
1090 snprintf(_network_game_info
.map_name
, lengthof(_network_game_info
.map_name
), "Random Map");
1092 #endif /* ENABLE_NETWORK */
1093 MakeNewGame(false, new_mode
== SM_NEWGAME
);
1096 case SM_LOAD_GAME
: { // Load game, Play Scenario
1097 ResetGRFConfig(true);
1098 ResetWindowSystem();
1100 if (!SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.mode
, GM_NORMAL
, NO_DIRECTORY
)) {
1101 SetDParamStr(0, GetSaveLoadErrorString());
1102 ShowErrorMessage(STR_ERROR_GAME_LOAD_FAILED
, STR_JUST_RAW_STRING
, WL_ERROR
);
1104 if (_saveload_mode
== SLD_LOAD_SCENARIO
) {
1105 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1106 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1108 /* Update the local company for a loaded game. It is either always
1109 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1110 SetLocalCompany(_network_dedicated
? COMPANY_SPECTATOR
: COMPANY_FIRST
);
1111 /* Execute the game-start script */
1112 IConsoleCmdExec("exec scripts/game_start.scr 0");
1113 /* Decrease pause counter (was increased from opening load dialog) */
1114 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1115 #ifdef ENABLE_NETWORK
1116 if (_network_server
) {
1117 snprintf(_network_game_info
.map_name
, lengthof(_network_game_info
.map_name
), "%s (Loaded game)", _file_to_saveload
.title
);
1119 #endif /* ENABLE_NETWORK */
1124 case SM_START_HEIGHTMAP
: // Load a heightmap and start a new game from it
1125 #ifdef ENABLE_NETWORK
1126 if (_network_server
) {
1127 snprintf(_network_game_info
.map_name
, lengthof(_network_game_info
.map_name
), "%s (Heightmap)", _file_to_saveload
.title
);
1129 #endif /* ENABLE_NETWORK */
1130 MakeNewGame(true, true);
1133 case SM_LOAD_HEIGHTMAP
: // Load heightmap from scenario editor
1134 SetLocalCompany(OWNER_NONE
);
1136 GenerateWorld(GWM_HEIGHTMAP
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1137 MarkWholeScreenDirty();
1140 case SM_LOAD_SCENARIO
: { // Load scenario from scenario editor
1141 if (SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.mode
, GM_EDITOR
, NO_DIRECTORY
)) {
1142 SetLocalCompany(OWNER_NONE
);
1143 _settings_newgame
.game_creation
.starting_year
= _cur_year
;
1144 /* Cancel the saveload pausing */
1145 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1147 SetDParamStr(0, GetSaveLoadErrorString());
1148 ShowErrorMessage(STR_ERROR_GAME_LOAD_FAILED
, STR_JUST_RAW_STRING
, WL_ERROR
);
1153 case SM_MENU
: // Switch to game intro menu
1155 if (BaseSounds::ini_set
== NULL
&& BaseSounds::GetUsedSet()->fallback
) {
1156 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET
, INVALID_STRING_ID
, WL_CRITICAL
);
1157 BaseSounds::ini_set
= strdup(BaseSounds::GetUsedSet()->name
);
1161 case SM_SAVE_GAME
: // Save game.
1162 /* Make network saved games on pause compatible to singleplayer */
1163 if (!SaveGame(_file_to_saveload
.name
, NO_DIRECTORY
)) {
1164 SetDParamStr(0, GetSaveLoadErrorString());
1165 ShowErrorMessage(STR_ERROR_GAME_SAVE_FAILED
, STR_JUST_RAW_STRING
, WL_ERROR
);
1167 DeleteWindowById(WC_SAVELOAD
, 0);
1171 case SM_SAVE_HEIGHTMAP
: // Save heightmap.
1172 MakeHeightmapScreenshot(_file_to_saveload
.name
);
1173 DeleteWindowById(WC_SAVELOAD
, 0);
1176 case SM_GENRANDLAND
: // Generate random land within scenario editor
1177 SetLocalCompany(OWNER_NONE
);
1178 GenerateWorld(GWM_RANDOM
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1180 MarkWholeScreenDirty();
1183 default: NOT_REACHED();
1189 * Check the validity of some of the caches.
1190 * Especially in the sense of desyncs between
1191 * the cached value and what the value would
1192 * be when calculated from the 'base' data.
1194 static void CheckCaches()
1196 /* Return here so it is easy to add checks that are run
1197 * always to aid testing of caches. */
1198 if (_debug_desync_level
<= 1) return;
1200 /* Check the town caches. */
1201 SmallVector
<TownCache
, 4> old_town_caches
;
1204 MemCpyT(old_town_caches
.Append(), &t
->cache
);
1207 extern void RebuildTownCaches();
1208 RebuildTownCaches();
1209 RebuildSubsidisedSourceAndDestinationCache();
1213 if (MemCmpT(old_town_caches
.Get(i
), &t
->cache
) != 0) {
1214 DEBUG(desync
, 2, "town cache mismatch: town %i", (int)t
->index
);
1219 /* Check company infrastructure cache. */
1220 SmallVector
<CompanyInfrastructure
, 4> old_infrastructure
;
1222 FOR_ALL_COMPANIES(c
) MemCpyT(old_infrastructure
.Append(), &c
->infrastructure
);
1224 extern void AfterLoadCompanyStats();
1225 AfterLoadCompanyStats();
1228 FOR_ALL_COMPANIES(c
) {
1229 if (MemCmpT(old_infrastructure
.Get(i
), &c
->infrastructure
) != 0) {
1230 DEBUG(desync
, 2, "infrastructure cache mismatch: company %i", (int)c
->index
);
1235 /* Strict checking of the road stop cache entries */
1237 FOR_ALL_ROADSTOPS(rs
) {
1238 if (IsStandardRoadStopTile(rs
->xy
)) continue;
1240 assert(rs
->GetEntry(DIAGDIR_NE
) != rs
->GetEntry(DIAGDIR_NW
));
1241 rs
->GetEntry(DIAGDIR_NE
)->CheckIntegrity(rs
);
1242 rs
->GetEntry(DIAGDIR_NW
)->CheckIntegrity(rs
);
1246 FOR_ALL_VEHICLES(v
) {
1247 extern void FillNewGRFVehicleCache(const Vehicle
*v
);
1248 if (v
!= v
->First() || v
->vehstatus
& VS_CRASHED
|| !v
->IsPrimaryVehicle()) continue;
1251 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) length
++;
1253 NewGRFCache
*grf_cache
= CallocT
<NewGRFCache
>(length
);
1254 VehicleCache
*veh_cache
= CallocT
<VehicleCache
>(length
);
1255 GroundVehicleCache
*gro_cache
= CallocT
<GroundVehicleCache
>(length
);
1256 TrainCache
*tra_cache
= CallocT
<TrainCache
>(length
);
1259 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
1260 FillNewGRFVehicleCache(u
);
1261 grf_cache
[length
] = u
->grf_cache
;
1262 veh_cache
[length
] = u
->vcache
;
1265 gro_cache
[length
] = Train::From(u
)->gcache
;
1266 tra_cache
[length
] = Train::From(u
)->tcache
;
1269 gro_cache
[length
] = RoadVehicle::From(u
)->gcache
;
1278 case VEH_TRAIN
: Train::From(v
)->ConsistChanged(true); break;
1279 case VEH_ROAD
: RoadVehUpdateCache(RoadVehicle::From(v
)); break;
1280 case VEH_AIRCRAFT
: UpdateAircraftCache(Aircraft::From(v
)); break;
1281 case VEH_SHIP
: Ship::From(v
)->UpdateCache(); break;
1286 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
1287 FillNewGRFVehicleCache(u
);
1288 if (memcmp(&grf_cache
[length
], &u
->grf_cache
, sizeof(NewGRFCache
)) != 0) {
1289 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
);
1291 if (memcmp(&veh_cache
[length
], &u
->vcache
, sizeof(VehicleCache
)) != 0) {
1292 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
);
1296 if (memcmp(&gro_cache
[length
], &Train::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1297 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
);
1299 if (memcmp(&tra_cache
[length
], &Train::From(u
)->tcache
, sizeof(TrainCache
)) != 0) {
1300 DEBUG(desync
, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1304 if (memcmp(&gro_cache
[length
], &RoadVehicle::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1305 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
);
1320 /* Check whether the caches are still valid */
1321 FOR_ALL_VEHICLES(v
) {
1322 byte buff
[sizeof(VehicleCargoList
)];
1323 memcpy(buff
, &v
->cargo
, sizeof(VehicleCargoList
));
1324 v
->cargo
.InvalidateCache();
1325 assert(memcmp(&v
->cargo
, buff
, sizeof(VehicleCargoList
)) == 0);
1329 FOR_ALL_STATIONS(st
) {
1330 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
1331 byte buff
[sizeof(StationCargoList
)];
1332 memcpy(buff
, &st
->goods
[c
].cargo
, sizeof(StationCargoList
));
1333 st
->goods
[c
].cargo
.InvalidateCache();
1334 assert(memcmp(&st
->goods
[c
].cargo
, buff
, sizeof(StationCargoList
)) == 0);
1340 * State controlling game loop.
1341 * The state must not be changed from anywhere but here.
1342 * That check is enforced in DoCommand.
1344 void StateGameLoop()
1346 /* don't execute the state loop during pause */
1347 if (_pause_mode
!= PM_UNPAUSED
) {
1348 UpdateLandscapingLimits();
1350 CallWindowTickEvent();
1353 if (HasModalProgress()) return;
1355 ClearPersistentStorageChanges(false);
1357 Layouter::ReduceLineCache();
1359 if (_game_mode
== GM_EDITOR
) {
1362 CallLandscapeTick();
1363 ClearPersistentStorageChanges(true);
1364 UpdateLandscapingLimits();
1366 CallWindowTickEvent();
1369 if (_debug_desync_level
> 2 && _date_fract
== 0 && (_date
& 0x1F) == 0) {
1370 /* Save the desync savegame if needed. */
1371 char name
[MAX_PATH
];
1372 snprintf(name
, lengthof(name
), "dmp_cmds_%08x_%08x.sav", _settings_game
.game_creation
.generation_seed
, _date
);
1373 SaveGame(name
, AUTOSAVE_DIR
, false);
1378 /* All these actions has to be done from OWNER_NONE
1379 * for multiplayer compatibility */
1380 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
1382 AnimateAnimatedTiles();
1386 CallLandscapeTick();
1387 ClearPersistentStorageChanges(true);
1391 UpdateLandscapingLimits();
1393 CallWindowTickEvent();
1395 cur_company
.Restore();
1398 assert(IsLocalCompany());
1402 * Create an autosave. The default name is "autosave#.sav". However with
1403 * the setting 'keep_all_autosave' the name defaults to company-name + date
1405 static void DoAutosave()
1410 /* Autosaving in networking is too time expensive for the PSP */
1411 if (_networking
) return;
1414 if (_settings_client
.gui
.keep_all_autosave
) {
1415 GenerateDefaultSaveName(buf
, lastof(buf
));
1416 strecat(buf
, ".sav", lastof(buf
));
1418 static int _autosave_ctr
= 0;
1420 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1421 snprintf(buf
, sizeof(buf
), "autosave%d.sav", _autosave_ctr
);
1423 if (++_autosave_ctr
>= _settings_client
.gui
.max_num_autosaves
) _autosave_ctr
= 0;
1426 DEBUG(sl
, 2, "Autosaving to '%s'", buf
);
1427 if (!SaveGame(buf
, AUTOSAVE_DIR
)) {
1428 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED
, INVALID_STRING_ID
, WL_ERROR
);
1434 if (_game_mode
== GM_BOOTSTRAP
) {
1435 #ifdef ENABLE_NETWORK
1436 /* Check for UDP stuff */
1437 if (_network_available
) NetworkBackgroundLoop();
1443 ProcessAsyncSaveFinish();
1445 /* autosave game? */
1447 _do_autosave
= false;
1449 SetWindowDirty(WC_STATUS_BAR
, 0);
1452 /* switch game mode? */
1453 if (_switch_mode
!= SM_NONE
&& !HasModalProgress()) {
1454 SwitchToMode(_switch_mode
);
1455 _switch_mode
= SM_NONE
;
1458 IncreaseSpriteLRU();
1459 InteractiveRandom();
1461 extern int _caret_timer
;
1465 #ifdef ENABLE_NETWORK
1466 /* Check for UDP stuff */
1467 if (_network_available
) NetworkBackgroundLoop();
1469 if (_networking
&& !HasModalProgress()) {
1473 if (_network_reconnect
> 0 && --_network_reconnect
== 0) {
1474 /* This means that we want to reconnect to the last host
1475 * We do this here, because it means that the network is really closed */
1476 NetworkClientConnectGame(NetworkAddress(_settings_client
.network
.last_host
, _settings_client
.network
.last_port
), COMPANY_SPECTATOR
);
1482 /* Check chat messages roughly once a second. */
1483 static uint check_message
= 0;
1484 if (++check_message
> 1000 / MILLISECONDS_PER_TICK
) {
1486 NetworkChatMessageLoop();
1490 #endif /* ENABLE_NETWORK */
1492 if (!_pause_mode
&& HasBit(_display_opt
, DO_FULL_ANIMATION
)) DoPaletteAnimations();
1494 if (!_pause_mode
|| _game_mode
== GM_EDITOR
|| _settings_game
.construction
.command_pause_level
> CMDPL_NO_CONSTRUCTION
) MoveAllTextEffects();
1498 _sound_driver
->MainLoop();