openttd.cpp

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