openttd.cpp

Go to the documentation of this file.
00001 /* $Id: openttd.cpp 22886 2011-09-03 18:56:34Z frosch $ */
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 
00308 static void ShutdownGame()
00309 {
00310   IConsoleFree();
00311 
00312   if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
00313 
00314   DriverFactoryBase::ShutdownDrivers();
00315 
00316   UnInitWindowSystem();
00317 
00318   /* stop the AI */
00319   AI::Uninitialize(false);
00320 
00321   /* Uninitialize variables that are allocated dynamically */
00322   GamelogReset();
00323   _town_pool.CleanPool();
00324   _industry_pool.CleanPool();
00325   _station_pool.CleanPool();
00326   _roadstop_pool.CleanPool();
00327   _vehicle_pool.CleanPool();
00328   _sign_pool.CleanPool();
00329   _order_pool.CleanPool();
00330   _group_pool.CleanPool();
00331   _cargopacket_pool.CleanPool();
00332   _engine_pool.CleanPool();
00333   _company_pool.CleanPool();
00334 
00335 #ifdef ENABLE_NETWORK
00336   free(_config_file);
00337 #endif
00338 
00339   ResetNewGRFData();
00340 
00341   /* Close all and any open filehandles */
00342   FioCloseAll();
00343 }
00344 
00345 static void LoadIntroGame()
00346 {
00347   _game_mode = GM_MENU;
00348 
00349   ResetGRFConfig(false);
00350 
00351   /* Setup main window */
00352   ResetWindowSystem();
00353   SetupColoursAndInitialWindow();
00354 
00355   /* Load the default opening screen savegame */
00356   if (SaveOrLoad("opntitle.dat", SL_LOAD, DATA_DIR) != SL_OK) {
00357     GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
00358     WaitTillGeneratedWorld();
00359     SetLocalCompany(COMPANY_SPECTATOR);
00360   } else {
00361     SetLocalCompany(COMPANY_FIRST);
00362   }
00363 
00364   _pause_mode = PM_UNPAUSED;
00365   _cursor.fix_at = false;
00366 
00367   CheckForMissingSprites();
00368   CheckForMissingGlyphsInLoadedLanguagePack();
00369 
00370   /* Play main theme */
00371   if (_music_driver->IsSongPlaying()) ResetMusic();
00372 }
00373 
00374 void MakeNewgameSettingsLive()
00375 {
00376 #ifdef ENABLE_AI
00377   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00378     if (_settings_game.ai_config[c] != NULL) {
00379       delete _settings_game.ai_config[c];
00380     }
00381   }
00382 #endif /* ENABLE_AI */
00383 
00384   /* Copy newgame settings to active settings.
00385    * Also initialise old settings needed for savegame conversion. */
00386   _settings_game = _settings_newgame;
00387   _old_vds = _settings_client.company.vehicle;
00388 
00389 #ifdef ENABLE_AI
00390   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00391     _settings_game.ai_config[c] = NULL;
00392     if (_settings_newgame.ai_config[c] != NULL) {
00393       _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
00394     }
00395   }
00396 #endif /* ENABLE_AI */
00397 }
00398 
00399 #if defined(UNIX) && !defined(__MORPHOS__)
00400 extern void DedicatedFork();
00401 #endif
00402 
00403 int ttd_main(int argc, char *argv[])
00404 {
00405   int i;
00406   const char *optformat;
00407   char *musicdriver = NULL;
00408   char *sounddriver = NULL;
00409   char *videodriver = NULL;
00410   char *blitter = NULL;
00411   char *graphics_set = NULL;
00412   char *sounds_set = NULL;
00413   char *music_set = NULL;
00414   Dimension resolution = {0, 0};
00415   Year startyear = INVALID_YEAR;
00416   uint generation_seed = GENERATE_NEW_SEED;
00417   bool save_config = true;
00418 #if defined(ENABLE_NETWORK)
00419   bool dedicated = false;
00420   bool network   = false;
00421   char *network_conn = NULL;
00422   char *debuglog_conn = NULL;
00423   char *dedicated_host = NULL;
00424   uint16 dedicated_port = 0;
00425   char *join_server_password = NULL;
00426   char *join_company_password = NULL;
00427 
00428   extern bool _dedicated_forks;
00429   _dedicated_forks = false;
00430 #endif /* ENABLE_NETWORK */
00431 
00432   _game_mode = GM_MENU;
00433   _switch_mode = SM_MENU;
00434   _switch_mode_errorstr = INVALID_STRING_ID;
00435   _config_file = NULL;
00436 
00437   /* The last param of the following function means this:
00438    *   a letter means: it accepts that param (e.g.: -h)
00439    *   a ':' behind it means: it need a param (e.g.: -m<driver>)
00440    *   a '::' behind it means: it can optional have a param (e.g.: -d<debug>) */
00441   optformat = "m:s:v:b:hD::n::ei::I:S:M:t:d::r:g::G:c:xl:p:P:"
00442 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00443     "f"
00444 #endif
00445   ;
00446 
00447   MyGetOptData mgo(argc - 1, argv + 1, optformat);
00448 
00449   while ((i = MyGetOpt(&mgo)) != -1) {
00450     switch (i) {
00451     case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
00452     case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
00453     case 'M': free(music_set); music_set = strdup(mgo.opt); break;
00454     case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
00455     case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
00456     case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
00457     case 'b': free(blitter); blitter = strdup(mgo.opt); break;
00458 #if defined(ENABLE_NETWORK)
00459     case 'D':
00460       free(musicdriver);
00461       free(sounddriver);
00462       free(videodriver);
00463       free(blitter);
00464       musicdriver = strdup("null");
00465       sounddriver = strdup("null");
00466       videodriver = strdup("dedicated");
00467       blitter = strdup("null");
00468       dedicated = true;
00469       SetDebugString("net=6");
00470       if (mgo.opt != NULL) {
00471         /* Use the existing method for parsing (openttd -n).
00472          * However, we do ignore the #company part. */
00473         const char *temp = NULL;
00474         const char *port = NULL;
00475         ParseConnectionString(&temp, &port, mgo.opt);
00476         if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
00477         if (port != NULL) dedicated_port = atoi(port);
00478       }
00479       break;
00480     case 'f': _dedicated_forks = true; break;
00481     case 'n':
00482       network = true;
00483       network_conn = mgo.opt; // optional IP parameter, NULL if unset
00484       break;
00485     case 'l':
00486       debuglog_conn = mgo.opt;
00487       break;
00488     case 'p':
00489       join_server_password = mgo.opt;
00490       break;
00491     case 'P':
00492       join_company_password = mgo.opt;
00493       break;
00494 #endif /* ENABLE_NETWORK */
00495     case 'r': ParseResolution(&resolution, mgo.opt); break;
00496     case 't': startyear = atoi(mgo.opt); break;
00497     case 'd': {
00498 #if defined(WIN32)
00499         CreateConsole();
00500 #endif
00501         if (mgo.opt != NULL) SetDebugString(mgo.opt);
00502         break;
00503       }
00504     case 'e': _switch_mode = SM_EDITOR; break;
00505     case 'i':
00506       /* there is an argument, it is not empty, and it is exactly 1 char long */
00507       if (!StrEmpty(mgo.opt) && mgo.opt[1] == '\0') {
00508         _use_palette = (PaletteType)(mgo.opt[0] - '0');
00509         if (_use_palette <= MAX_PAL) break;
00510       }
00511       usererror("Valid value for '-i' is 0, 1 or 2");
00512     case 'g':
00513       if (mgo.opt != NULL) {
00514         strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
00515         _switch_mode = SM_LOAD;
00516         _file_to_saveload.mode = SL_LOAD;
00517 
00518         /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
00519         const char *t = strrchr(_file_to_saveload.name, '.');
00520         if (t != NULL) {
00521           FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
00522           if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
00523         }
00524 
00525         break;
00526       }
00527 
00528       _switch_mode = SM_NEWGAME;
00529       /* Give a random map if no seed has been given */
00530       if (generation_seed == GENERATE_NEW_SEED) {
00531         generation_seed = InteractiveRandom();
00532       }
00533       break;
00534     case 'G': generation_seed = atoi(mgo.opt); break;
00535     case 'c': _config_file = strdup(mgo.opt); break;
00536     case 'x': save_config = false; break;
00537     case -2:
00538     case 'h':
00539       /* The next two functions are needed to list the graphics sets.
00540        * We can't do them earlier because then we can't show it on
00541        * the debug console as that hasn't been configured yet. */
00542       DeterminePaths(argv[0]);
00543       BaseGraphics::FindSets();
00544       BaseSounds::FindSets();
00545       BaseMusic::FindSets();
00546       ShowHelp();
00547       return 0;
00548     }
00549   }
00550 
00551 #if defined(WINCE) && defined(_DEBUG)
00552   /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
00553   SetDebugString("4");
00554 #endif
00555 
00556   DeterminePaths(argv[0]);
00557   BaseGraphics::FindSets();
00558   BaseSounds::FindSets();
00559   BaseMusic::FindSets();
00560 
00561 #if defined(ENABLE_NETWORK) && defined(UNIX) && !defined(__MORPHOS__)
00562   /* We must fork here, or we'll end up without some resources we need (like sockets) */
00563   if (_dedicated_forks) DedicatedFork();
00564 #endif
00565 
00566   TarScanner::DoScan();
00567   AI::Initialize();
00568   LoadFromConfig();
00569   AI::Uninitialize(true);
00570   CheckConfig();
00571   LoadFromHighScore();
00572   LoadHotkeysFromConfig();
00573 
00574   if (resolution.width != 0) { _cur_resolution = resolution; }
00575   if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
00576   if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
00577 
00578   /*
00579    * The width and height must be at least 1 pixel and width times
00580    * height times bytes per pixel must still fit within a 32 bits
00581    * integer, even for 32 bpp video modes. This way all internal
00582    * drawing routines work correctly.
00583    */
00584   _cur_resolution.width  = ClampU(_cur_resolution.width,  1, UINT16_MAX / 2);
00585   _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
00586 
00587 #if defined(ENABLE_NETWORK)
00588   if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
00589   if (dedicated_host) {
00590     _network_bind_list.Clear();
00591     *_network_bind_list.Append() = strdup(dedicated_host);
00592   }
00593   if (dedicated_port) _settings_client.network.server_port = dedicated_port;
00594   if (_dedicated_forks && !dedicated) _dedicated_forks = false;
00595 #endif /* ENABLE_NETWORK */
00596 
00597   /* enumerate language files */
00598   InitializeLanguagePacks();
00599 
00600   /* initialize screenshot formats */
00601   InitializeScreenshotFormats();
00602 
00603   /* Initialize FreeType */
00604   InitFreeType();
00605 
00606   /* This must be done early, since functions use the SetWindowDirty* calls */
00607   InitWindowSystem();
00608 
00609   /* Look for the sounds before the graphics. Otherwise none would be set and
00610    * the first initialisation of the video happens on the wrong data. Now it
00611    * can do the first initialisation right. */
00612   if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set);
00613   if (!BaseSounds::SetSet(sounds_set)) {
00614     StrEmpty(sounds_set) ?
00615       usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.") :
00616       usererror("Failed to select requested sounds set '%s'", sounds_set);
00617   }
00618   free(sounds_set);
00619 
00620   if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set);
00621   if (!BaseGraphics::SetSet(graphics_set)) {
00622     StrEmpty(graphics_set) ?
00623       usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD. See section 4.1 of readme.txt.") :
00624       usererror("Failed to select requested graphics set '%s'", graphics_set);
00625   }
00626   free(graphics_set);
00627 
00628   if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set);
00629   if (!BaseMusic::SetSet(music_set)) {
00630     StrEmpty(music_set) ?
00631       usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.") :
00632       usererror("Failed to select requested music set '%s'", music_set);
00633   }
00634   free(music_set);
00635 
00636   /* Initialize game palette */
00637   GfxInitPalettes();
00638 
00639   DEBUG(misc, 1, "Loading blitter...");
00640   if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter);
00641   if (BlitterFactoryBase::SelectBlitter(blitter) == NULL) {
00642     StrEmpty(blitter) ?
00643       usererror("Failed to autoprobe blitter") :
00644       usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
00645   }
00646   free(blitter);
00647 
00648   DEBUG(driver, 1, "Loading drivers...");
00649 
00650   if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver);
00651   _sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
00652   if (_sound_driver == NULL) {
00653     StrEmpty(sounddriver) ?
00654       usererror("Failed to autoprobe sound driver") :
00655       usererror("Failed to select requested sound driver '%s'", sounddriver);
00656   }
00657   free(sounddriver);
00658 
00659   if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver);
00660   _video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
00661   if (_video_driver == NULL) {
00662     StrEmpty(videodriver) ?
00663       usererror("Failed to autoprobe video driver") :
00664       usererror("Failed to select requested video driver '%s'", videodriver);
00665   }
00666   free(videodriver);
00667 
00668   if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver);
00669   _music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
00670   if (_music_driver == NULL) {
00671     StrEmpty(musicdriver) ?
00672       usererror("Failed to autoprobe music driver") :
00673       usererror("Failed to select requested music driver '%s'", musicdriver);
00674   }
00675   free(musicdriver);
00676 
00677   /* Initialize the zoom level of the screen to normal */
00678   _screen.zoom = ZOOM_LVL_NORMAL;
00679 
00680   /* restore saved music volume */
00681   _music_driver->SetVolume(_msf.music_vol);
00682 
00683   NetworkStartUp(); // initialize network-core
00684 
00685 #if defined(ENABLE_NETWORK)
00686   if (debuglog_conn != NULL && _network_available) {
00687     const char *not_used = NULL;
00688     const char *port = NULL;
00689     uint16 rport;
00690 
00691     rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
00692 
00693     ParseConnectionString(&not_used, &port, debuglog_conn);
00694     if (port != NULL) rport = atoi(port);
00695 
00696     NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
00697   }
00698 #endif /* ENABLE_NETWORK */
00699 
00700   ScanNewGRFFiles();
00701 
00702   ResetGRFConfig(false);
00703 
00704   /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
00705   if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
00706 
00707   /* initialize the ingame console */
00708   IConsoleInit();
00709   _cursor.in_window = true;
00710   InitializeGUI();
00711   IConsoleCmdExec("exec scripts/autoexec.scr 0");
00712 
00713   /* Take our initial lock on whatever we might want to do! */
00714   _genworld_paint_mutex->BeginCritical();
00715   _genworld_mapgen_mutex->BeginCritical();
00716 
00717   GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
00718   WaitTillGeneratedWorld();
00719 
00720   CheckForMissingGlyphsInLoadedLanguagePack();
00721 
00722 #ifdef ENABLE_NETWORK
00723   if (network && _network_available) {
00724     if (network_conn != NULL) {
00725       const char *port = NULL;
00726       const char *company = NULL;
00727       uint16 rport = NETWORK_DEFAULT_PORT;
00728       CompanyID join_as = COMPANY_NEW_COMPANY;
00729 
00730       ParseConnectionString(&company, &port, network_conn);
00731 
00732       if (company != NULL) {
00733         join_as = (CompanyID)atoi(company);
00734 
00735         if (join_as != COMPANY_SPECTATOR) {
00736           join_as--;
00737           if (join_as >= MAX_COMPANIES) return false;
00738         }
00739       }
00740       if (port != NULL) rport = atoi(port);
00741 
00742       LoadIntroGame();
00743       _switch_mode = SM_NONE;
00744       NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
00745     }
00746   }
00747 #endif /* ENABLE_NETWORK */
00748 
00749   _video_driver->MainLoop();
00750 
00751   WaitTillSaved();
00752 
00753   /* only save config if we have to */
00754   if (save_config) {
00755     SaveToConfig();
00756     SaveHotkeysToConfig();
00757     SaveToHighScore();
00758   }
00759 
00760   /* Reset windowing system, stop drivers, free used memory, ... */
00761   ShutdownGame();
00762 
00763   free(const_cast<char *>(BaseGraphics::ini_set));
00764   free(const_cast<char *>(BaseSounds::ini_set));
00765   free(const_cast<char *>(BaseMusic::ini_set));
00766   free(_ini_musicdriver);
00767   free(_ini_sounddriver);
00768   free(_ini_videodriver);
00769   free(_ini_blitter);
00770 
00771   return 0;
00772 }
00773 
00774 void HandleExitGameRequest()
00775 {
00776   if (_game_mode == GM_MENU) { // do not ask to quit on the main screen
00777     _exit_game = true;
00778   } else if (_settings_client.gui.autosave_on_exit) {
00779     DoExitSave();
00780     _exit_game = true;
00781   } else {
00782     AskExitGame();
00783   }
00784 }
00785 
00786 static void MakeNewGameDone()
00787 {
00788   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
00789 
00790   /* In a dedicated server, the server does not play */
00791   if (_network_dedicated || BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 0) {
00792     SetLocalCompany(COMPANY_SPECTATOR);
00793     IConsoleCmdExec("exec scripts/game_start.scr 0");
00794     return;
00795   }
00796 
00797   /* Create a single company */
00798   DoStartupNewCompany(false);
00799 
00800   Company *c = Company::Get(COMPANY_FIRST);
00801   c->settings = _settings_client.company;
00802 
00803   IConsoleCmdExec("exec scripts/game_start.scr 0");
00804 
00805   SetLocalCompany(COMPANY_FIRST);
00806 
00807   InitializeRailGUI();
00808 
00809 #ifdef ENABLE_NETWORK
00810   /* We are the server, we start a new company (not dedicated),
00811    * so set the default password *if* needed. */
00812   if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
00813     NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
00814   }
00815 #endif /* ENABLE_NETWORK */
00816 
00817   if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
00818 
00819   MarkWholeScreenDirty();
00820 }
00821 
00822 static void MakeNewGame(bool from_heightmap, bool reset_settings)
00823 {
00824   _game_mode = GM_NORMAL;
00825 
00826   ResetGRFConfig(true);
00827 
00828   GenerateWorldSetCallback(&MakeNewGameDone);
00829   GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
00830 }
00831 
00832 static void MakeNewEditorWorldDone()
00833 {
00834   SetLocalCompany(OWNER_NONE);
00835 }
00836 
00837 static void MakeNewEditorWorld()
00838 {
00839   _game_mode = GM_EDITOR;
00840 
00841   ResetGRFConfig(true);
00842 
00843   GenerateWorldSetCallback(&MakeNewEditorWorldDone);
00844   GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00845 }
00846 
00857 bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
00858 {
00859   assert(mode == SL_LOAD || (lf == NULL && mode == SL_OLD_LOAD));
00860   GameMode ogm = _game_mode;
00861 
00862   _game_mode = newgm;
00863 
00864   switch (lf == NULL ? SaveOrLoad(filename, mode, subdir) : LoadWithFilter(lf)) {
00865     case SL_OK: return true;
00866 
00867     case SL_REINIT:
00868 #ifdef ENABLE_NETWORK
00869       if (_network_dedicated) {
00870         /*
00871          * We need to reinit a network map...
00872          * We can't simply load the intro game here as that game has many
00873          * special cases which make clients desync immediately. So we fall
00874          * back to just generating a new game with the current settings.
00875          */
00876         DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
00877         MakeNewGame(false, true);
00878         return false;
00879       }
00880       if (_network_server) {
00881         /* We can't load the intro game as server, so disconnect first. */
00882         NetworkDisconnect();
00883       }
00884 #endif /* ENABLE_NETWORK */
00885 
00886       switch (ogm) {
00887         default:
00888         case GM_MENU:   LoadIntroGame();      break;
00889         case GM_EDITOR: MakeNewEditorWorld(); break;
00890       }
00891       return false;
00892 
00893     default:
00894       _game_mode = ogm;
00895       return false;
00896   }
00897 }
00898 
00899 void SwitchToMode(SwitchMode new_mode)
00900 {
00901 #ifdef ENABLE_NETWORK
00902   /* If we are saving something, the network stays in his current state */
00903   if (new_mode != SM_SAVE) {
00904     /* If the network is active, make it not-active */
00905     if (_networking) {
00906       if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
00907         NetworkReboot();
00908       } else {
00909         NetworkDisconnect();
00910       }
00911     }
00912 
00913     /* If we are a server, we restart the server */
00914     if (_is_network_server) {
00915       /* But not if we are going to the menu */
00916       if (new_mode != SM_MENU) {
00917         /* check if we should reload the config */
00918         if (_settings_client.network.reload_cfg) {
00919           LoadFromConfig();
00920           MakeNewgameSettingsLive();
00921           ResetGRFConfig(false);
00922         }
00923         NetworkServerStart();
00924       } else {
00925         /* This client no longer wants to be a network-server */
00926         _is_network_server = false;
00927       }
00928     }
00929   }
00930 #endif /* ENABLE_NETWORK */
00931   /* Make sure all AI controllers are gone at quiting game */
00932   if (new_mode != SM_SAVE) AI::KillAll();
00933 
00934   switch (new_mode) {
00935     case SM_EDITOR: // Switch to scenario editor
00936       MakeNewEditorWorld();
00937       break;
00938 
00939     case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
00940     case SM_NEWGAME: // New Game --> 'Random game'
00941 #ifdef ENABLE_NETWORK
00942       if (_network_server) {
00943         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
00944       }
00945 #endif /* ENABLE_NETWORK */
00946       MakeNewGame(false, new_mode == SM_NEWGAME);
00947       break;
00948 
00949     case SM_LOAD: { // Load game, Play Scenario
00950       ResetGRFConfig(true);
00951       ResetWindowSystem();
00952 
00953       if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
00954         SetDParamStr(0, GetSaveLoadErrorString());
00955         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
00956       } else {
00957         if (_saveload_mode == SLD_LOAD_SCENARIO) {
00958           StartupEngines();
00959         }
00960         /* Update the local company for a loaded game. It is either always
00961          * company #1 (eg 0) or in the case of a dedicated server a spectator */
00962         SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
00963         /* Execute the game-start script */
00964         IConsoleCmdExec("exec scripts/game_start.scr 0");
00965         /* Decrease pause counter (was increased from opening load dialog) */
00966         DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
00967 #ifdef ENABLE_NETWORK
00968         if (_network_server) {
00969           snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
00970         }
00971 #endif /* ENABLE_NETWORK */
00972       }
00973       break;
00974     }
00975 
00976     case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
00977 #ifdef ENABLE_NETWORK
00978       if (_network_server) {
00979         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
00980       }
00981 #endif /* ENABLE_NETWORK */
00982       MakeNewGame(true, true);
00983       break;
00984 
00985     case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
00986       SetLocalCompany(OWNER_NONE);
00987 
00988       GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00989       MarkWholeScreenDirty();
00990       break;
00991 
00992     case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
00993       if (SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
00994         SetLocalCompany(OWNER_NONE);
00995         _settings_newgame.game_creation.starting_year = _cur_year;
00996         /* Cancel the saveload pausing */
00997         DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
00998       } else {
00999         SetDParamStr(0, GetSaveLoadErrorString());
01000         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01001       }
01002       break;
01003     }
01004 
01005     case SM_MENU: // Switch to game intro menu
01006       LoadIntroGame();
01007       if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
01008         ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
01009         BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name);
01010       }
01011       break;
01012 
01013     case SM_SAVE: // Save game
01014       /* Make network saved games on pause compatible to singleplayer */
01015       if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
01016         SetDParamStr(0, GetSaveLoadErrorString());
01017         ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01018       } else {
01019         DeleteWindowById(WC_SAVELOAD, 0);
01020       }
01021       break;
01022 
01023     case SM_GENRANDLAND: // Generate random land within scenario editor
01024       SetLocalCompany(OWNER_NONE);
01025       GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01026       /* XXX: set date */
01027       MarkWholeScreenDirty();
01028       break;
01029 
01030     default: NOT_REACHED();
01031   }
01032 
01033   if (_switch_mode_errorstr != INVALID_STRING_ID) {
01034     ShowErrorMessage(_switch_mode_errorstr, INVALID_STRING_ID, WL_CRITICAL);
01035     _switch_mode_errorstr = INVALID_STRING_ID;
01036   }
01037 }
01038 
01039 
01046 static void CheckCaches()
01047 {
01048   /* Return here so it is easy to add checks that are run
01049    * always to aid testing of caches. */
01050   if (_debug_desync_level <= 1) return;
01051 
01052   /* Strict checking of the road stop cache entries */
01053   const RoadStop *rs;
01054   FOR_ALL_ROADSTOPS(rs) {
01055     if (IsStandardRoadStopTile(rs->xy)) continue;
01056 
01057     assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
01058     rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
01059     rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
01060   }
01061 
01062   Vehicle *v;
01063   FOR_ALL_VEHICLES(v) {
01064     extern void FillNewGRFVehicleCache(const Vehicle *v);
01065     if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
01066 
01067     uint length = 0;
01068     for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
01069 
01070     NewGRFCache        *grf_cache = CallocT<NewGRFCache>(length);
01071     VehicleCache       *veh_cache = CallocT<VehicleCache>(length);
01072     GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
01073     TrainCache         *tra_cache = CallocT<TrainCache>(length);
01074 
01075     length = 0;
01076     for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01077       FillNewGRFVehicleCache(u);
01078       grf_cache[length] = u->grf_cache;
01079       veh_cache[length] = u->vcache;
01080       switch (u->type) {
01081         case VEH_TRAIN:
01082           gro_cache[length] = Train::From(u)->gcache;
01083           tra_cache[length] = Train::From(u)->tcache;
01084           break;
01085         case VEH_ROAD:
01086           gro_cache[length] = RoadVehicle::From(u)->gcache;
01087           break;
01088         default:
01089           break;
01090       }
01091       length++;
01092     }
01093 
01094     switch (v->type) {
01095       case VEH_TRAIN:    Train::From(v)->ConsistChanged(true);     break;
01096       case VEH_ROAD:     RoadVehUpdateCache(RoadVehicle::From(v)); break;
01097       case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v));   break;
01098       case VEH_SHIP:     Ship::From(v)->UpdateCache();             break;
01099       default: break;
01100     }
01101 
01102     length = 0;
01103     for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01104       FillNewGRFVehicleCache(u);
01105       if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
01106         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);
01107       }
01108       if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
01109         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);
01110       }
01111       switch (u->type) {
01112         case VEH_TRAIN:
01113           if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01114             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);
01115           }
01116           if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
01117             DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01118           }
01119           break;
01120         case VEH_ROAD:
01121           if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01122             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);
01123           }
01124           break;
01125         default:
01126           break;
01127       }
01128       length++;
01129     }
01130 
01131     free(grf_cache);
01132     free(veh_cache);
01133     free(gro_cache);
01134     free(tra_cache);
01135   }
01136 
01137   /* Check whether the caches are still valid */
01138   FOR_ALL_VEHICLES(v) {
01139     byte buff[sizeof(VehicleCargoList)];
01140     memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
01141     v->cargo.InvalidateCache();
01142     assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
01143   }
01144 
01145   Station *st;
01146   FOR_ALL_STATIONS(st) {
01147     for (CargoID c = 0; c < NUM_CARGO; c++) {
01148       byte buff[sizeof(StationCargoList)];
01149       memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
01150       st->goods[c].cargo.InvalidateCache();
01151       assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
01152     }
01153   }
01154 }
01155 
01161 void StateGameLoop()
01162 {
01163   /* dont execute the state loop during pause */
01164   if (_pause_mode != PM_UNPAUSED) {
01165     UpdateLandscapingLimits();
01166     CallWindowTickEvent();
01167     return;
01168   }
01169   if (IsGeneratingWorld()) return;
01170 
01171   ClearStorageChanges(false);
01172 
01173   if (_game_mode == GM_EDITOR) {
01174     RunTileLoop();
01175     CallVehicleTicks();
01176     CallLandscapeTick();
01177     ClearStorageChanges(true);
01178     UpdateLandscapingLimits();
01179 
01180     CallWindowTickEvent();
01181     NewsLoop();
01182   } else {
01183     if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
01184       /* Save the desync savegame if needed. */
01185       char name[MAX_PATH];
01186       snprintf(name, lengthof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
01187       SaveOrLoad(name, SL_SAVE, AUTOSAVE_DIR, false);
01188     }
01189 
01190     CheckCaches();
01191 
01192     /* All these actions has to be done from OWNER_NONE
01193      *  for multiplayer compatibility */
01194     Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
01195 
01196     AnimateAnimatedTiles();
01197     IncreaseDate();
01198     RunTileLoop();
01199     CallVehicleTicks();
01200     CallLandscapeTick();
01201     ClearStorageChanges(true);
01202 
01203     AI::GameLoop();
01204     UpdateLandscapingLimits();
01205 
01206     CallWindowTickEvent();
01207     NewsLoop();
01208     cur_company.Restore();
01209   }
01210 
01211   assert(IsLocalCompany());
01212 }
01213 
01218 static void DoAutosave()
01219 {
01220   char buf[MAX_PATH];
01221 
01222 #if defined(PSP)
01223   /* Autosaving in networking is too time expensive for the PSP */
01224   if (_networking) return;
01225 #endif /* PSP */
01226 
01227   if (_settings_client.gui.keep_all_autosave) {
01228     GenerateDefaultSaveName(buf, lastof(buf));
01229     strecat(buf, ".sav", lastof(buf));
01230   } else {
01231     static int _autosave_ctr = 0;
01232 
01233     /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
01234     snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
01235 
01236     if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
01237   }
01238 
01239   DEBUG(sl, 2, "Autosaving to '%s'", buf);
01240   if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
01241     ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
01242   }
01243 }
01244 
01245 void GameLoop()
01246 {
01247   ProcessAsyncSaveFinish();
01248 
01249   /* autosave game? */
01250   if (_do_autosave) {
01251     _do_autosave = false;
01252     DoAutosave();
01253     SetWindowDirty(WC_STATUS_BAR, 0);
01254   }
01255 
01256   /* switch game mode? */
01257   if (_switch_mode != SM_NONE) {
01258     SwitchToMode(_switch_mode);
01259     _switch_mode = SM_NONE;
01260   }
01261 
01262   IncreaseSpriteLRU();
01263   InteractiveRandom();
01264 
01265   extern int _caret_timer;
01266   _caret_timer += 3;
01267   CursorTick();
01268 
01269 #ifdef ENABLE_NETWORK
01270   /* Check for UDP stuff */
01271   if (_network_available) NetworkUDPGameLoop();
01272 
01273   if (_networking && !IsGeneratingWorld()) {
01274     /* Multiplayer */
01275     NetworkGameLoop();
01276   } else {
01277     if (_network_reconnect > 0 && --_network_reconnect == 0) {
01278       /* This means that we want to reconnect to the last host
01279        * We do this here, because it means that the network is really closed */
01280       NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
01281     }
01282     /* Singleplayer */
01283     StateGameLoop();
01284   }
01285 
01286   /* Check chat messages roughly once a second. */
01287   static uint check_message = 0;
01288   if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
01289     check_message = 0;
01290     NetworkChatMessageLoop();
01291   }
01292 #else
01293   StateGameLoop();
01294 #endif /* ENABLE_NETWORK */
01295 
01296   if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
01297 
01298   if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
01299 
01300   InputLoop();
01301 
01302   _sound_driver->MainLoop();
01303   MusicLoop();
01304 }