# openttd.cpp

Go to the documentation of this file.

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