openttd.cpp

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

Generated on Fri Mar 18 23:17:39 2011 for OpenTTD by  doxygen 1.6.1