# openttd.cpp

Go to the documentation of this file.

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