openttd.cpp

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

Generated on Sun Jan 23 01:49:06 2011 for OpenTTD by  doxygen 1.6.1