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