openttd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 
00014 #include "blitter/factory.hpp"
00015 #include "sound/sound_driver.hpp"
00016 #include "music/music_driver.hpp"
00017 #include "video/video_driver.hpp"
00018 
00019 #include "fontcache.h"
00020 #include "error.h"
00021 #include "gui.h"
00022 #include "sound_func.h"
00023 #include "window_func.h"
00024 
00025 #include "base_media_base.h"
00026 #include "saveload/saveload.h"
00027 #include "company_func.h"
00028 #include "command_func.h"
00029 #include "news_func.h"
00030 #include "fios.h"
00031 #include "aircraft.h"
00032 #include "roadveh.h"
00033 #include "train.h"
00034 #include "ship.h"
00035 #include "console_func.h"
00036 #include "screenshot.h"
00037 #include "network/network.h"
00038 #include "network/network_func.h"
00039 #include "signs_base.h"
00040 #include "ai/ai.hpp"
00041 #include "ai/ai_config.hpp"
00042 #include "settings_func.h"
00043 #include "genworld.h"
00044 #include "progress.h"
00045 #include "group.h"
00046 #include "strings_func.h"
00047 #include "date_func.h"
00048 #include "vehicle_func.h"
00049 #include "gamelog.h"
00050 #include "animated_tile_func.h"
00051 #include "roadstop_base.h"
00052 #include "elrail_func.h"
00053 #include "rev.h"
00054 #include "highscore.h"
00055 #include "thread/thread.h"
00056 #include "station_base.h"
00057 #include "crashlog.h"
00058 #include "engine_func.h"
00059 #include "core/random_func.hpp"
00060 #include "rail_gui.h"
00061 #include "core/backup_type.hpp"
00062 #include "hotkeys.h"
00063 #include "newgrf.h"
00064 #include "misc/getoptdata.h"
00065 
00066 
00067 #include "town.h"
00068 #include "industry.h"
00069 
00070 #include "linkgraph/linkgraph.h"
00071 
00072 #include <stdarg.h>
00073 
00074 #include "table/strings.h"
00075 
00076 void CallLandscapeTick();
00077 void IncreaseDate();
00078 void DoPaletteAnimations();
00079 void MusicLoop();
00080 void ResetMusic();
00081 void CallWindowTickEvent();
00082 bool HandleBootstrap();
00083 
00084 extern void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
00085 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
00086 extern void ShowOSErrorBox(const char *buf, bool system);
00087 extern char *_config_file;
00088 
00094 void CDECL usererror(const char *s, ...)
00095 {
00096   va_list va;
00097   char buf[512];
00098 
00099   va_start(va, s);
00100   vsnprintf(buf, lengthof(buf), s, va);
00101   va_end(va);
00102 
00103   ShowOSErrorBox(buf, false);
00104   if (_video_driver != NULL) _video_driver->Stop();
00105 
00106   exit(1);
00107 }
00108 
00114 void CDECL error(const char *s, ...)
00115 {
00116   va_list va;
00117   char buf[512];
00118 
00119   va_start(va, s);
00120   vsnprintf(buf, lengthof(buf), s, va);
00121   va_end(va);
00122 
00123   ShowOSErrorBox(buf, true);
00124 
00125   /* Set the error message for the crash log and then invoke it. */
00126   CrashLog::SetErrorMessage(buf);
00127   abort();
00128 }
00129 
00134 void CDECL ShowInfoF(const char *str, ...)
00135 {
00136   va_list va;
00137   char buf[1024];
00138   va_start(va, str);
00139   vsnprintf(buf, lengthof(buf), str, va);
00140   va_end(va);
00141   ShowInfo(buf);
00142 }
00143 
00147 static void ShowHelp()
00148 {
00149   char buf[8192];
00150   char *p = buf;
00151 
00152   p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
00153   p = strecpy(p,
00154     "\n"
00155     "\n"
00156     "Command line options:\n"
00157     "  -v drv              = Set video driver (see below)\n"
00158     "  -s drv              = Set sound driver (see below) (param bufsize,hz)\n"
00159     "  -m drv              = Set music driver (see below)\n"
00160     "  -b drv              = Set the blitter to use (see below)\n"
00161     "  -r res              = Set resolution (for instance 800x600)\n"
00162     "  -h                  = Display this help text\n"
00163     "  -t year             = Set starting year\n"
00164     "  -d [[fac=]lvl[,...]]= Debug mode\n"
00165     "  -e                  = Start Editor\n"
00166     "  -g [savegame]       = Start new/save game immediately\n"
00167     "  -G seed             = Set random seed\n"
00168 #if defined(ENABLE_NETWORK)
00169     "  -n [ip:port#company]= Start networkgame\n"
00170     "  -p password         = Password to join server\n"
00171     "  -P password         = Password to join company\n"
00172     "  -D [ip][:port]      = Start dedicated server\n"
00173     "  -l ip[:port]        = Redirect DEBUG()\n"
00174 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00175     "  -f                  = Fork into the background (dedicated only)\n"
00176 #endif
00177 #endif /* ENABLE_NETWORK */
00178     "  -I graphics_set     = Force the graphics set (see below)\n"
00179     "  -S sounds_set       = Force the sounds set (see below)\n"
00180     "  -M music_set        = Force the music set (see below)\n"
00181     "  -c config_file      = Use 'config_file' instead of 'openttd.cfg'\n"
00182     "  -x                  = Do not automatically save to config file on exit\n"
00183     "  -q savegame         = Write some information about the savegame and exit\n"
00184     "\n",
00185     lastof(buf)
00186   );
00187 
00188   /* List the graphics packs */
00189   p = BaseGraphics::GetSetsList(p, lastof(buf));
00190 
00191   /* List the sounds packs */
00192   p = BaseSounds::GetSetsList(p, lastof(buf));
00193 
00194   /* List the music packs */
00195   p = BaseMusic::GetSetsList(p, lastof(buf));
00196 
00197   /* List the drivers */
00198   p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
00199 
00200   /* List the blitters */
00201   p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
00202 
00203   /* We need to initialize the AI, so it finds the AIs */
00204   AI::Initialize();
00205   p = AI::GetConsoleList(p, lastof(buf), true);
00206   AI::Uninitialize(true);
00207 
00208   /* ShowInfo put output to stderr, but version information should go
00209    * to stdout; this is the only exception */
00210 #if !defined(WIN32) && !defined(WIN64)
00211   printf("%s\n", buf);
00212 #else
00213   ShowInfo(buf);
00214 #endif
00215 }
00216 
00217 static void WriteSavegameInfo(const char *name)
00218 {
00219   extern uint16 _sl_version;
00220   uint32 last_ottd_rev = 0;
00221   byte ever_modified = 0;
00222   bool removed_newgrfs = false;
00223 
00224   GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
00225 
00226   char buf[8192];
00227   char *p = buf;
00228   p += seprintf(p, lastof(buf), "Name:         %s\n", name);
00229   p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
00230   p += seprintf(p, lastof(buf), "NewGRF ver:   0x%08X\n", last_ottd_rev);
00231   p += seprintf(p, lastof(buf), "Modified:     %d\n", ever_modified);
00232 
00233   if (removed_newgrfs) {
00234     p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
00235   }
00236 
00237   p = strecpy(p, "NewGRFs:\n", lastof(buf));
00238   if (_load_check_data.HasNewGrfs()) {
00239     for (GRFConfig *c = _load_check_data.grfconfig; c != NULL; c = c->next) {
00240       char md5sum[33];
00241       md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
00242       p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
00243     }
00244   }
00245 
00246   /* ShowInfo put output to stderr, but version information should go
00247    * to stdout; this is the only exception */
00248 #if !defined(WIN32) && !defined(WIN64)
00249   printf("%s\n", buf);
00250 #else
00251   ShowInfo(buf);
00252 #endif
00253 }
00254 
00255 
00262 static void ParseResolution(Dimension *res, const char *s)
00263 {
00264   const char *t = strchr(s, 'x');
00265   if (t == NULL) {
00266     ShowInfoF("Invalid resolution '%s'", s);
00267     return;
00268   }
00269 
00270   res->width  = max(strtoul(s, NULL, 0), 64UL);
00271   res->height = max(strtoul(t + 1, NULL, 0), 64UL);
00272 }
00273 
00274 
00279 static void ShutdownGame()
00280 {
00281   IConsoleFree();
00282 
00283   if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
00284 
00285   DriverFactoryBase::ShutdownDrivers();
00286 
00287   UnInitWindowSystem();
00288 
00289   /* stop the AI */
00290   AI::Uninitialize(false);
00291 
00292   /* Uninitialize variables that are allocated dynamically */
00293   GamelogReset();
00294 
00295   /* Reinitialize the link graphs to forcibly stop the threads.
00296    * If a link graph thread is running while the link graph handlers are
00297    * deleted we get a crash.
00298    */
00299   InitializeLinkGraphs();
00300 
00301 #ifdef ENABLE_NETWORK
00302   free(_config_file);
00303 #endif
00304 
00305   PoolBase::Clean(PT_ALL);
00306 
00307   /* No NewGRFs were loaded when it was still bootstrapping. */
00308   if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
00309 
00310   /* Close all and any open filehandles */
00311   FioCloseAll();
00312 
00313   UninitFreeType();
00314 }
00315 
00320 static void LoadIntroGame(bool load_newgrfs = true)
00321 {
00322   _game_mode = GM_MENU;
00323 
00324   if (load_newgrfs) ResetGRFConfig(false);
00325 
00326   /* Setup main window */
00327   ResetWindowSystem();
00328   SetupColoursAndInitialWindow();
00329 
00330   /* Load the default opening screen savegame */
00331   if (SaveOrLoad("opntitle.dat", SL_LOAD, BASESET_DIR) != SL_OK) {
00332     GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
00333     WaitTillGeneratedWorld();
00334     SetLocalCompany(COMPANY_SPECTATOR);
00335   } else {
00336     SetLocalCompany(COMPANY_FIRST);
00337   }
00338 
00339   _pause_mode = PM_UNPAUSED;
00340   _cursor.fix_at = false;
00341 
00342   CheckForMissingSprites();
00343   CheckForMissingGlyphs();
00344 
00345   /* Play main theme */
00346   if (_music_driver->IsSongPlaying()) ResetMusic();
00347 }
00348 
00349 void MakeNewgameSettingsLive()
00350 {
00351   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00352     if (_settings_game.ai_config[c] != NULL) {
00353       delete _settings_game.ai_config[c];
00354     }
00355   }
00356 
00357   /* Copy newgame settings to active settings.
00358    * Also initialise old settings needed for savegame conversion. */
00359   _settings_game = _settings_newgame;
00360   _old_vds = _settings_client.company.vehicle;
00361 
00362   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00363     _settings_game.ai_config[c] = NULL;
00364     if (_settings_newgame.ai_config[c] != NULL) {
00365       _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
00366     }
00367   }
00368 }
00369 
00371 struct AfterNewGRFScan : NewGRFScanCallback {
00372   Year startyear;                    
00373   uint generation_seed;              
00374   char *dedicated_host;              
00375   uint16 dedicated_port;             
00376   char *network_conn;                
00377   const char *join_server_password;  
00378   const char *join_company_password; 
00379   bool *save_config_ptr;             
00380   bool save_config;                  
00381 
00387   AfterNewGRFScan(bool *save_config_ptr) :
00388       startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
00389       dedicated_host(NULL), dedicated_port(0), network_conn(NULL),
00390       join_server_password(NULL), join_company_password(NULL),
00391       save_config_ptr(save_config_ptr), save_config(true)
00392   {
00393   }
00394 
00395   virtual void OnNewGRFsScanned()
00396   {
00397     ResetGRFConfig(false);
00398 
00399     TarScanner::DoScan(TarScanner::SCENARIO);
00400 
00401     AI::Initialize();
00402 
00403     /* We want the new (correct) NewGRF count to survive the loading. */
00404     uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
00405     LoadFromConfig();
00406     _settings_client.gui.last_newgrf_count = last_newgrf_count;
00407     /* Since the default for the palette might have changed due to
00408      * reading the configuration file, recalculate that now. */
00409     UpdateNewGRFConfigPalette();
00410 
00411     AI::Uninitialize(true);
00412     CheckConfig();
00413     LoadFromHighScore();
00414     LoadHotkeysFromConfig();
00415 
00416     /* We have loaded the config, so we may possibly save it. */
00417     *save_config_ptr = save_config;
00418 
00419 
00420     if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
00421     if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
00422 
00423 #if defined(ENABLE_NETWORK)
00424     if (dedicated_host != NULL) {
00425       _network_bind_list.Clear();
00426       *_network_bind_list.Append() = strdup(dedicated_host);
00427     }
00428     if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
00429 #endif /* ENABLE_NETWORK */
00430 
00431     /* initialize the ingame console */
00432     IConsoleInit();
00433     InitializeGUI();
00434     IConsoleCmdExec("exec scripts/autoexec.scr 0");
00435 
00436     /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
00437     if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
00438 
00439 #ifdef ENABLE_NETWORK
00440     if (_network_available && network_conn != NULL) {
00441       const char *port = NULL;
00442       const char *company = NULL;
00443       uint16 rport = NETWORK_DEFAULT_PORT;
00444       CompanyID join_as = COMPANY_NEW_COMPANY;
00445 
00446       ParseConnectionString(&company, &port, network_conn);
00447 
00448       if (company != NULL) {
00449         join_as = (CompanyID)atoi(company);
00450 
00451         if (join_as != COMPANY_SPECTATOR) {
00452           join_as--;
00453           if (join_as >= MAX_COMPANIES) {
00454             delete this;
00455             return;
00456           }
00457         }
00458       }
00459       if (port != NULL) rport = atoi(port);
00460 
00461       LoadIntroGame();
00462       _switch_mode = SM_NONE;
00463       NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
00464     }
00465 #endif /* ENABLE_NETWORK */
00466 
00467     /* After the scan we're not used anymore. */
00468     delete this;
00469   }
00470 };
00471 
00472 #if defined(UNIX) && !defined(__MORPHOS__)
00473 extern void DedicatedFork();
00474 #endif
00475 
00477 static const OptionData _options[] = {
00478    GETOPT_SHORT_VALUE('I'),
00479    GETOPT_SHORT_VALUE('S'),
00480    GETOPT_SHORT_VALUE('M'),
00481    GETOPT_SHORT_VALUE('m'),
00482    GETOPT_SHORT_VALUE('s'),
00483    GETOPT_SHORT_VALUE('v'),
00484    GETOPT_SHORT_VALUE('b'),
00485 #if defined(ENABLE_NETWORK)
00486   GETOPT_SHORT_OPTVAL('D'),
00487   GETOPT_SHORT_OPTVAL('n'),
00488    GETOPT_SHORT_VALUE('l'),
00489    GETOPT_SHORT_VALUE('p'),
00490    GETOPT_SHORT_VALUE('P'),
00491 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00492    GETOPT_SHORT_NOVAL('f'),
00493 #endif
00494 #endif /* ENABLE_NETWORK */
00495    GETOPT_SHORT_VALUE('r'),
00496    GETOPT_SHORT_VALUE('t'),
00497   GETOPT_SHORT_OPTVAL('d'),
00498    GETOPT_SHORT_NOVAL('e'),
00499   GETOPT_SHORT_OPTVAL('g'),
00500    GETOPT_SHORT_VALUE('G'),
00501    GETOPT_SHORT_VALUE('c'),
00502    GETOPT_SHORT_NOVAL('x'),
00503    GETOPT_SHORT_VALUE('q'),
00504    GETOPT_SHORT_NOVAL('h'),
00505   GETOPT_END()
00506 };
00507 
00508 
00509 int ttd_main(int argc, char *argv[])
00510 {
00511   char *musicdriver = NULL;
00512   char *sounddriver = NULL;
00513   char *videodriver = NULL;
00514   char *blitter = NULL;
00515   char *graphics_set = NULL;
00516   char *sounds_set = NULL;
00517   char *music_set = NULL;
00518   Dimension resolution = {0, 0};
00519   /* AfterNewGRFScan sets save_config to true after scanning completed. */
00520   bool save_config = false;
00521   AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
00522 #if defined(ENABLE_NETWORK)
00523   bool dedicated = false;
00524   char *debuglog_conn = NULL;
00525 
00526   extern bool _dedicated_forks;
00527   _dedicated_forks = false;
00528 #endif /* ENABLE_NETWORK */
00529 
00530   _game_mode = GM_MENU;
00531   _switch_mode = SM_MENU;
00532   _config_file = NULL;
00533 
00534   GetOptData mgo(argc - 1, argv + 1, _options);
00535 
00536   int i;
00537   while ((i = mgo.GetOpt()) != -1) {
00538     switch (i) {
00539     case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
00540     case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
00541     case 'M': free(music_set); music_set = strdup(mgo.opt); break;
00542     case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
00543     case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
00544     case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
00545     case 'b': free(blitter); blitter = strdup(mgo.opt); break;
00546 #if defined(ENABLE_NETWORK)
00547     case 'D':
00548       free(musicdriver);
00549       free(sounddriver);
00550       free(videodriver);
00551       free(blitter);
00552       musicdriver = strdup("null");
00553       sounddriver = strdup("null");
00554       videodriver = strdup("dedicated");
00555       blitter = strdup("null");
00556       dedicated = true;
00557       SetDebugString("net=6");
00558       if (mgo.opt != NULL) {
00559         /* Use the existing method for parsing (openttd -n).
00560          * However, we do ignore the #company part. */
00561         const char *temp = NULL;
00562         const char *port = NULL;
00563         ParseConnectionString(&temp, &port, mgo.opt);
00564         if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
00565         if (port != NULL) scanner->dedicated_port = atoi(port);
00566       }
00567       break;
00568     case 'f': _dedicated_forks = true; break;
00569     case 'n':
00570       scanner->network_conn = mgo.opt; // optional IP parameter, NULL if unset
00571       break;
00572     case 'l':
00573       debuglog_conn = mgo.opt;
00574       break;
00575     case 'p':
00576       scanner->join_server_password = mgo.opt;
00577       break;
00578     case 'P':
00579       scanner->join_company_password = mgo.opt;
00580       break;
00581 #endif /* ENABLE_NETWORK */
00582     case 'r': ParseResolution(&resolution, mgo.opt); break;
00583     case 't': scanner->startyear = atoi(mgo.opt); break;
00584     case 'd': {
00585 #if defined(WIN32)
00586         CreateConsole();
00587 #endif
00588         if (mgo.opt != NULL) SetDebugString(mgo.opt);
00589         break;
00590       }
00591     case 'e': _switch_mode = SM_EDITOR; break;
00592     case 'g':
00593       if (mgo.opt != NULL) {
00594         strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
00595         _switch_mode = SM_LOAD_GAME;
00596         _file_to_saveload.mode = SL_LOAD;
00597 
00598         /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
00599         const char *t = strrchr(_file_to_saveload.name, '.');
00600         if (t != NULL) {
00601           FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
00602           if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
00603         }
00604 
00605         break;
00606       }
00607 
00608       _switch_mode = SM_NEWGAME;
00609       /* Give a random map if no seed has been given */
00610       if (scanner->generation_seed == GENERATE_NEW_SEED) {
00611         scanner->generation_seed = InteractiveRandom();
00612       }
00613       break;
00614     case 'q': {
00615       DeterminePaths(argv[0]);
00616       if (StrEmpty(mgo.opt)) return 1;
00617       char title[80];
00618       title[0] = '\0';
00619       FiosGetSavegameListCallback(SLD_LOAD_GAME, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
00620 
00621       _load_check_data.Clear();
00622       SaveOrLoadResult res = SaveOrLoad(mgo.opt, SL_LOAD_CHECK, SAVE_DIR, false);
00623       if (res != SL_OK || _load_check_data.HasErrors()) {
00624         fprintf(stderr, "Failed to open savegame\n");
00625         if (_load_check_data.HasErrors()) {
00626           char buf[256];
00627           SetDParamStr(0, _load_check_data.error_data);
00628           GetString(buf, _load_check_data.error, lastof(buf));
00629           fprintf(stderr, "%s\n", buf);
00630         }
00631         return 1;
00632       }
00633 
00634       WriteSavegameInfo(title);
00635 
00636       return 0;
00637     }
00638     case 'G': scanner->generation_seed = atoi(mgo.opt); break;
00639     case 'c': _config_file = strdup(mgo.opt); break;
00640     case 'x': scanner->save_config = false; break;
00641     case 'h':
00642       i = -2; // Force printing of help.
00643       break;
00644     }
00645     if (i == -2) break;
00646   }
00647 
00648   if (i == -2 || mgo.numleft > 0) {
00649     /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
00650      * In all cases, print the help, and exit.
00651      *
00652      * The next two functions are needed to list the graphics sets. We can't do them earlier
00653      * because then we cannot show it on the debug console as that hasn't been configured yet. */
00654     DeterminePaths(argv[0]);
00655     TarScanner::DoScan(TarScanner::BASESET);
00656     BaseGraphics::FindSets();
00657     BaseSounds::FindSets();
00658     BaseMusic::FindSets();
00659     ShowHelp();
00660     delete scanner;
00661     return 0;
00662   }
00663 
00664 #if defined(WINCE) && defined(_DEBUG)
00665   /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
00666   SetDebugString("4");
00667 #endif
00668 
00669   DeterminePaths(argv[0]);
00670   TarScanner::DoScan(TarScanner::BASESET);
00671 
00672 #if defined(ENABLE_NETWORK)
00673   if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
00674   if (_dedicated_forks && !dedicated) _dedicated_forks = false;
00675 
00676 #if defined(UNIX) && !defined(__MORPHOS__)
00677   /* We must fork here, or we'll end up without some resources we need (like sockets) */
00678   if (_dedicated_forks) DedicatedFork();
00679 #endif
00680 #endif
00681 
00682   LoadFromConfig(true);
00683 
00684   if (resolution.width != 0) _cur_resolution = resolution;
00685 
00686   /*
00687    * The width and height must be at least 1 pixel and width times
00688    * height times bytes per pixel must still fit within a 32 bits
00689    * integer, even for 32 bpp video modes. This way all internal
00690    * drawing routines work correctly.
00691    */
00692   _cur_resolution.width  = ClampU(_cur_resolution.width,  1, UINT16_MAX / 2);
00693   _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
00694 
00695   /* Assume the cursor starts within the game as not all video drivers
00696    * get an event that the cursor is within the window when it is opened.
00697    * Saying the cursor is there makes no visible difference as it would
00698    * just be out of the bounds of the window. */
00699   _cursor.in_window = true;
00700 
00701   /* enumerate language files */
00702   InitializeLanguagePacks();
00703 
00704   /* Initialize the regular font for FreeType */
00705   InitFreeType(false);
00706 
00707   /* This must be done early, since functions use the SetWindowDirty* calls */
00708   InitWindowSystem();
00709 
00710   BaseGraphics::FindSets();
00711   if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set);
00712   if (!BaseGraphics::SetSet(graphics_set) && !StrEmpty(graphics_set)) {
00713     usererror("Failed to select requested graphics set '%s'", graphics_set);
00714   }
00715   free(graphics_set);
00716 
00717   /* Initialize game palette */
00718   GfxInitPalettes();
00719 
00720   DEBUG(misc, 1, "Loading blitter...");
00721   if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter);
00722   _blitter_autodetected = StrEmpty(blitter);
00723   /* If we have a 32 bpp base set, try to select the 32 bpp blitter first, but only if we autoprobe the blitter. */
00724   if (!_blitter_autodetected || BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP || BlitterFactoryBase::SelectBlitter("32bpp-anim") == NULL) {
00725     if (BlitterFactoryBase::SelectBlitter(blitter) == NULL) {
00726       StrEmpty(blitter) ?
00727         usererror("Failed to autoprobe blitter") :
00728         usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
00729     }
00730   }
00731   free(blitter);
00732 
00733   if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver);
00734   _video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
00735   if (_video_driver == NULL) {
00736     StrEmpty(videodriver) ?
00737       usererror("Failed to autoprobe video driver") :
00738       usererror("Failed to select requested video driver '%s'", videodriver);
00739   }
00740   free(videodriver);
00741 
00742   /* Initialize the zoom level of the screen to normal */
00743   _screen.zoom = ZOOM_LVL_NORMAL;
00744 
00745   NetworkStartUp(); // initialize network-core
00746 
00747 #if defined(ENABLE_NETWORK)
00748   if (debuglog_conn != NULL && _network_available) {
00749     const char *not_used = NULL;
00750     const char *port = NULL;
00751     uint16 rport;
00752 
00753     rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
00754 
00755     ParseConnectionString(&not_used, &port, debuglog_conn);
00756     if (port != NULL) rport = atoi(port);
00757 
00758     NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
00759   }
00760 #endif /* ENABLE_NETWORK */
00761 
00762   if (!HandleBootstrap()) goto exit;
00763 
00764   _video_driver->ClaimMousePointer();
00765 
00766   /* initialize screenshot formats */
00767   InitializeScreenshotFormats();
00768 
00769   BaseSounds::FindSets();
00770   if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set);
00771   if (!BaseSounds::SetSet(sounds_set)) {
00772     StrEmpty(sounds_set) ?
00773       usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.") :
00774       usererror("Failed to select requested sounds set '%s'", sounds_set);
00775   }
00776   free(sounds_set);
00777 
00778   BaseMusic::FindSets();
00779   if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set);
00780   if (!BaseMusic::SetSet(music_set)) {
00781     StrEmpty(music_set) ?
00782       usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.") :
00783       usererror("Failed to select requested music set '%s'", music_set);
00784   }
00785   free(music_set);
00786 
00787   if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver);
00788   _sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
00789   if (_sound_driver == NULL) {
00790     StrEmpty(sounddriver) ?
00791       usererror("Failed to autoprobe sound driver") :
00792       usererror("Failed to select requested sound driver '%s'", sounddriver);
00793   }
00794   free(sounddriver);
00795 
00796   if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver);
00797   _music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
00798   if (_music_driver == NULL) {
00799     StrEmpty(musicdriver) ?
00800       usererror("Failed to autoprobe music driver") :
00801       usererror("Failed to select requested music driver '%s'", musicdriver);
00802   }
00803   free(musicdriver);
00804 
00805   /* restore saved music volume */
00806   _music_driver->SetVolume(_settings_client.music.music_vol);
00807 
00808   /* Take our initial lock on whatever we might want to do! */
00809   _modal_progress_paint_mutex->BeginCritical();
00810   _modal_progress_work_mutex->BeginCritical();
00811 
00812   GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
00813   WaitTillGeneratedWorld();
00814 
00815   LoadIntroGame(false);
00816 
00817   CheckForMissingGlyphs();
00818 
00819   ScanNewGRFFiles(scanner);
00820 
00821   _video_driver->MainLoop();
00822 
00823   WaitTillSaved();
00824 
00825   /* only save config if we have to */
00826   if (save_config) {
00827     SaveToConfig();
00828     SaveHotkeysToConfig();
00829     SaveToHighScore();
00830   }
00831 
00832 exit:
00833   /* Reset windowing system, stop drivers, free used memory, ... */
00834   ShutdownGame();
00835 
00836   free(BaseGraphics::ini_set);
00837   free(BaseSounds::ini_set);
00838   free(BaseMusic::ini_set);
00839   free(_ini_musicdriver);
00840   free(_ini_sounddriver);
00841   free(_ini_videodriver);
00842   free(_ini_blitter);
00843 
00844   return 0;
00845 }
00846 
00847 void HandleExitGameRequest()
00848 {
00849   if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
00850     _exit_game = true;
00851   } else if (_settings_client.gui.autosave_on_exit) {
00852     DoExitSave();
00853     _exit_game = true;
00854   } else {
00855     AskExitGame();
00856   }
00857 }
00858 
00859 static void MakeNewGameDone()
00860 {
00861   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
00862 
00863   /* In a dedicated server, the server does not play */
00864   if (!_video_driver->HasGUI()) {
00865     SetLocalCompany(COMPANY_SPECTATOR);
00866     IConsoleCmdExec("exec scripts/game_start.scr 0");
00867     return;
00868   }
00869 
00870   /* Create a single company */
00871   DoStartupNewCompany(false);
00872 
00873   Company *c = Company::Get(COMPANY_FIRST);
00874   c->settings = _settings_client.company;
00875 
00876   IConsoleCmdExec("exec scripts/game_start.scr 0");
00877 
00878   SetLocalCompany(COMPANY_FIRST);
00879 
00880   InitializeRailGUI();
00881 
00882 #ifdef ENABLE_NETWORK
00883   /* We are the server, we start a new company (not dedicated),
00884    * so set the default password *if* needed. */
00885   if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
00886     NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
00887   }
00888 #endif /* ENABLE_NETWORK */
00889 
00890   if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
00891 
00892   MarkWholeScreenDirty();
00893 }
00894 
00895 static void MakeNewGame(bool from_heightmap, bool reset_settings)
00896 {
00897   _game_mode = GM_NORMAL;
00898 
00899   ResetGRFConfig(true);
00900 
00901   GenerateWorldSetCallback(&MakeNewGameDone);
00902   GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
00903 }
00904 
00905 static void MakeNewEditorWorldDone()
00906 {
00907   SetLocalCompany(OWNER_NONE);
00908 }
00909 
00910 static void MakeNewEditorWorld()
00911 {
00912   _game_mode = GM_EDITOR;
00913 
00914   ResetGRFConfig(true);
00915 
00916   GenerateWorldSetCallback(&MakeNewEditorWorldDone);
00917   GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00918 }
00919 
00930 bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
00931 {
00932   assert(mode == SL_LOAD || (lf == NULL && mode == SL_OLD_LOAD));
00933   GameMode ogm = _game_mode;
00934 
00935   _game_mode = newgm;
00936 
00937   switch (lf == NULL ? SaveOrLoad(filename, mode, subdir) : LoadWithFilter(lf)) {
00938     case SL_OK: return true;
00939 
00940     case SL_REINIT:
00941 #ifdef ENABLE_NETWORK
00942       if (_network_dedicated) {
00943         /*
00944          * We need to reinit a network map...
00945          * We can't simply load the intro game here as that game has many
00946          * special cases which make clients desync immediately. So we fall
00947          * back to just generating a new game with the current settings.
00948          */
00949         DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
00950         MakeNewGame(false, true);
00951         return false;
00952       }
00953       if (_network_server) {
00954         /* We can't load the intro game as server, so disconnect first. */
00955         NetworkDisconnect();
00956       }
00957 #endif /* ENABLE_NETWORK */
00958 
00959       switch (ogm) {
00960         default:
00961         case GM_MENU:   LoadIntroGame();      break;
00962         case GM_EDITOR: MakeNewEditorWorld(); break;
00963       }
00964       return false;
00965 
00966     default:
00967       _game_mode = ogm;
00968       return false;
00969   }
00970 }
00971 
00972 void SwitchToMode(SwitchMode new_mode)
00973 {
00974 #ifdef ENABLE_NETWORK
00975   /* If we are saving something, the network stays in his current state */
00976   if (new_mode != SM_SAVE_GAME) {
00977     /* If the network is active, make it not-active */
00978     if (_networking) {
00979       if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
00980         NetworkReboot();
00981       } else {
00982         NetworkDisconnect();
00983       }
00984     }
00985 
00986     /* If we are a server, we restart the server */
00987     if (_is_network_server) {
00988       /* But not if we are going to the menu */
00989       if (new_mode != SM_MENU) {
00990         /* check if we should reload the config */
00991         if (_settings_client.network.reload_cfg) {
00992           LoadFromConfig();
00993           MakeNewgameSettingsLive();
00994           ResetGRFConfig(false);
00995         }
00996         NetworkServerStart();
00997       } else {
00998         /* This client no longer wants to be a network-server */
00999         _is_network_server = false;
01000       }
01001     }
01002   }
01003 #endif /* ENABLE_NETWORK */
01004   /* Make sure all AI controllers are gone at quiting game */
01005   if (new_mode != SM_SAVE_GAME) AI::KillAll();
01006 
01007   switch (new_mode) {
01008     case SM_EDITOR: // Switch to scenario editor
01009       MakeNewEditorWorld();
01010       break;
01011 
01012     case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
01013     case SM_NEWGAME: // New Game --> 'Random game'
01014 #ifdef ENABLE_NETWORK
01015       if (_network_server) {
01016         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
01017       }
01018 #endif /* ENABLE_NETWORK */
01019       MakeNewGame(false, new_mode == SM_NEWGAME);
01020       break;
01021 
01022     case SM_LOAD_GAME: { // Load game, Play Scenario
01023       ResetGRFConfig(true);
01024       ResetWindowSystem();
01025 
01026       if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
01027         SetDParamStr(0, GetSaveLoadErrorString());
01028         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01029       } else {
01030         if (_saveload_mode == SLD_LOAD_SCENARIO) {
01031           StartupEngines();
01032         }
01033         /* Update the local company for a loaded game. It is either always
01034          * company #1 (eg 0) or in the case of a dedicated server a spectator */
01035         SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
01036         /* Execute the game-start script */
01037         IConsoleCmdExec("exec scripts/game_start.scr 0");
01038         /* Decrease pause counter (was increased from opening load dialog) */
01039         DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01040 #ifdef ENABLE_NETWORK
01041         if (_network_server) {
01042           snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
01043         }
01044 #endif /* ENABLE_NETWORK */
01045       }
01046       break;
01047     }
01048 
01049     case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
01050 #ifdef ENABLE_NETWORK
01051       if (_network_server) {
01052         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
01053       }
01054 #endif /* ENABLE_NETWORK */
01055       MakeNewGame(true, true);
01056       break;
01057 
01058     case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
01059       SetLocalCompany(OWNER_NONE);
01060 
01061       GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01062       MarkWholeScreenDirty();
01063       break;
01064 
01065     case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
01066       if (SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
01067         SetLocalCompany(OWNER_NONE);
01068         _settings_newgame.game_creation.starting_year = _cur_year;
01069         /* Cancel the saveload pausing */
01070         DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01071       } else {
01072         SetDParamStr(0, GetSaveLoadErrorString());
01073         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01074       }
01075       break;
01076     }
01077 
01078     case SM_MENU: // Switch to game intro menu
01079       LoadIntroGame();
01080       if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
01081         ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
01082         BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name);
01083       }
01084       break;
01085 
01086     case SM_SAVE_GAME: // Save game.
01087       /* Make network saved games on pause compatible to singleplayer */
01088       if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
01089         SetDParamStr(0, GetSaveLoadErrorString());
01090         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01091       } else {
01092         DeleteWindowById(WC_SAVELOAD, 0);
01093       }
01094       break;
01095 
01096     case SM_SAVE_HEIGHTMAP: // Save heightmap.
01097       MakeHeightmapScreenshot(_file_to_saveload.name);
01098       DeleteWindowById(WC_SAVELOAD, 0);
01099       break;
01100 
01101     case SM_GENRANDLAND: // Generate random land within scenario editor
01102       SetLocalCompany(OWNER_NONE);
01103       GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01104       /* XXX: set date */
01105       MarkWholeScreenDirty();
01106       break;
01107 
01108     default: NOT_REACHED();
01109   }
01110 }
01111 
01112 
01119 static void CheckCaches()
01120 {
01121   /* Check company infrastructure cache. */
01122   SmallVector<CompanyInfrastructure, 4> old_infrastructure;
01123   Company *c;
01124   FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);
01125 
01126   extern void AfterLoadCompanyStats();
01127   AfterLoadCompanyStats();
01128 
01129   uint i = 0;
01130   FOR_ALL_COMPANIES(c) {
01131     if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
01132       DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
01133     }
01134     i++;
01135   }
01136 
01137   /* Return here so it is easy to add checks that are run
01138    * always to aid testing of caches. */
01139   if (_debug_desync_level <= 1) return;
01140 
01141   /* Strict checking of the road stop cache entries */
01142   const RoadStop *rs;
01143   FOR_ALL_ROADSTOPS(rs) {
01144     if (IsStandardRoadStopTile(rs->xy)) continue;
01145 
01146     assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
01147     rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
01148     rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
01149   }
01150 
01151   Vehicle *v;
01152   FOR_ALL_VEHICLES(v) {
01153     extern void FillNewGRFVehicleCache(const Vehicle *v);
01154     if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
01155 
01156     uint length = 0;
01157     for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
01158 
01159     NewGRFCache        *grf_cache = CallocT<NewGRFCache>(length);
01160     VehicleCache       *veh_cache = CallocT<VehicleCache>(length);
01161     GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
01162     TrainCache         *tra_cache = CallocT<TrainCache>(length);
01163 
01164     length = 0;
01165     for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01166       FillNewGRFVehicleCache(u);
01167       grf_cache[length] = u->grf_cache;
01168       veh_cache[length] = u->vcache;
01169       switch (u->type) {
01170         case VEH_TRAIN:
01171           gro_cache[length] = Train::From(u)->gcache;
01172           tra_cache[length] = Train::From(u)->tcache;
01173           break;
01174         case VEH_ROAD:
01175           gro_cache[length] = RoadVehicle::From(u)->gcache;
01176           break;
01177         default:
01178           break;
01179       }
01180       length++;
01181     }
01182 
01183     switch (v->type) {
01184       case VEH_TRAIN:    Train::From(v)->ConsistChanged(true);     break;
01185       case VEH_ROAD:     RoadVehUpdateCache(RoadVehicle::From(v)); break;
01186       case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v));   break;
01187       case VEH_SHIP:     Ship::From(v)->UpdateCache();             break;
01188       default: break;
01189     }
01190 
01191     length = 0;
01192     for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01193       FillNewGRFVehicleCache(u);
01194       if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
01195         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);
01196       }
01197       if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
01198         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);
01199       }
01200       switch (u->type) {
01201         case VEH_TRAIN:
01202           if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01203             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);
01204           }
01205           if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
01206             DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01207           }
01208           break;
01209         case VEH_ROAD:
01210           if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01211             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);
01212           }
01213           break;
01214         default:
01215           break;
01216       }
01217       length++;
01218     }
01219 
01220     free(grf_cache);
01221     free(veh_cache);
01222     free(gro_cache);
01223     free(tra_cache);
01224   }
01225 
01226   /* Check whether the caches are still valid */
01227   FOR_ALL_VEHICLES(v) {
01228     byte buff[sizeof(VehicleCargoList)];
01229     memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
01230     v->cargo.InvalidateCache();
01231     assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
01232   }
01233 
01234   Station *st;
01235   FOR_ALL_STATIONS(st) {
01236     for (CargoID c = 0; c < NUM_CARGO; c++) {
01237       byte buff[sizeof(StationCargoList)];
01238       memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
01239       st->goods[c].cargo.InvalidateCache();
01240       assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
01241     }
01242   }
01243 }
01244 
01250 void StateGameLoop()
01251 {
01252   /* dont execute the state loop during pause */
01253   if (_pause_mode != PM_UNPAUSED) {
01254     UpdateLandscapingLimits();
01255     CallWindowTickEvent();
01256     return;
01257   }
01258   if (HasModalProgress()) return;
01259 
01260   ClearStorageChanges(false);
01261 
01262   if (_game_mode == GM_EDITOR) {
01263     RunTileLoop();
01264     CallVehicleTicks();
01265     CallLandscapeTick();
01266     ClearStorageChanges(true);
01267     UpdateLandscapingLimits();
01268 
01269     CallWindowTickEvent();
01270     NewsLoop();
01271   } else {
01272     if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
01273       /* Save the desync savegame if needed. */
01274       char name[MAX_PATH];
01275       snprintf(name, lengthof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
01276       SaveOrLoad(name, SL_SAVE, AUTOSAVE_DIR, false);
01277     }
01278 
01279     CheckCaches();
01280 
01281     /* All these actions has to be done from OWNER_NONE
01282      *  for multiplayer compatibility */
01283     Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
01284 
01285     AnimateAnimatedTiles();
01286     IncreaseDate();
01287     RunTileLoop();
01288     CallVehicleTicks();
01289     CallLandscapeTick();
01290     ClearStorageChanges(true);
01291 
01292     AI::GameLoop();
01293     UpdateLandscapingLimits();
01294 
01295     CallWindowTickEvent();
01296     NewsLoop();
01297     cur_company.Restore();
01298   }
01299 
01300   assert(IsLocalCompany());
01301 }
01302 
01307 static void DoAutosave()
01308 {
01309   char buf[MAX_PATH];
01310 
01311 #if defined(PSP)
01312   /* Autosaving in networking is too time expensive for the PSP */
01313   if (_networking) return;
01314 #endif /* PSP */
01315 
01316   if (_settings_client.gui.keep_all_autosave) {
01317     GenerateDefaultSaveName(buf, lastof(buf));
01318     strecat(buf, ".sav", lastof(buf));
01319   } else {
01320     static int _autosave_ctr = 0;
01321 
01322     /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
01323     snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
01324 
01325     if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
01326   }
01327 
01328   DEBUG(sl, 2, "Autosaving to '%s'", buf);
01329   if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
01330     ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
01331   }
01332 }
01333 
01334 void GameLoop()
01335 {
01336   if (_game_mode == GM_BOOTSTRAP) {
01337 #ifdef ENABLE_NETWORK
01338     /* Check for UDP stuff */
01339     if (_network_available) NetworkUDPGameLoop();
01340 #endif
01341     InputLoop();
01342     return;
01343   }
01344 
01345   ProcessAsyncSaveFinish();
01346 
01347   /* autosave game? */
01348   if (_do_autosave) {
01349     _do_autosave = false;
01350     DoAutosave();
01351     SetWindowDirty(WC_STATUS_BAR, 0);
01352   }
01353 
01354   /* switch game mode? */
01355   if (_switch_mode != SM_NONE && !HasModalProgress()) {
01356     SwitchToMode(_switch_mode);
01357     _switch_mode = SM_NONE;
01358   }
01359 
01360   IncreaseSpriteLRU();
01361   InteractiveRandom();
01362 
01363   extern int _caret_timer;
01364   _caret_timer += 3;
01365   CursorTick();
01366 
01367 #ifdef ENABLE_NETWORK
01368   /* Check for UDP stuff */
01369   if (_network_available) NetworkUDPGameLoop();
01370 
01371   if (_networking && !HasModalProgress()) {
01372     /* Multiplayer */
01373     NetworkGameLoop();
01374   } else {
01375     if (_network_reconnect > 0 && --_network_reconnect == 0) {
01376       /* This means that we want to reconnect to the last host
01377        * We do this here, because it means that the network is really closed */
01378       NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
01379     }
01380     /* Singleplayer */
01381     StateGameLoop();
01382   }
01383 
01384   /* Check chat messages roughly once a second. */
01385   static uint check_message = 0;
01386   if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
01387     check_message = 0;
01388     NetworkChatMessageLoop();
01389   }
01390 #else
01391   StateGameLoop();
01392 #endif /* ENABLE_NETWORK */
01393 
01394   if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
01395 
01396   if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
01397 
01398   InputLoop();
01399 
01400   _sound_driver->MainLoop();
01401   MusicLoop();
01402 }