# openttd.cpp

Go to the documentation of this file.

    00001 /* $Id: openttd.cpp 14385 2008-09-22 19:57:31Z rubidium $ */
    00002
    00005 #include "stdafx.h"
    00006 #define VARDEF
    00007 #include "debug.h"
    00008 #include "driver.h"
    00009 #include "saveload.h"
    00010
    00011 #include "openttd.h"
    00012 #include "bridge_map.h"
    00013 #include "mixer.h"
    00014 #include "spritecache.h"
    00015 #include "gfxinit.h"
    00016 #include "gui.h"
    00017 #include "landscape.h"
    00018 #include "station.h"
    00019 #include "station_map.h"
    00020 #include "town_map.h"
    00021 #include "tunnel_map.h"
    00022 #include "viewport_func.h"
    00023 #include "gfx_func.h"
    00024 #include "window_func.h"
    00025 #include "window_gui.h"
    00026 #include "player_func.h"
    00027 #include "player_base.h"
    00028 #include "command_func.h"
    00029 #include "town.h"
    00030 #include "industry.h"
    00031 #include "news.h"
    00032 #include "engine.h"
    00033 #include "fileio.h"
    00034 #include "fios.h"
    00035 #include "airport.h"
    00036 #include "aircraft.h"
    00037 #include "console.h"
    00038 #include "screenshot.h"
    00039 #include "network/network.h"
    00040 #include "network/network_internal.h"
    00041 #include "signs.h"
    00042 #include "depot.h"
    00043 #include "waypoint.h"
    00044 #include "ai/ai.h"
    00045 #include "train.h"
    00046 #include "yapf/yapf.h"
    00047 #include "settings_func.h"
    00048 #include "genworld.h"
    00049 #include "clear_map.h"
    00050 #include "fontcache.h"
    00051 #include "newgrf.h"
    00052 #include "newgrf_config.h"
    00053 #include "newgrf_house.h"
    00054 #include "newgrf_commons.h"
    00055 #include "newgrf_storage.h"
    00056 #include "player_face.h"
    00057 #include "group.h"
    00058 #include "blitter/factory.hpp"
    00059 #include "sound/sound_driver.hpp"
    00060 #include "music/music_driver.hpp"
    00061 #include "video/video_driver.hpp"
    00062 #include "strings_func.h"
    00063 #include "zoom_func.h"
    00064 #include "date_func.h"
    00065 #include "vehicle_func.h"
    00066 #include "sound_func.h"
    00067 #include "variables.h"
    00068 #include "road_func.h"
    00069
    00070 #include "bridge_map.h"
    00071 #include "clear_map.h"
    00072 #include "rail_map.h"
    00073 #include "road_map.h"
    00074 #include "water_map.h"
    00075 #include "industry_map.h"
    00076 #include "unmovable_map.h"
    00077 #include "tree_map.h"
    00078 #include "tunnelbridge_map.h"
    00079 #include "void_map.h"
    00080 #include "water.h"
    00081
    00082 #include <stdarg.h>
    00083
    00084 #include "table/strings.h"
    00085
    00086 void CallLandscapeTick();
    00087 void IncreaseDate();
    00088 void DoPaletteAnimations();
    00089 void MusicLoop();
    00090 void ResetMusic();
    00091
    00092 extern void SetDifficultyLevel(int mode, GameOptions *gm_opt);
    00093 extern Player* DoStartupNewPlayer(bool is_ai);
    00094 extern void ShowOSErrorBox(const char *buf);
    00095 extern void SetDefaultRailGui();
    00096
    00097 /* TODO: usrerror() for errors which are not of an internal nature but
    00098  * caused by the user, i.e. missing files or fatal configuration errors.
    00099  * Post-0.4.0 since Celestar doesn't want this in SVN before. --pasky */
    00100
    00101 void CDECL error(const char *s, ...)
    00102 {
    00103   va_list va;
    00104   char buf[512];
    00105
    00106   va_start(va, s);
    00107   vsnprintf(buf, lengthof(buf), s, va);
    00108   va_end(va);
    00109
    00110   ShowOSErrorBox(buf);
    00111   if (_video_driver != NULL) _video_driver->Stop();
    00112
    00113   assert(0);
    00114   exit(1);
    00115 }
    00116
    00117 void CDECL ShowInfoF(const char *str, ...)
    00118 {
    00119   va_list va;
    00120   char buf[1024];
    00121   va_start(va, str);
    00122   vsnprintf(buf, lengthof(buf), str, va);
    00123   va_end(va);
    00124   ShowInfo(buf);
    00125 }
    00126
    00127
    00128 extern const char _openttd_revision[];
    00129 static void showhelp()
    00130 {
    00131   char buf[4096], *p;
    00132
    00133   p = buf;
    00134
    00135   p += snprintf(p, lengthof(buf), "OpenTTD %s\n", _openttd_revision);
    00136   p = strecpy(p,
    00137     "\n"
    00138     "\n"
    00139     "Command line options:\n"
    00140     "  -v drv              = Set video driver (see below)\n"
    00141     "  -s drv              = Set sound driver (see below) (param bufsize,hz)\n"
    00142     "  -m drv              = Set music driver (see below)\n"
    00143     "  -b drv              = Set the blitter to use (see below)\n"
    00144     "  -r res              = Set resolution (for instance 800x600)\n"
    00145     "  -h                  = Display this help text\n"
    00146     "  -t year             = Set starting year\n"
    00147     "  -d [[fac=]lvl[,...]]= Debug mode\n"
    00148     "  -e                  = Start Editor\n"
    00149     "  -g [savegame]       = Start new/save game immediately\n"
    00150     "  -G seed             = Set random seed\n"
    00151 #if defined(ENABLE_NETWORK)
    00152     "  -n [ip:port#player] = Start networkgame\n"
    00153     "  -D [ip][:port]      = Start dedicated server\n"
    00154     "  -l ip[:port]        = Redirect DEBUG()\n"
    00155 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
    00156     "  -f                  = Fork into the background (dedicated only)\n"
    00157 #endif
    00158 #endif /* ENABLE_NETWORK */
    00159     "  -i                  = Force to use the DOS palette\n"
    00160     "                          (use this if you see a lot of pink)\n"
    00161     "  -c config_file      = Use 'config_file' instead of 'openttd.cfg'\n"
    00162     "  -x                  = Do not automatically save to config file on exit\n",
    00163     lastof(buf)
    00164   );
    00165
    00166   /* List the drivers */
    00167   p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
    00168
    00169   /* List the blitters */
    00170   p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
    00171
    00172   /* ShowInfo put output to stderr, but version information should go
    00173    * to stdout; this is the only exception */
    00174 #if !defined(WIN32) && !defined(WIN64)
    00175   printf("%s\n", buf);
    00176 #else
    00177   ShowInfo(buf);
    00178 #endif
    00179 }
    00180
    00181
    00182 struct MyGetOptData {
    00183   char *opt;
    00184   int numleft;
    00185   char **argv;
    00186   const char *options;
    00187   const char *cont;
    00188
    00189   MyGetOptData(int argc, char **argv, const char *options)
    00190   {
    00191     opt = NULL;
    00192     numleft = argc;
    00193     this->argv = argv;
    00194     this->options = options;
    00195     cont = NULL;
    00196   }
    00197 };
    00198
    00199 static int MyGetOpt(MyGetOptData *md)
    00200 {
    00201   const char *s,*r,*t;
    00202
    00203   s = md->cont;
    00204   if (s != NULL)
    00205     goto md_continue_here;
    00206
    00207   for (;;) {
    00208     if (--md->numleft < 0) return -1;
    00209
    00210     s = *md->argv++;
    00211     if (*s == '-') {
    00212 md_continue_here:;
    00213       s++;
    00214       if (*s != 0) {
    00215         /* Found argument, try to locate it in options. */
    00216         if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
    00217           /* ERROR! */
    00218           return -2;
    00219         }
    00220         if (r[1] == ':') {
    00221           /* Item wants an argument. Check if the argument follows, or if it comes as a separate arg. */
    00222           if (!*(t = s + 1)) {
    00223             /* It comes as a separate arg. Check if out of args? */
    00224             if (--md->numleft < 0 || *(t = *md->argv) == '-') {
    00225               /* Check if item is optional? */
    00226               if (r[2] != ':')
    00227                 return -2;
    00228               md->numleft++;
    00229               t = NULL;
    00230             } else {
    00231               md->argv++;
    00232             }
    00233           }
    00234           md->opt = (char*)t;
    00235           md->cont = NULL;
    00236           return *s;
    00237         }
    00238         md->opt = NULL;
    00239         md->cont = s;
    00240         return *s;
    00241       }
    00242     } else {
    00243       /* This is currently not supported. */
    00244       return -2;
    00245     }
    00246   }
    00247 }
    00248
    00249
    00250 static void ParseResolution(int res[2], const char *s)
    00251 {
    00252   const char *t = strchr(s, 'x');
    00253   if (t == NULL) {
    00254     ShowInfoF("Invalid resolution '%s'", s);
    00255     return;
    00256   }
    00257
    00258   res[0] = Clamp(strtoul(s, NULL, 0), 64, MAX_SCREEN_WIDTH);
    00259   res[1] = Clamp(strtoul(t + 1, NULL, 0), 64, MAX_SCREEN_HEIGHT);
    00260 }
    00261
    00262 static void InitializeDynamicVariables()
    00263 {
    00264   /* Dynamic stuff needs to be initialized somewhere... */
    00265   _town_sort     = NULL;
    00266   _industry_sort = NULL;
    00267   _industry_mngr.ResetMapping();
    00268   _industile_mngr.ResetMapping();
    00269 }
    00270
    00271
    00272 static void UnInitializeGame()
    00273 {
    00274   UnInitWindowSystem();
    00275
    00276   /* Uninitialize airport state machines */
    00277   UnInitializeAirports();
    00278
    00279   /* Uninitialize variables that are allocated dynamically */
    00280   _Town_pool.CleanPool();
    00281   _Industry_pool.CleanPool();
    00282   _Station_pool.CleanPool();
    00283   _Vehicle_pool.CleanPool();
    00284   _Sign_pool.CleanPool();
    00285   _Order_pool.CleanPool();
    00286   _Group_pool.CleanPool();
    00287   _CargoPacket_pool.CleanPool();
    00288
    00289   free((void*)_town_sort);
    00290   free((void*)_industry_sort);
    00291
    00292   free(_config_file);
    00293 }
    00294
    00295 static void LoadIntroGame()
    00296 {
    00297   _game_mode = GM_MENU;
    00298
    00299   _opt_ptr = &_opt_newgame;
    00300   ResetGRFConfig(false);
    00301
    00302   /* Setup main window */
    00303   ResetWindowSystem();
    00304   SetupColorsAndInitialWindow();
    00305
    00306   /* Load the default opening screen savegame */
    00307   if (SaveOrLoad("opntitle.dat", SL_LOAD, DATA_DIR) != SL_OK) {
    00308     GenerateWorld(GW_EMPTY, 64, 64); // if failed loading, make empty world.
    00309     WaitTillGeneratedWorld();
    00310   }
    00311
    00312   _pause_game = 0;
    00313   SetLocalPlayer(PLAYER_FIRST);
    00314   /* Make sure you can't scroll in the menu */
    00315   _scrolling_viewport = 0;
    00316   _cursor.fix_at = false;
    00317   MarkWholeScreenDirty();
    00318
    00319   CheckForMissingGlyphsInLoadedLanguagePack();
    00320
    00321   /* Play main theme */
    00322   if (_music_driver->IsSongPlaying()) ResetMusic();
    00323 }
    00324
    00325 byte _no_scroll;
    00326 byte _savegame_sort_order;
    00327 #if defined(UNIX) && !defined(__MORPHOS__)
    00328 extern void DedicatedFork();
    00329 #endif
    00330
    00331 int ttd_main(int argc, char *argv[])
    00332 {
    00333   int i;
    00334   const char *optformat;
    00335   char musicdriver[32], sounddriver[32], videodriver[32], blitter[32];
    00336   int resolution[2] = {0, 0};
    00337   Year startyear = INVALID_YEAR;
    00338   uint generation_seed = GENERATE_NEW_SEED;
    00339   bool save_config = true;
    00340 #if defined(ENABLE_NETWORK)
    00341   bool dedicated = false;
    00342   bool network   = false;
    00343   char *network_conn = NULL;
    00344   char *debuglog_conn = NULL;
    00345   char *dedicated_host = NULL;
    00346   uint16 dedicated_port = 0;
    00347 #endif /* ENABLE_NETWORK */
    00348
    00349   musicdriver[0] = sounddriver[0] = videodriver[0] = blitter[0] = '\0';
    00350
    00351   _game_mode = GM_MENU;
    00352   _switch_mode = SM_MENU;
    00353   _switch_mode_errorstr = INVALID_STRING_ID;
    00354   _dedicated_forks = false;
    00355   _config_file = NULL;
    00356
    00357   /* The last param of the following function means this:
    00358    *   a letter means: it accepts that param (e.g.: -h)
    00359    *   a ':' behind it means: it need a param (e.g.: -m<driver>)
    00360    *   a '::' behind it means: it can optional have a param (e.g.: -d<debug>) */
    00361   optformat = "m:s:v:b:hD::n::eit:d::r:g::G:c:xl:"
    00362 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
    00363     "f"
    00364 #endif
    00365   ;
    00366
    00367   MyGetOptData mgo(argc - 1, argv + 1, optformat);
    00368
    00369   while ((i = MyGetOpt(&mgo)) != -1) {
    00370     switch (i) {
    00371     case 'm': ttd_strlcpy(musicdriver, mgo.opt, sizeof(musicdriver)); break;
    00372     case 's': ttd_strlcpy(sounddriver, mgo.opt, sizeof(sounddriver)); break;
    00373     case 'v': ttd_strlcpy(videodriver, mgo.opt, sizeof(videodriver)); break;
    00374     case 'b': ttd_strlcpy(blitter, mgo.opt, sizeof(blitter)); break;
    00375 #if defined(ENABLE_NETWORK)
    00376     case 'D':
    00377       strcpy(musicdriver, "null");
    00378       strcpy(sounddriver, "null");
    00379       strcpy(videodriver, "dedicated");
    00380       strcpy(blitter, "null");
    00381       dedicated = true;
    00382       if (mgo.opt != NULL) {
    00383         /* Use the existing method for parsing (openttd -n).
    00384          * However, we do ignore the #player part. */
    00385         const char *temp = NULL;
    00386         const char *port = NULL;
    00387         ParseConnectionString(&temp, &port, mgo.opt);
    00388         if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
    00389         if (port != NULL) dedicated_port = atoi(port);
    00390       }
    00391       break;
    00392     case 'f': _dedicated_forks = true; break;
    00393     case 'n':
    00394       network = true;
    00395       network_conn = mgo.opt; // optional IP parameter, NULL if unset
    00396       break;
    00397     case 'l':
    00398       debuglog_conn = mgo.opt;
    00399       break;
    00400 #endif /* ENABLE_NETWORK */
    00401     case 'r': ParseResolution(resolution, mgo.opt); break;
    00402     case 't': startyear = atoi(mgo.opt); break;
    00403     case 'd': {
    00404 #if defined(WIN32)
    00405         CreateConsole();
    00406 #endif
    00407         if (mgo.opt != NULL) SetDebugString(mgo.opt);
    00408       } break;
    00409     case 'e': _switch_mode = SM_EDITOR; break;
    00410     case 'i': _use_dos_palette = true; break;
    00411     case 'g':
    00412       if (mgo.opt != NULL) {
    00413         ttd_strlcpy(_file_to_saveload.name, mgo.opt, sizeof(_file_to_saveload.name));
    00414         _switch_mode = SM_LOAD;
    00415         _file_to_saveload.mode = SL_LOAD;
    00416
    00417         /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
    00418         const char *t = strrchr(_file_to_saveload.name, '.');
    00419         if (t != NULL) {
    00420           FiosType ft = (FiosType)FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL);
    00421           if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
    00422         }
    00423
    00424         break;
    00425       }
    00426
    00427       _switch_mode = SM_NEWGAME;
    00428       /* Give a random map */
    00429       generation_seed = InteractiveRandom();
    00430       break;
    00431     case 'G': generation_seed = atoi(mgo.opt); break;
    00432     case 'c': _config_file = strdup(mgo.opt); break;
    00433     case 'x': save_config = false; break;
    00434     case -2:
    00435     case 'h':
    00436       showhelp();
    00437       return 0;
    00438     }
    00439   }
    00440
    00441 #if defined(WINCE) && defined(_DEBUG)
    00442   /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
    00443   SetDebugString("4");
    00444 #endif
    00445
    00446   DeterminePaths(argv[0]);
    00447   CheckExternalFiles();
    00448
    00449 #if defined(UNIX) && !defined(__MORPHOS__)
    00450   /* We must fork here, or we'll end up without some resources we need (like sockets) */
    00451   if (_dedicated_forks)
    00452     DedicatedFork();
    00453 #endif
    00454
    00455   LoadFromConfig();
    00456   CheckConfig();
    00457   LoadFromHighScore();
    00458
    00459   /* override config? */
    00460   if (!StrEmpty(musicdriver)) ttd_strlcpy(_ini_musicdriver, musicdriver, sizeof(_ini_musicdriver));
    00461   if (!StrEmpty(sounddriver)) ttd_strlcpy(_ini_sounddriver, sounddriver, sizeof(_ini_sounddriver));
    00462   if (!StrEmpty(videodriver)) ttd_strlcpy(_ini_videodriver, videodriver, sizeof(_ini_videodriver));
    00463   if (!StrEmpty(blitter))     ttd_strlcpy(_ini_blitter, blitter, sizeof(_ini_blitter));
    00464   if (resolution[0] != 0) { _cur_resolution[0] = resolution[0]; _cur_resolution[1] = resolution[1]; }
    00465   if (startyear != INVALID_YEAR) _patches_newgame.starting_year = startyear;
    00466   if (generation_seed != GENERATE_NEW_SEED) _patches_newgame.generation_seed = generation_seed;
    00467
    00468   /* The width and height must be at least 1 pixel, this
    00469    * way all internal drawing routines work correctly. */
    00470   if (_cur_resolution[0] == 0) _cur_resolution[0] = 1;
    00471   if (_cur_resolution[1] == 0) _cur_resolution[1] = 1;
    00472
    00473 #if defined(ENABLE_NETWORK)
    00474   if (dedicated_host) snprintf(_network_server_bind_ip_host, NETWORK_HOSTNAME_LENGTH, "%s", dedicated_host);
    00475   if (dedicated_port) _network_server_port = dedicated_port;
    00476   if (_dedicated_forks && !dedicated) _dedicated_forks = false;
    00477 #endif /* ENABLE_NETWORK */
    00478
    00479   /* enumerate language files */
    00480   InitializeLanguagePacks();
    00481
    00482   /* initialize screenshot formats */
    00483   InitializeScreenshotFormats();
    00484
    00485   /* initialize airport state machines */
    00486   InitializeAirports();
    00487
    00488   /* initialize all variables that are allocated dynamically */
    00489   InitializeDynamicVariables();
    00490
    00491   /* start the AI */
    00492   AI_Initialize();
    00493
    00494   /* Sample catalogue */
    00495   DEBUG(misc, 1, "Loading sound effects...");
    00496   MxInitialize(11025);
    00497   SoundInitialize("sample.cat");
    00498
    00499   /* Initialize FreeType */
    00500   InitFreeType();
    00501
    00502   /* This must be done early, since functions use the InvalidateWindow* calls */
    00503   InitWindowSystem();
    00504
    00505   /* Initialize game palette */
    00506   GfxInitPalettes();
    00507
    00508   DEBUG(misc, 1, "Loading blitter...");
    00509   if (BlitterFactoryBase::SelectBlitter(_ini_blitter) == NULL)
    00510     StrEmpty(_ini_blitter) ?
    00511       error("Failed to autoprobe blitter") :
    00512       error("Failed to select requested blitter '%s'; does it exist?", _ini_blitter);
    00513
    00514   DEBUG(driver, 1, "Loading drivers...");
    00515
    00516   _sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(_ini_sounddriver, Driver::DT_SOUND);
    00517   if (_sound_driver == NULL) {
    00518     StrEmpty(_ini_sounddriver) ?
    00519       error("Failed to autoprobe sound driver") :
    00520       error("Failed to select requested sound driver '%s'", _ini_sounddriver);
    00521   }
    00522
    00523   _music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(_ini_musicdriver, Driver::DT_MUSIC);
    00524   if (_music_driver == NULL) {
    00525     StrEmpty(_ini_musicdriver) ?
    00526       error("Failed to autoprobe music driver") :
    00527       error("Failed to select requested music driver '%s'", _ini_musicdriver);
    00528   }
    00529
    00530   _video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(_ini_videodriver, Driver::DT_VIDEO);
    00531   if (_video_driver == NULL) {
    00532     StrEmpty(_ini_videodriver) ?
    00533       error("Failed to autoprobe video driver") :
    00534       error("Failed to select requested video driver '%s'", _ini_videodriver);
    00535   }
    00536
    00537   _savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
    00538   /* Initialize the zoom level of the screen to normal */
    00539   _screen.zoom = ZOOM_LVL_NORMAL;
    00540
    00541   /* restore saved music volume */
    00542   _music_driver->SetVolume(msf.music_vol);
    00543
    00544   NetworkStartUp(); // initialize network-core
    00545
    00546 #if defined(ENABLE_NETWORK)
    00547   if (debuglog_conn != NULL && _network_available) {
    00548     const char *not_used = NULL;
    00549     const char *port = NULL;
    00550     uint16 rport;
    00551
    00552     rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
    00553
    00554     ParseConnectionString(&not_used, &port, debuglog_conn);
    00555     if (port != NULL) rport = atoi(port);
    00556
    00557     NetworkStartDebugLog(debuglog_conn, rport);
    00558   }
    00559 #endif /* ENABLE_NETWORK */
    00560
    00561   ScanNewGRFFiles();
    00562
    00563   _opt_ptr = &_opt_newgame;
    00564   ResetGRFConfig(false);
    00565
    00566   /* XXX - ugly hack, if diff_level is 9, it means we got no setting from the config file */
    00567   if (_opt_newgame.diff_level == 9) SetDifficultyLevel(0, &_opt_newgame);
    00568
    00569   /* Make sure _patches is filled with _patches_newgame if we switch to a game directly */
    00570   if (_switch_mode != SM_NONE) {
    00571     _opt = _opt_newgame;
    00572     UpdatePatches();
    00573   }
    00574
    00575   /* initialize the ingame console */
    00576   IConsoleInit();
    00577   _cursor.in_window = true;
    00578   InitializeGUI();
    00579   IConsoleCmdExec("exec scripts/autoexec.scr 0");
    00580
    00581   GenerateWorld(GW_EMPTY, 64, 64); // Make the viewport initialization happy
    00582   WaitTillGeneratedWorld();
    00583
    00584 #ifdef ENABLE_NETWORK
    00585   if (network && _network_available) {
    00586     if (network_conn != NULL) {
    00587       const char *port = NULL;
    00588       const char *player = NULL;
    00589       uint16 rport;
    00590
    00591       rport = NETWORK_DEFAULT_PORT;
    00592       _network_playas = PLAYER_NEW_COMPANY;
    00593
    00594       ParseConnectionString(&player, &port, network_conn);
    00595
    00596       if (player != NULL) {
    00597         _network_playas = (PlayerID)atoi(player);
    00598
    00599         if (_network_playas != PLAYER_SPECTATOR) {
    00600           _network_playas--;
    00601           if (!IsValidPlayer(_network_playas)) return false;
    00602         }
    00603       }
    00604       if (port != NULL) rport = atoi(port);
    00605
    00606       LoadIntroGame();
    00607       _switch_mode = SM_NONE;
    00608       NetworkClientConnectGame(network_conn, rport);
    00609     }
    00610   }
    00611 #endif /* ENABLE_NETWORK */
    00612
    00613   _video_driver->MainLoop();
    00614
    00615   WaitTillSaved();
    00616   IConsoleFree();
    00617
    00618   if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
    00619
    00620   _video_driver->Stop();
    00621   _music_driver->Stop();
    00622   _sound_driver->Stop();
    00623
    00624   /* only save config if we have to */
    00625   if (save_config) {
    00626     SaveToConfig();
    00627     SaveToHighScore();
    00628   }
    00629
    00630   /* Reset windowing system and free config file */
    00631   UnInitializeGame();
    00632
    00633   /* stop the AI */
    00634   AI_Uninitialize();
    00635
    00636   /* Close all and any open filehandles */
    00637   FioCloseAll();
    00638
    00639   return 0;
    00640 }
    00641
    00642 void HandleExitGameRequest()
    00643 {
    00644   if (_game_mode == GM_MENU) { // do not ask to quit on the main screen
    00645     _exit_game = true;
    00646   } else if (_patches.autosave_on_exit) {
    00647     DoExitSave();
    00648     _exit_game = true;
    00649   } else {
    00650     AskExitGame();
    00651   }
    00652 }
    00653
    00654
    00657 static ThreadMsg _message = MSG_OTTD_NO_MESSAGE;
    00658
    00659 static inline void OTTD_ReleaseMutex() {_message = MSG_OTTD_NO_MESSAGE;}
    00660 static inline ThreadMsg OTTD_PollThreadEvent() {return _message;}
    00661
    00664 void OTTD_SendThreadMessage(ThreadMsg msg)
    00665 {
    00666   if (_exit_game) return;
    00667   while (_message != MSG_OTTD_NO_MESSAGE) CSleep(10);
    00668
    00669   _message = msg;
    00670 }
    00671
    00672
    00676 static void ProcessSentMessage(ThreadMsg message)
    00677 {
    00678   switch (message) {
    00679     case MSG_OTTD_SAVETHREAD_DONE:  SaveFileDone(); break;
    00680     case MSG_OTTD_SAVETHREAD_ERROR: SaveFileError(); break;
    00681     default: NOT_REACHED();
    00682   }
    00683
    00684   OTTD_ReleaseMutex(); // release mutex so that other threads, messages can be handled
    00685 }
    00686
    00687 static void ShowScreenshotResult(bool b)
    00688 {
    00689   if (b) {
    00690     SetDParamStr(0, _screenshot_name);
    00691     ShowErrorMessage(INVALID_STRING_ID, STR_031B_SCREENSHOT_SUCCESSFULLY, 0, 0);
    00692   } else {
    00693     ShowErrorMessage(INVALID_STRING_ID, STR_031C_SCREENSHOT_FAILED, 0, 0);
    00694   }
    00695
    00696 }
    00697
    00698 static void MakeNewGameDone()
    00699 {
    00700   SettingsDisableElrail(_patches.disable_elrails);
    00701
    00702   /* In a dedicated server, the server does not play */
    00703   if (_network_dedicated) {
    00704     SetLocalPlayer(PLAYER_SPECTATOR);
    00705     return;
    00706   }
    00707
    00708   /* Create a single player */
    00709   DoStartupNewPlayer(false);
    00710
    00711   SetLocalPlayer(PLAYER_FIRST);
    00712   _current_player = _local_player;
    00713   DoCommandP(0, (_patches.autorenew << 15 ) | (_patches.autorenew_months << 16) | 4, _patches.autorenew_money, NULL, CMD_SET_AUTOREPLACE);
    00714
    00715   SetDefaultRailGui();
    00716
    00717 #ifdef ENABLE_NETWORK
    00718   /* We are the server, we start a new player (not dedicated),
    00719    * so set the default password *if* needed. */
    00720   if (_network_server && !StrEmpty(_network_default_company_pass)) {
    00721     char *password = _network_default_company_pass;
    00722     NetworkChangeCompanyPassword(1, &password);
    00723   }
    00724 #endif /* ENABLE_NETWORK */
    00725
    00726   MarkWholeScreenDirty();
    00727 }
    00728
    00729 static void MakeNewGame(bool from_heightmap)
    00730 {
    00731   _game_mode = GM_NORMAL;
    00732
    00733   ResetGRFConfig(true);
    00734   _house_mngr.ResetMapping();
    00735   _industile_mngr.ResetMapping();
    00736   _industry_mngr.ResetMapping();
    00737
    00738   GenerateWorldSetCallback(&MakeNewGameDone);
    00739   GenerateWorld(from_heightmap ? GW_HEIGHTMAP : GW_NEWGAME, 1 << _patches.map_x, 1 << _patches.map_y);
    00740 }
    00741
    00742 static void MakeNewEditorWorldDone()
    00743 {
    00744   SetLocalPlayer(OWNER_NONE);
    00745
    00746   MarkWholeScreenDirty();
    00747 }
    00748
    00749 static void MakeNewEditorWorld()
    00750 {
    00751   _game_mode = GM_EDITOR;
    00752
    00753   ResetGRFConfig(true);
    00754
    00755   GenerateWorldSetCallback(&MakeNewEditorWorldDone);
    00756   GenerateWorld(GW_EMPTY, 1 << _patches.map_x, 1 << _patches.map_y);
    00757 }
    00758
    00759 void StartupPlayers();
    00760 void StartupDisasters();
    00761 extern void StartupEconomy();
    00762
    00768 static void StartScenario()
    00769 {
    00770   _game_mode = GM_NORMAL;
    00771
    00772   /* invalid type */
    00773   if (_file_to_saveload.mode == SL_INVALID) {
    00774     DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
    00775     SetDParamStr(0, GetSaveLoadErrorString());
    00776     ShowErrorMessage(INVALID_STRING_ID, STR_012D, 0, 0);
    00777     _game_mode = GM_MENU;
    00778     return;
    00779   }
    00780
    00781   /* Reinitialize windows */
    00782   ResetWindowSystem();
    00783
    00784   SetupColorsAndInitialWindow();
    00785
    00786   ResetGRFConfig(true);
    00787
    00788   /* Load game */
    00789   if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, SCENARIO_DIR) != SL_OK) {
    00790     LoadIntroGame();
    00791     SetDParamStr(0, GetSaveLoadErrorString());
    00792     ShowErrorMessage(INVALID_STRING_ID, STR_012D, 0, 0);
    00793   }
    00794
    00795   _opt_ptr = &_opt;
    00796   _opt_ptr->diff = _opt_newgame.diff;
    00797   _opt.diff_level = _opt_newgame.diff_level;
    00798
    00799   /* Inititalize data */
    00800   StartupEconomy();
    00801   StartupPlayers();
    00802   StartupEngines();
    00803   StartupDisasters();
    00804
    00805   SetLocalPlayer(PLAYER_FIRST);
    00806   _current_player = _local_player;
    00807   DoCommandP(0, (_patches.autorenew << 15 ) | (_patches.autorenew_months << 16) | 4, _patches.autorenew_money, NULL, CMD_SET_AUTOREPLACE);
    00808
    00809   MarkWholeScreenDirty();
    00810 }
    00811
    00819 bool SafeSaveOrLoad(const char *filename, int mode, int newgm, Subdirectory subdir)
    00820 {
    00821   byte ogm = _game_mode;
    00822
    00823   _game_mode = newgm;
    00824   assert(mode == SL_LOAD || mode == SL_OLD_LOAD);
    00825   switch (SaveOrLoad(filename, mode, subdir)) {
    00826     case SL_OK: return true;
    00827
    00828     case SL_REINIT:
    00829       switch (ogm) {
    00830         default:
    00831         case GM_MENU:   LoadIntroGame();      break;
    00832         case GM_EDITOR: MakeNewEditorWorld(); break;
    00833       }
    00834       return false;
    00835
    00836     default:
    00837       _game_mode = ogm;
    00838       return false;
    00839   }
    00840 }
    00841
    00842 void SwitchMode(int new_mode)
    00843 {
    00844 #ifdef ENABLE_NETWORK
    00845   /* If we are saving something, the network stays in his current state */
    00846   if (new_mode != SM_SAVE) {
    00847     /* If the network is active, make it not-active */
    00848     if (_networking) {
    00849       if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
    00850         NetworkReboot();
    00851         NetworkUDPCloseAll();
    00852       } else {
    00853         NetworkDisconnect();
    00854         NetworkUDPCloseAll();
    00855       }
    00856     }
    00857
    00858     /* If we are a server, we restart the server */
    00859     if (_is_network_server) {
    00860       /* But not if we are going to the menu */
    00861       if (new_mode != SM_MENU) {
    00862         /* check if we should reload the config */
    00863         if (_network_reload_cfg) {
    00864           LoadFromConfig();
    00865           _patches = _patches_newgame;
    00866           _opt = _opt_newgame;
    00867           ResetGRFConfig(false);
    00868         }
    00869         NetworkServerStart();
    00870       } else {
    00871         /* This client no longer wants to be a network-server */
    00872         _is_network_server = false;
    00873       }
    00874     }
    00875   }
    00876 #endif /* ENABLE_NETWORK */
    00877
    00878   switch (new_mode) {
    00879   case SM_EDITOR: /* Switch to scenario editor */
    00880     MakeNewEditorWorld();
    00881     break;
    00882
    00883   case SM_NEWGAME: /* New Game --> 'Random game' */
    00884 #ifdef ENABLE_NETWORK
    00885     if (_network_server) {
    00886       snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
    00887     }
    00888 #endif /* ENABLE_NETWORK */
    00889     MakeNewGame(false);
    00890     break;
    00891
    00892   case SM_START_SCENARIO: /* New Game --> Choose one of the preset scenarios */
    00893 #ifdef ENABLE_NETWORK
    00894     if (_network_server) {
    00895       snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded scenario)", _file_to_saveload.title);
    00896     }
    00897 #endif /* ENABLE_NETWORK */
    00898     StartScenario();
    00899     break;
    00900
    00901   case SM_LOAD: { /* Load game, Play Scenario */
    00902     _opt_ptr = &_opt;
    00903     ResetGRFConfig(true);
    00904     ResetWindowSystem();
    00905
    00906     if (!SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
    00907       LoadIntroGame();
    00908       SetDParamStr(0, GetSaveLoadErrorString());
    00909       ShowErrorMessage(INVALID_STRING_ID, STR_012D, 0, 0);
    00910     } else {
    00911       if (_saveload_mode == SLD_LOAD_SCENARIO) {
    00912         StartupEngines();
    00913       }
    00914       /* Update the local player for a loaded game. It is either always
    00915        * player #1 (eg 0) or in the case of a dedicated server a spectator */
    00916       SetLocalPlayer(_network_dedicated ? PLAYER_SPECTATOR : PLAYER_FIRST);
    00917       /* Decrease pause counter (was increased from opening load dialog) */
    00918       DoCommandP(0, 0, 0, NULL, CMD_PAUSE);
    00919 #ifdef ENABLE_NETWORK
    00920       if (_network_server) {
    00921         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
    00922       }
    00923 #endif /* ENABLE_NETWORK */
    00924     }
    00925     break;
    00926   }
    00927
    00928   case SM_START_HEIGHTMAP: /* Load a heightmap and start a new game from it */
    00929 #ifdef ENABLE_NETWORK
    00930     if (_network_server) {
    00931       snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
    00932     }
    00933 #endif /* ENABLE_NETWORK */
    00934     MakeNewGame(true);
    00935     break;
    00936
    00937   case SM_LOAD_HEIGHTMAP: /* Load heightmap from scenario editor */
    00938     SetLocalPlayer(OWNER_NONE);
    00939
    00940     GenerateWorld(GW_HEIGHTMAP, 1 << _patches.map_x, 1 << _patches.map_y);
    00941     MarkWholeScreenDirty();
    00942     break;
    00943
    00944   case SM_LOAD_SCENARIO: { /* Load scenario from scenario editor */
    00945     if (SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
    00946       _opt_ptr = &_opt;
    00947
    00948       SetLocalPlayer(OWNER_NONE);
    00949       _patches_newgame.starting_year = _cur_year;
    00950     } else {
    00951       SetDParamStr(0, GetSaveLoadErrorString());
    00952       ShowErrorMessage(INVALID_STRING_ID, STR_012D, 0, 0);
    00953     }
    00954     break;
    00955   }
    00956
    00957   case SM_MENU: /* Switch to game intro menu */
    00958     LoadIntroGame();
    00959     break;
    00960
    00961   case SM_SAVE: /* Save game */
    00962     /* Make network saved games on pause compatible to singleplayer */
    00963     if (_networking && _pause_game == 1) _pause_game = 2;
    00964     if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
    00965       SetDParamStr(0, GetSaveLoadErrorString());
    00966       ShowErrorMessage(INVALID_STRING_ID, STR_012D, 0, 0);
    00967     } else {
    00968       DeleteWindowById(WC_SAVELOAD, 0);
    00969     }
    00970     if (_networking && _pause_game == 2) _pause_game = 1;
    00971     break;
    00972
    00973   case SM_GENRANDLAND: /* Generate random land within scenario editor */
    00974     SetLocalPlayer(OWNER_NONE);
    00975     GenerateWorld(GW_RANDOM, 1 << _patches.map_x, 1 << _patches.map_y);
    00976     /* XXX: set date */
    00977     MarkWholeScreenDirty();
    00978     break;
    00979   }
    00980
    00981   if (_switch_mode_errorstr != INVALID_STRING_ID) {
    00982     ShowErrorMessage(INVALID_STRING_ID, _switch_mode_errorstr, 0, 0);
    00983   }
    00984 }
    00985
    00986
    00987 /* State controlling game loop.
    00988  * The state must not be changed from anywhere
    00989  * but here.
    00990  * That check is enforced in DoCommand. */
    00991 void StateGameLoop()
    00992 {
    00993   /* dont execute the state loop during pause */
    00994   if (_pause_game) {
    00995     CallWindowTickEvent();
    00996     return;
    00997   }
    00998   if (IsGeneratingWorld()) return;
    00999
    01000   ClearStorageChanges(false);
    01001
    01002   if (_game_mode == GM_EDITOR) {
    01003     RunTileLoop();
    01004     CallVehicleTicks();
    01005     CallLandscapeTick();
    01006     ClearStorageChanges(true);
    01007
    01008     CallWindowTickEvent();
    01009     NewsLoop();
    01010   } else {
    01011     /* All these actions has to be done from OWNER_NONE
    01012      *  for multiplayer compatibility */
    01013     PlayerID p = _current_player;
    01014     _current_player = OWNER_NONE;
    01015
    01016     AnimateAnimatedTiles();
    01017     IncreaseDate();
    01018     RunTileLoop();
    01019     CallVehicleTicks();
    01020     CallLandscapeTick();
    01021     ClearStorageChanges(true);
    01022
    01023     AI_RunGameLoop();
    01024
    01025     CallWindowTickEvent();
    01026     NewsLoop();
    01027     _current_player = p;
    01028   }
    01029 }
    01030
    01033 static void DoAutosave()
    01034 {
    01035   char buf[MAX_PATH];
    01036
    01037 #if defined(PSP)
    01038   /* Autosaving in networking is too time expensive for the PSP */
    01039   if (_networking)
    01040     return;
    01041 #endif /* PSP */
    01042
    01043   if (_patches.keep_all_autosave && _local_player != PLAYER_SPECTATOR) {
    01044     SetDParam(0, _local_player);
    01045     SetDParam(1, _date);
    01046     GetString(buf, STR_4004, lastof(buf));
    01047     ttd_strlcat(buf, ".sav", lengthof(buf));
    01048   } else {
    01049     /* generate a savegame name and number according to _patches.max_num_autosaves */
    01050     snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
    01051
    01052     if (++_autosave_ctr >= _patches.max_num_autosaves) _autosave_ctr = 0;
    01053   }
    01054
    01055   DEBUG(sl, 2, "Autosaving to '%s'", buf);
    01056   if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK)
    01057     ShowErrorMessage(INVALID_STRING_ID, STR_AUTOSAVE_FAILED, 0, 0);
    01058 }
    01059
    01060 static void ScrollMainViewport(int x, int y)
    01061 {
    01062   if (_game_mode != GM_MENU) {
    01063     Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
    01064     assert(w);
    01065
    01066     WP(w, vp_d).dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
    01067     WP(w, vp_d).dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
    01068   }
    01069 }
    01079 static const int8 scrollamt[16][2] = {
    01080   { 0,  0},
    01081   {-2,  0},
    01082   { 0, -2},
    01083   {-2, -1},
    01084   { 2,  0},
    01085   { 0,  0},
    01086   { 2, -1},
    01087   { 0, -2},
    01088   { 0  ,2},
    01089   {-2  ,1},
    01090   { 0,  0},
    01091   {-2,  0},
    01092   { 2,  1},
    01093   { 0,  2},
    01094   { 2,  0},
    01095   { 0,  0},
    01096 };
    01097
    01098 static void HandleKeyScrolling()
    01099 {
    01100   if (_dirkeys && !_no_scroll) {
    01101     int factor = _shift_pressed ? 50 : 10;
    01102     ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
    01103   }
    01104 }
    01105
    01106 void GameLoop()
    01107 {
    01108   ThreadMsg message;
    01109
    01110   if ((message = OTTD_PollThreadEvent()) != 0) ProcessSentMessage(message);
    01111
    01112   /* autosave game? */
    01113   if (_do_autosave) {
    01114     _do_autosave = false;
    01115     DoAutosave();
    01116     RedrawAutosave();
    01117   }
    01118
    01119   /* handle scrolling of the main window */
    01120   HandleKeyScrolling();
    01121
    01122   /* make a screenshot? */
    01123   if (IsScreenshotRequested()) ShowScreenshotResult(MakeScreenshot());
    01124
    01125   /* switch game mode? */
    01126   if (_switch_mode != SM_NONE) {
    01127     SwitchMode(_switch_mode);
    01128     _switch_mode = SM_NONE;
    01129   }
    01130
    01131   IncreaseSpriteLRU();
    01132   InteractiveRandom();
    01133
    01134   if (_scroller_click_timeout > 3) {
    01135     _scroller_click_timeout -= 3;
    01136   } else {
    01137     _scroller_click_timeout = 0;
    01138   }
    01139
    01140   _caret_timer += 3;
    01141   _palette_animation_counter += 8;
    01142   CursorTick();
    01143
    01144 #ifdef ENABLE_NETWORK
    01145   /* Check for UDP stuff */
    01146   if (_network_available) NetworkUDPGameLoop();
    01147
    01148   if (_networking && !IsGeneratingWorld()) {
    01149     /* Multiplayer */
    01150     NetworkGameLoop();
    01151   } else {
    01152     if (_network_reconnect > 0 && --_network_reconnect == 0) {
    01153       /* This means that we want to reconnect to the last host
    01154        * We do this here, because it means that the network is really closed */
    01155       NetworkClientConnectGame(_network_last_host, _network_last_port);
    01156     }
    01157     /* Singleplayer */
    01158     StateGameLoop();
    01159   }
    01160 #else
    01161   StateGameLoop();
    01162 #endif /* ENABLE_NETWORK */
    01163
    01164   if (!_pause_game && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
    01165
    01166   if (!_pause_game || _cheats.build_in_pause.value) MoveAllTextEffects();
    01167
    01168   InputLoop();
    01169
    01170   MusicLoop();
    01171 }
    01172
    01173 void BeforeSaveGame()
    01174 {
    01175   const Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
    01176
    01177   if (w != NULL) {
    01178     _saved_scrollpos_x = WP(w, const vp_d).scrollpos_x;
    01179     _saved_scrollpos_y = WP(w, const vp_d).scrollpos_y;
    01180     _saved_scrollpos_zoom = w->viewport->zoom;
    01181   }
    01182 }
    01183
    01184 static void ConvertTownOwner()
    01185 {
    01186   TileIndex tile;
    01187
    01188   for (tile = 0; tile != MapSize(); tile++) {
    01189     switch (GetTileType(tile)) {
    01190       case MP_ROAD:
    01191         if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
    01192           _m[tile].m3 = OWNER_TOWN;
    01193         }
    01194         /* FALLTHROUGH */
    01195
    01196       case MP_TUNNELBRIDGE:
    01197         if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN);
    01198         break;
    01199
    01200       default: break;
    01201     }
    01202   }
    01203 }
    01204
    01205 /* before savegame version 4, the name of the company determined if it existed */
    01206 static void CheckIsPlayerActive()
    01207 {
    01208   Player *p;
    01209
    01210   FOR_ALL_PLAYERS(p) {
    01211     if (p->name_1 != 0) p->is_active = true;
    01212   }
    01213 }
    01214
    01215 /* since savegame version 4.1, exclusive transport rights are stored at towns */
    01216 static void UpdateExclusiveRights()
    01217 {
    01218   Town *t;
    01219
    01220   FOR_ALL_TOWNS(t) {
    01221     t->exclusivity = INVALID_PLAYER;
    01222   }
    01223
    01224   /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
    01225    *   could be implemented this way:
    01226    * 1.) Go through all stations
    01227    *     Build an array town_blocked[ town_id ][ player_id ]
    01228    *     that stores if at least one station in that town is blocked for a player
    01229    * 2.) Go through that array, if you find a town that is not blocked for
    01230    *     one player, but for all others, then give him exclusivity.
    01231    */
    01232 }
    01233
    01234 static const byte convert_currency[] = {
    01235    0,  1, 12,  8,  3,
    01236   10, 14, 19,  4,  5,
    01237    9, 11, 13,  6, 17,
    01238   16, 22, 21,  7, 15,
    01239   18,  2, 20, };
    01240
    01241 /* since savegame version 4.2 the currencies are arranged differently */
    01242 static void UpdateCurrencies()
    01243 {
    01244   _opt.currency = convert_currency[_opt.currency];
    01245 }
    01246
    01247 /* Up to revision 1413 the invisible tiles at the southern border have not been
    01248  * MP_VOID, even though they should have. This is fixed by this function
    01249  */
    01250 static void UpdateVoidTiles()
    01251 {
    01252   uint i;
    01253
    01254   for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
    01255   for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
    01256 }
    01257
    01258 /* since savegame version 6.0 each sign has an "owner", signs without owner (from old games are set to 255) */
    01259 static void UpdateSignOwner()
    01260 {
    01261   Sign *si;
    01262
    01263   FOR_ALL_SIGNS(si) si->owner = OWNER_NONE;
    01264 }
    01265
    01266 extern void UpdateOldAircraft();
    01267
    01268
    01269 static inline RailType UpdateRailType(RailType rt, RailType min)
    01270 {
    01271   return rt >= min ? (RailType)(rt + 1): rt;
    01272 }
    01273
    01285 static bool InitializeWindowsAndCaches()
    01286 {
    01287   /* Initialize windows */
    01288   ResetWindowSystem();
    01289   SetupColorsAndInitialWindow();
    01290
    01291   Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
    01292
    01293   WP(w, vp_d).scrollpos_x = _saved_scrollpos_x;
    01294   WP(w, vp_d).scrollpos_y = _saved_scrollpos_y;
    01295   WP(w, vp_d).dest_scrollpos_x = _saved_scrollpos_x;
    01296   WP(w, vp_d).dest_scrollpos_y = _saved_scrollpos_y;
    01297
    01298   ViewPort *vp = w->viewport;
    01299   vp->zoom = min(_saved_scrollpos_zoom, ZOOM_LVL_MAX);
    01300   vp->virtual_width = ScaleByZoom(vp->width, vp->zoom);
    01301   vp->virtual_height = ScaleByZoom(vp->height, vp->zoom);
    01302
    01303   DoZoomInOutWindow(ZOOM_NONE, w); // update button status
    01304   MarkWholeScreenDirty();
    01305
    01306   /* Update coordinates of the signs. */
    01307   UpdateAllStationVirtCoord();
    01308   UpdateAllSignVirtCoords();
    01309   UpdateAllTownVirtCoords();
    01310   UpdateAllWaypointSigns();
    01311
    01312   /* Recalculate */
    01313   Group *g;
    01314   FOR_ALL_GROUPS(g) {
    01315     const Vehicle *v;
    01316     FOR_ALL_VEHICLES(v) {
    01317       if (!IsEngineCountable(v)) continue;
    01318
    01319       if (v->group_id != g->index || v->type != g->vehicle_type || v->owner != g->owner) continue;
    01320
    01321       g->num_engines[v->engine_type]++;
    01322     }
    01323   }
    01324
    01325   /* Set up the engine count for all players */
    01326   Player *players[MAX_PLAYERS];
    01327   const Vehicle *v;
    01328
    01329   for (PlayerID i = PLAYER_FIRST; i < MAX_PLAYERS; i++) {
    01330     players[i] = GetPlayer(i);
    01331
    01332     /* For each player, verify (while loading a scenario) that the inauguration date is the current year and set it
    01333      * accordingly if it is not the case.  No need to set it on players that are not been used already,
    01334      * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
    01335     if (_file_to_saveload.filetype == FT_SCENARIO && players[i]->inaugurated_year != MIN_YEAR)
    01336       players[i]->inaugurated_year = _cur_year;
    01337   }
    01338
    01339   FOR_ALL_VEHICLES(v) {
    01340     if (!IsEngineCountable(v)) continue;
    01341     players[v->owner]->num_engines[v->engine_type]++;
    01342   }
    01343
    01344   CheckTrainsLengths();
    01345
    01346   return true;
    01347 }
    01348
    01349 bool AfterLoadGame()
    01350 {
    01351   TileIndex map_size = MapSize();
    01352   Player *p;
    01353
    01354   /* in version 2.1 of the savegame, town owner was unified. */
    01355   if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
    01356
    01357   /* from version 4.1 of the savegame, exclusive rights are stored at towns */
    01358   if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
    01359
    01360   /* from version 4.2 of the savegame, currencies are in a different order */
    01361   if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
    01362
    01363   /* from version 6.1 of the savegame, signs have an "owner" */
    01364   if (CheckSavegameVersionOldStyle(6, 1)) UpdateSignOwner();
    01365
    01366   /* In old version there seems to be a problem that water is owned by
    01367    * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
    01368    * (4.3) version, so I just check when versions are older, and then
    01369    * walk through the whole map.. */
    01370   if (CheckSavegameVersionOldStyle(4, 3)) {
    01371     for (TileIndex t = 0; t < map_size; t++) {
    01372       if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_PLAYERS) {
    01373         SetTileOwner(t, OWNER_WATER);
    01374       }
    01375     }
    01376   }
    01377
    01378   if (CheckSavegameVersion(84)) {
    01379     Player *p;
    01380     FOR_ALL_PLAYERS(p) {
    01381       p->name = CopyFromOldName(p->name_1);
    01382       if (p->name != NULL) p->name_1 = STR_SV_UNNAMED;
    01383       p->president_name = CopyFromOldName(p->president_name_1);
    01384       if (p->president_name != NULL) p->president_name_1 = SPECSTR_PRESIDENT_NAME;
    01385     }
    01386
    01387     Station *st;
    01388     FOR_ALL_STATIONS(st) {
    01389       st->name = CopyFromOldName(st->string_id);
    01390       if (st->name != NULL) st->string_id = STR_EMPTY;
    01391     }
    01392
    01393     Town *t;
    01394     FOR_ALL_TOWNS(t) {
    01395       t->name = CopyFromOldName(t->townnametype);
    01396       if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _opt.town_name;
    01397     }
    01398
    01399     Waypoint *wp;
    01400     FOR_ALL_WAYPOINTS(wp) {
    01401       wp->name = CopyFromOldName(wp->string);
    01402       wp->string = STR_EMPTY;
    01403     }
    01404
    01405     for (uint i = 0; i < GetSignPoolSize(); i++) {
    01406       /* invalid signs are determined by si->ower == INVALID_PLAYER now */
    01407       Sign *si = GetSign(i);
    01408       if (!si->IsValid() && si->name != NULL) {
    01409         si->owner = OWNER_NONE;
    01410       }
    01411     }
    01412   }
    01413
    01414   /* convert road side to my format. */
    01415   if (_opt.road_side) _opt.road_side = 1;
    01416
    01417   /* Check if all NewGRFs are present, we are very strict in MP mode */
    01418   GRFListCompatibility gcf_res = IsGoodGRFConfigList();
    01419   if (_networking && gcf_res != GLC_ALL_GOOD) {
    01420     SetSaveLoadError(STR_NETWORK_ERR_CLIENT_NEWGRF_MISMATCH);
    01421     return false;
    01422   }
    01423
    01424   switch (gcf_res) {
    01425     case GLC_COMPATIBLE: _switch_mode_errorstr = STR_NEWGRF_COMPATIBLE_LOAD_WARNING; break;
    01426     case GLC_NOT_FOUND: _switch_mode_errorstr = STR_NEWGRF_DISABLED_WARNING; _pause_game = -1; break;
    01427     default: break;
    01428   }
    01429
    01430   /* Update current year
    01431    * must be done before loading sprites as some newgrfs check it */
    01432   SetDate(_date);
    01433
    01434   /* Load the sprites */
    01435   GfxLoadSprites();
    01436   LoadStringWidthTable();
    01437
    01438   /* Connect front and rear engines of multiheaded trains and converts
    01439    * subtype to the new format */
    01440   if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
    01441
    01442   /* Connect front and rear engines of multiheaded trains */
    01443   ConnectMultiheadedTrains();
    01444
    01445   /* reinit the landscape variables (landscape might have changed) */
    01446   InitializeLandscapeVariables(true);
    01447
    01448   /* Update all vehicles */
    01449   AfterLoadVehicles(true);
    01450
    01451   /* Update all waypoints */
    01452   if (CheckSavegameVersion(12)) FixOldWaypoints();
    01453
    01454   /* in version 2.2 of the savegame, we have new airports */
    01455   if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
    01456
    01457   AfterLoadTown();
    01458
    01459   /* make sure there is a town in the game */
    01460   if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, (uint)-1)) {
    01461     SetSaveLoadError(STR_NO_TOWN_IN_SCENARIO);
    01462     return false;
    01463   }
    01464
    01465   /* in version 4.1 of the savegame, is_active was introduced to determine
    01466    * if a player does exist, rather then checking name_1 */
    01467   if (CheckSavegameVersionOldStyle(4, 1)) CheckIsPlayerActive();
    01468
    01469   /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
    01470    * This problem appears in savegame version 21 too, see r3455. But after loading the
    01471    * savegame and saving again, the buggy map array could be converted to new savegame
    01472    * version. It didn't show up before r12070. */
    01473   if (CheckSavegameVersion(87)) UpdateVoidTiles();
    01474
    01475   /* If Load Scenario / New (Scenario) Game is used,
    01476    *  a player does not exist yet. So create one here.
    01477    * 1 exeption: network-games. Those can have 0 players
    01478    *   But this exeption is not true for non dedicated network_servers! */
    01479   if (!_players[0].is_active && (!_networking || (_networking && _network_server && !_network_dedicated)))
    01480     DoStartupNewPlayer(false);
    01481
    01482   if (CheckSavegameVersion(72)) {
    01483     /* Locks/shiplifts in very old savegames had OWNER_WATER as owner */
    01484     for (TileIndex t = 0; t < MapSize(); t++) {
    01485       switch (GetTileType(t)) {
    01486         default: break;
    01487
    01488         case MP_WATER:
    01489           if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
    01490           break;
    01491
    01492         case MP_STATION: {
    01493           if (HasBit(_m[t].m6, 3)) SetBit(_m[t].m6, 2);
    01494           StationGfx gfx = GetStationGfx(t);
    01495           StationType st;
    01496           if (       IsInsideMM(gfx,   0,   8)) { // Railway station
    01497             st = STATION_RAIL;
    01498             SetStationGfx(t, gfx - 0);
    01499           } else if (IsInsideMM(gfx,   8,  67)) { // Airport
    01500             st = STATION_AIRPORT;
    01501             SetStationGfx(t, gfx - 8);
    01502           } else if (IsInsideMM(gfx,  67,  71)) { // Truck
    01503             st = STATION_TRUCK;
    01504             SetStationGfx(t, gfx - 67);
    01505           } else if (IsInsideMM(gfx,  71,  75)) { // Bus
    01506             st = STATION_BUS;
    01507             SetStationGfx(t, gfx - 71);
    01508           } else if (gfx == 75) {                    // Oil rig
    01509             st = STATION_OILRIG;
    01510             SetStationGfx(t, gfx - 75);
    01511           } else if (IsInsideMM(gfx,  76,  82)) { // Dock
    01512             st = STATION_DOCK;
    01513             SetStationGfx(t, gfx - 76);
    01514           } else if (gfx == 82) {                    // Buoy
    01515             st = STATION_BUOY;
    01516             SetStationGfx(t, gfx - 82);
    01517           } else if (IsInsideMM(gfx,  83, 168)) { // Extended airport
    01518             st = STATION_AIRPORT;
    01519             SetStationGfx(t, gfx - 83 + 67 - 8);
    01520           } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
    01521             st = STATION_TRUCK;
    01522             SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
    01523           } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
    01524             st = STATION_BUS;
    01525             SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
    01526           } else {
    01527             return false;
    01528           }
    01529           SB(_m[t].m6, 3, 3, st);
    01530         } break;
    01531       }
    01532     }
    01533   }
    01534
    01535   for (TileIndex t = 0; t < map_size; t++) {
    01536     switch (GetTileType(t)) {
    01537       case MP_STATION: {
    01538         Station *st = GetStationByTile(t);
    01539
    01540         st->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
    01541
    01542         switch (GetStationType(t)) {
    01543           case STATION_TRUCK:
    01544           case STATION_BUS:
    01545             if (CheckSavegameVersion(6)) {
    01546               /* From this version on there can be multiple road stops of the
    01547                * same type per station. Convert the existing stops to the new
    01548                * internal data structure. */
    01549               RoadStop *rs = new RoadStop(t);
    01550               if (rs == NULL) error("Too many road stops in savegame");
    01551
    01552               RoadStop **head =
    01553                 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
    01554               *head = rs;
    01555             }
    01556             break;
    01557
    01558           case STATION_OILRIG: {
    01559             /* Very old savegames sometimes have phantom oil rigs, i.e.
    01560              * an oil rig which got shut down, but not completly removed from
    01561              * the map
    01562              */
    01563             TileIndex t1 = TILE_ADDXY(t, 0, 1);
    01564             if (IsTileType(t1, MP_INDUSTRY) &&
    01565                 GetIndustryGfx(t1) == GFX_OILRIG_1) {
    01566               /* The internal encoding of oil rigs was changed twice.
    01567                * It was 3 (till 2.2) and later 5 (till 5.1).
    01568                * Setting it unconditionally does not hurt.
    01569                */
    01570               GetStationByTile(t)->airport_type = AT_OILRIG;
    01571             } else {
    01572               DeleteOilRig(t);
    01573             }
    01574             break;
    01575           }
    01576
    01577           default: break;
    01578         }
    01579         break;
    01580       }
    01581
    01582       default: break;
    01583     }
    01584   }
    01585
    01586   /* In version 6.1 we put the town index in the map-array. To do this, we need
    01587    *  to use m2 (16bit big), so we need to clean m2, and that is where this is
    01588    *  all about ;) */
    01589   if (CheckSavegameVersionOldStyle(6, 1)) {
    01590     for (TileIndex t = 0; t < map_size; t++) {
    01591       switch (GetTileType(t)) {
    01592         case MP_HOUSE:
    01593           _m[t].m4 = _m[t].m2;
    01594           SetTownIndex(t, CalcClosestTownFromTile(t, (uint)-1)->index);
    01595           break;
    01596
    01597         case MP_ROAD:
    01598           _m[t].m4 |= (_m[t].m2 << 4);
    01599           if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
    01600             SetTownIndex(t, CalcClosestTownFromTile(t, (uint)-1)->index);
    01601           } else {
    01602             SetTownIndex(t, 0);
    01603           }
    01604           break;
    01605
    01606         default: break;
    01607       }
    01608     }
    01609   }
    01610
    01611   /* From version 9.0, we update the max passengers of a town (was sometimes negative
    01612    *  before that. */
    01613   if (CheckSavegameVersion(9)) {
    01614     Town *t;
    01615     FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
    01616   }
    01617
    01618   /* From version 16.0, we included autorenew on engines, which are now saved, but
    01619    *  of course, we do need to initialize them for older savegames. */
    01620   if (CheckSavegameVersion(16)) {
    01621     FOR_ALL_PLAYERS(p) {
    01622       p->engine_renew_list   = NULL;
    01623       p->engine_renew        = false;
    01624       p->engine_renew_months = -6;
    01625       p->engine_renew_money  = 100000;
    01626     }
    01627
    01628     /* When loading a game, _local_player is not yet set to the correct value.
    01629      * However, in a dedicated server we are a spectator, so nothing needs to
    01630      * happen. In case we are not a dedicated server, the local player always
    01631      * becomes player 0, unless we are in the scenario editor where all the
    01632      * players are 'invalid'.
    01633      */
    01634     if (!_network_dedicated && IsValidPlayer(PLAYER_FIRST)) {
    01635       p = GetPlayer(PLAYER_FIRST);
    01636       p->engine_renew        = _patches.autorenew;
    01637       p->engine_renew_months = _patches.autorenew_months;
    01638       p->engine_renew_money  = _patches.autorenew_money;
    01639     }
    01640   }
    01641
    01642   if (CheckSavegameVersion(48)) {
    01643     for (TileIndex t = 0; t < map_size; t++) {
    01644       switch (GetTileType(t)) {
    01645         case MP_RAILWAY:
    01646           if (IsPlainRailTile(t)) {
    01647             /* Swap ground type and signal type for plain rail tiles, so the
    01648              * ground type uses the same bits as for depots and waypoints. */
    01649             uint tmp = GB(_m[t].m4, 0, 4);
    01650             SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
    01651             SB(_m[t].m2, 0, 4, tmp);
    01652           } else if (HasBit(_m[t].m5, 2)) {
    01653             /* Split waypoint and depot rail type and remove the subtype. */
    01654             ClrBit(_m[t].m5, 2);
    01655             ClrBit(_m[t].m5, 6);
    01656           }
    01657           break;
    01658
    01659         case MP_ROAD:
    01660           /* Swap m3 and m4, so the track type for rail crossings is the
    01661            * same as for normal rail. */
    01662           Swap(_m[t].m3, _m[t].m4);
    01663           break;
    01664
    01665         default: break;
    01666       }
    01667     }
    01668   }
    01669
    01670   if (CheckSavegameVersion(61)) {
    01671     /* Added the RoadType */
    01672     bool old_bridge = CheckSavegameVersion(42);
    01673     for (TileIndex t = 0; t < map_size; t++) {
    01674       switch(GetTileType(t)) {
    01675         case MP_ROAD:
    01676           SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
    01677           switch (GetRoadTileType(t)) {
    01678             default: NOT_REACHED();
    01679             case ROAD_TILE_NORMAL:
    01680               SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
    01681               SB(_m[t].m4, 4, 4, 0);
    01682               SB(_m[t].m6, 2, 4, 0);
    01683               break;
    01684             case ROAD_TILE_CROSSING:
    01685               SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
    01686               break;
    01687             case ROAD_TILE_DEPOT:    break;
    01688           }
    01689           SetRoadTypes(t, ROADTYPES_ROAD);
    01690           break;
    01691
    01692         case MP_STATION:
    01693           if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
    01694           break;
    01695
    01696         case MP_TUNNELBRIDGE:
    01697           /* Middle part of "old" bridges */
    01698           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
    01699           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
    01700             SetRoadTypes(t, ROADTYPES_ROAD);
    01701           }
    01702           break;
    01703
    01704         default: break;
    01705       }
    01706     }
    01707   }
    01708
    01709   if (CheckSavegameVersion(42)) {
    01710     Vehicle* v;
    01711
    01712     for (TileIndex t = 0; t < map_size; t++) {
    01713       if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
    01714       if (IsBridgeTile(t)) {
    01715         if (HasBit(_m[t].m5, 6)) { // middle part
    01716           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
    01717
    01718           if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
    01719             if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
    01720               MakeRailNormal(
    01721                 t,
    01722                 GetTileOwner(t),
    01723                 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
    01724                 GetRailType(t)
    01725               );
    01726             } else {
    01727               TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, (uint)-1)->index : 0;
    01728
    01729               MakeRoadNormal(
    01730                 t,
    01731                 axis == AXIS_X ? ROAD_Y : ROAD_X,
    01732                 ROADTYPES_ROAD,
    01733                 town,
    01734                 GetTileOwner(t), OWNER_NONE, OWNER_NONE
    01735               );
    01736             }
    01737           } else {
    01738             if (GB(_m[t].m5, 3, 2) == 0) {
    01739               MakeClear(t, CLEAR_GRASS, 3);
    01740             } else {
    01741               if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
    01742                 MakeShore(t);
    01743               } else {
    01744                 if (GetTileOwner(t) == OWNER_WATER) {
    01745                   MakeWater(t);
    01746                 } else {
    01747                   MakeCanal(t, GetTileOwner(t), Random());
    01748                 }
    01749               }
    01750             }
    01751           }
    01752           SetBridgeMiddle(t, axis);
    01753         } else { // ramp
    01754           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
    01755           uint north_south = GB(_m[t].m5, 5, 1);
    01756           DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
    01757           TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
    01758
    01759           _m[t].m5 = 1 << 7 | type << 2 | dir;
    01760         }
    01761       }
    01762     }
    01763
    01764     FOR_ALL_VEHICLES(v) {
    01765       if (v->type != VEH_TRAIN && v->type != VEH_ROAD) continue;
    01766       if (IsBridgeTile(v->tile)) {
    01767         DiagDirection dir = GetTunnelBridgeDirection(v->tile);
    01768
    01769         if (dir != DirToDiagDir(v->direction)) continue;
    01770         switch (dir) {
    01771           default: NOT_REACHED();
    01772           case DIAGDIR_NE: if ((v->x_pos & 0xF) !=  0)            continue; break;
    01773           case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
    01774           case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
    01775           case DIAGDIR_NW: if ((v->y_pos & 0xF) !=  0)            continue; break;
    01776         }
    01777       } else if (v->z_pos > GetSlopeZ(v->x_pos, v->y_pos)) {
    01778         v->tile = GetNorthernBridgeEnd(v->tile);
    01779       } else {
    01780         continue;
    01781       }
    01782       if (v->type == VEH_TRAIN) {
    01783         v->u.rail.track = TRACK_BIT_WORMHOLE;
    01784       } else {
    01785         v->u.road.state = RVSB_WORMHOLE;
    01786       }
    01787     }
    01788   }
    01789
    01790   /* Elrails got added in rev 24 */
    01791   if (CheckSavegameVersion(24)) {
    01792     Vehicle *v;
    01793     RailType min_rail = RAILTYPE_ELECTRIC;
    01794
    01795     FOR_ALL_VEHICLES(v) {
    01796       if (v->type == VEH_TRAIN) {
    01797         RailType rt = RailVehInfo(v->engine_type)->railtype;
    01798
    01799         v->u.rail.railtype = rt;
    01800         if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
    01801       }
    01802     }
    01803
    01804     /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
    01805     for (TileIndex t = 0; t < map_size; t++) {
    01806       switch (GetTileType(t)) {
    01807         case MP_RAILWAY:
    01808           SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    01809           break;
    01810
    01811         case MP_ROAD:
    01812           if (IsLevelCrossing(t)) {
    01813             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    01814           }
    01815           break;
    01816
    01817         case MP_STATION:
    01818           if (IsRailwayStation(t)) {
    01819             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    01820           }
    01821           break;
    01822
    01823         case MP_TUNNELBRIDGE:
    01824           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
    01825             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    01826           }
    01827           break;
    01828
    01829         default:
    01830           break;
    01831       }
    01832     }
    01833
    01834     FOR_ALL_VEHICLES(v) {
    01835       if (v->type == VEH_TRAIN && (IsFrontEngine(v) || IsFreeWagon(v))) TrainConsistChanged(v, true);
    01836     }
    01837
    01838   }
    01839
    01840   /* In version 16.1 of the savegame a player can decide if trains, which get
    01841    * replaced, shall keep their old length. In all prior versions, just default
    01842    * to false */
    01843   if (CheckSavegameVersionOldStyle(16, 1)) {
    01844     FOR_ALL_PLAYERS(p) p->renew_keep_length = false;
    01845   }
    01846
    01847   /* In version 17, ground type is moved from m2 to m4 for depots and
    01848    * waypoints to make way for storing the index in m2. The custom graphics
    01849    * id which was stored in m4 is now saved as a grf/id reference in the
    01850    * waypoint struct. */
    01851   if (CheckSavegameVersion(17)) {
    01852     Waypoint *wp;
    01853
    01854     FOR_ALL_WAYPOINTS(wp) {
    01855       if (wp->deleted == 0) {
    01856         const StationSpec *statspec = NULL;
    01857
    01858         if (HasBit(_m[wp->xy].m3, 4))
    01859           statspec = GetCustomStationSpec(STAT_CLASS_WAYP, _m[wp->xy].m4 + 1);
    01860
    01861         if (statspec != NULL) {
    01862           wp->stat_id = _m[wp->xy].m4 + 1;
    01863           wp->grfid = statspec->grffile->grfid;
    01864           wp->localidx = statspec->localidx;
    01865         } else {
    01866           /* No custom graphics set, so set to default. */
    01867           wp->stat_id = 0;
    01868           wp->grfid = 0;
    01869           wp->localidx = 0;
    01870         }
    01871
    01872         /* Move ground type bits from m2 to m4. */
    01873         _m[wp->xy].m4 = GB(_m[wp->xy].m2, 0, 4);
    01874         /* Store waypoint index in the tile. */
    01875         _m[wp->xy].m2 = wp->index;
    01876       }
    01877     }
    01878   } else {
    01879     /* As of version 17, we recalculate the custom graphic ID of waypoints
    01880      * from the GRF ID / station index. */
    01881     AfterLoadWaypoints();
    01882   }
    01883
    01884   /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
    01885    *  room for PBS. Now in version 21 move it back :P. */
    01886   if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
    01887     for (TileIndex t = 0; t < map_size; t++) {
    01888       switch (GetTileType(t)) {
    01889         case MP_RAILWAY:
    01890           if (HasSignals(t)) {
    01891             /* convert PBS signals to combo-signals */
    01892             if (HasBit(_m[t].m2, 2)) SetSignalType(t, TRACK_X, SIGTYPE_COMBO);
    01893
    01894             /* move the signal variant back */
    01895             SetSignalVariant(t, TRACK_X, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
    01896             ClrBit(_m[t].m2, 3);
    01897           }
    01898
    01899           /* Clear PBS reservation on track */
    01900           if (!IsTileDepotType(t, TRANSPORT_RAIL)) {
    01901             SB(_m[t].m4, 4, 4, 0);
    01902           } else {
    01903             ClrBit(_m[t].m3, 6);
    01904           }
    01905           break;
    01906
    01907         case MP_ROAD: /* Clear PBS reservation on crossing */
    01908           if (IsLevelCrossing(t)) ClrBit(_m[t].m5, 0);
    01909           break;
    01910
    01911         case MP_STATION: /* Clear PBS reservation on station */
    01912           ClrBit(_m[t].m3, 6);
    01913           break;
    01914
    01915         default: break;
    01916       }
    01917     }
    01918   }
    01919
    01920   if (CheckSavegameVersion(22))  UpdatePatches();
    01921
    01922   if (CheckSavegameVersion(25)) {
    01923     Vehicle *v;
    01924     FOR_ALL_VEHICLES(v) {
    01925       if (v->type == VEH_ROAD) {
    01926         v->vehstatus &= ~0x40;
    01927         v->u.road.slot = NULL;
    01928         v->u.road.slot_age = 0;
    01929       }
    01930     }
    01931   } else {
    01932     Vehicle *v;
    01933     FOR_ALL_VEHICLES(v) {
    01934       if (v->type == VEH_ROAD && v->u.road.slot != NULL) v->u.road.slot->num_vehicles++;
    01935     }
    01936   }
    01937
    01938   if (CheckSavegameVersion(26)) {
    01939     Station *st;
    01940     FOR_ALL_STATIONS(st) {
    01941       st->last_vehicle_type = VEH_INVALID;
    01942     }
    01943   }
    01944
    01945   YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
    01946
    01947   if (CheckSavegameVersion(34)) FOR_ALL_PLAYERS(p) ResetPlayerLivery(p);
    01948
    01949   FOR_ALL_PLAYERS(p) {
    01950     p->avail_railtypes = GetPlayerRailtypes(p->index);
    01951     p->avail_roadtypes = GetPlayerRoadtypes(p->index);
    01952   }
    01953
    01954   if (!CheckSavegameVersion(27)) AfterLoadStations();
    01955
    01956   /* Time starts at 0 instead of 1920.
    01957    * Account for this in older games by adding an offset */
    01958   if (CheckSavegameVersion(31)) {
    01959     Station *st;
    01960     Waypoint *wp;
    01961     Engine *e;
    01962     Player *player;
    01963     Industry *i;
    01964     Vehicle *v;
    01965
    01966     _date += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01967     _cur_year += ORIGINAL_BASE_YEAR;
    01968
    01969     FOR_ALL_STATIONS(st)    st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01970     FOR_ALL_WAYPOINTS(wp)   wp->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01971     FOR_ALL_ENGINES(e)      e->intro_date  += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01972     FOR_ALL_PLAYERS(player) player->inaugurated_year += ORIGINAL_BASE_YEAR;
    01973     FOR_ALL_INDUSTRIES(i)   i->last_prod_year        += ORIGINAL_BASE_YEAR;
    01974
    01975     FOR_ALL_VEHICLES(v) {
    01976       v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01977       v->build_year += ORIGINAL_BASE_YEAR;
    01978     }
    01979   }
    01980
    01981   /* From 32 on we save the industry who made the farmland.
    01982    *  To give this prettyness to old savegames, we remove all farmfields and
    01983    *  plant new ones. */
    01984   if (CheckSavegameVersion(32)) {
    01985     Industry *i;
    01986
    01987     for (TileIndex t = 0; t < map_size; t++) {
    01988       if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
    01989         MakeClear(t, CLEAR_GRASS, 3);
    01990       }
    01991     }
    01992
    01993     FOR_ALL_INDUSTRIES(i) {
    01994       uint j;
    01995
    01996       if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
    01997         for (j = 0; j != 50; j++) PlantRandomFarmField(i);
    01998       }
    01999     }
    02000   }
    02001
    02002   /* Setting no refit flags to all orders in savegames from before refit in orders were added */
    02003   if (CheckSavegameVersion(36)) {
    02004     Order *order;
    02005     Vehicle *v;
    02006
    02007     FOR_ALL_ORDERS(order) {
    02008       order->refit_cargo   = CT_NO_REFIT;
    02009       order->refit_subtype = CT_NO_REFIT;
    02010     }
    02011
    02012     FOR_ALL_VEHICLES(v) {
    02013       v->current_order.refit_cargo   = CT_NO_REFIT;
    02014       v->current_order.refit_subtype = CT_NO_REFIT;
    02015     }
    02016   }
    02017
    02018   /* from version 38 we have optional elrails, since we cannot know the
    02019    * preference of a user, let elrails enabled; it can be disabled manually */
    02020   if (CheckSavegameVersion(38)) _patches.disable_elrails = false;
    02021   /* do the same as when elrails were enabled/disabled manually just now */
    02022   SettingsDisableElrail(_patches.disable_elrails);
    02023   SetDefaultRailGui();
    02024
    02025   /* From version 53, the map array was changed for house tiles to allow
    02026    * space for newhouses grf features. A new byte, m7, was also added. */
    02027   if (CheckSavegameVersion(53)) {
    02028     for (TileIndex t = 0; t < map_size; t++) {
    02029       if (IsTileType(t, MP_HOUSE)) {
    02030         if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
    02031           /* Move the construction stage from m3[7..6] to m5[5..4].
    02032            * The construction counter does not have to move. */
    02033           SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
    02034           SB(_m[t].m3, 6, 2, 0);
    02035
    02036           /* The "house is completed" bit is now in m6[2]. */
    02037           SetHouseCompleted(t, false);
    02038         } else {
    02039           /* The "lift has destination" bit has been moved from
    02040            * m5[7] to m7[0]. */
    02041           SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
    02042           ClrBit(_m[t].m5, 7);
    02043
    02044           /* The "lift is moving" bit has been removed, as it does
    02045            * the same job as the "lift has destination" bit. */
    02046           ClrBit(_m[t].m1, 7);
    02047
    02048           /* The position of the lift goes from m1[7..0] to m6[7..2],
    02049            * making m1 totally free, now. The lift position does not
    02050            * have to be a full byte since the maximum value is 36. */
    02051           SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
    02052
    02053           _m[t].m1 = 0;
    02054           _m[t].m3 = 0;
    02055           SetHouseCompleted(t, true);
    02056         }
    02057       }
    02058     }
    02059   }
    02060
    02061   /* Check and update house and town values */
    02062   UpdateHousesAndTowns();
    02063
    02064   if (CheckSavegameVersion(43)) {
    02065     for (TileIndex t = 0; t < map_size; t++) {
    02066       if (IsTileType(t, MP_INDUSTRY)) {
    02067         switch (GetIndustryGfx(t)) {
    02068           case GFX_POWERPLANT_SPARKS:
    02069             SetIndustryAnimationState(t, GB(_m[t].m1, 2, 5));
    02070             break;
    02071
    02072           case GFX_OILWELL_ANIMATED_1:
    02073           case GFX_OILWELL_ANIMATED_2:
    02074           case GFX_OILWELL_ANIMATED_3:
    02075             SetIndustryAnimationState(t, GB(_m[t].m1, 0, 2));
    02076             break;
    02077
    02078           case GFX_COAL_MINE_TOWER_ANIMATED:
    02079           case GFX_COPPER_MINE_TOWER_ANIMATED:
    02080           case GFX_GOLD_MINE_TOWER_ANIMATED:
    02081              SetIndustryAnimationState(t, _m[t].m1);
    02082              break;
    02083
    02084           default: /* No animation states to change */
    02085             break;
    02086         }
    02087       }
    02088     }
    02089   }
    02090
    02091   if (CheckSavegameVersion(44)) {
    02092     Vehicle *v;
    02093     /* If we remove a station while cargo from it is still enroute, payment calculation will assume
    02094      * 0, 0 to be the source of the cargo, resulting in very high payments usually. v->source_xy
    02095      * stores the coordinates, preserving them even if the station is removed. However, if a game is loaded
    02096      * where this situation exists, the cargo-source information is lost. in this case, we set the source
    02097      * to the current tile of the vehicle to prevent excessive profits
    02098      */
    02099     FOR_ALL_VEHICLES(v) {
    02100       const CargoList::List *packets = v->cargo.Packets();
    02101       for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
    02102         CargoPacket *cp = *it;
    02103         cp->source_xy = IsValidStationID(cp->source) ? GetStation(cp->source)->xy : v->tile;
    02104         cp->loaded_at_xy = cp->source_xy;
    02105       }
    02106       v->cargo.InvalidateCache();
    02107     }
    02108
    02109     /* Store position of the station where the goods come from, so there
    02110      * are no very high payments when stations get removed. However, if the
    02111      * station where the goods came from is already removed, the source
    02112      * information is lost. In that case we set it to the position of this
    02113      * station */
    02114     Station *st;
    02115     FOR_ALL_STATIONS(st) {
    02116       for (CargoID c = 0; c < NUM_CARGO; c++) {
    02117         GoodsEntry *ge = &st->goods[c];
    02118
    02119         const CargoList::List *packets = ge->cargo.Packets();
    02120         for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
    02121           CargoPacket *cp = *it;
    02122           cp->source_xy = IsValidStationID(cp->source) ? GetStation(cp->source)->xy : st->xy;
    02123           cp->loaded_at_xy = cp->source_xy;
    02124         }
    02125       }
    02126     }
    02127   }
    02128
    02129   if (CheckSavegameVersion(45)) {
    02130     Vehicle *v;
    02131     /* Originally just the fact that some cargo had been paid for was
    02132      * stored to stop people cheating and cashing in several times. This
    02133      * wasn't enough though as it was cleared when the vehicle started
    02134      * loading again, even if it didn't actually load anything, so now the
    02135      * amount of cargo that has been paid for is stored. */
    02136     FOR_ALL_VEHICLES(v) {
    02137       const CargoList::List *packets = v->cargo.Packets();
    02138       for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
    02139         CargoPacket *cp = *it;
    02140         cp->paid_for = HasBit(v->vehicle_flags, 2);
    02141       }
    02142       ClrBit(v->vehicle_flags, 2);
    02143       v->cargo.InvalidateCache();
    02144     }
    02145   }
    02146
    02147   /* Buoys do now store the owner of the previous water tile, which can never
    02148    * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
    02149   if (CheckSavegameVersion(46)) {
    02150     Station *st;
    02151     FOR_ALL_STATIONS(st) {
    02152       if (st->IsBuoy() && IsTileOwner(st->xy, OWNER_NONE) && TileHeight(st->xy) == 0) SetTileOwner(st->xy, OWNER_WATER);
    02153     }
    02154   }
    02155
    02156   if (CheckSavegameVersion(50)) {
    02157     Vehicle *v;
    02158     /* Aircraft units changed from 8 mph to 1 km/h */
    02159     FOR_ALL_VEHICLES(v) {
    02160       if (v->type == VEH_AIRCRAFT && v->subtype <= AIR_AIRCRAFT) {
    02161         const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
    02162         v->cur_speed *= 129;
    02163         v->cur_speed /= 10;
    02164         v->max_speed = avi->max_speed;
    02165         v->acceleration = avi->acceleration;
    02166       }
    02167     }
    02168   }
    02169
    02170   if (CheckSavegameVersion(49)) FOR_ALL_PLAYERS(p) p->face = ConvertFromOldPlayerFace(p->face);
    02171
    02172   if (CheckSavegameVersion(52)) {
    02173     for (TileIndex t = 0; t < map_size; t++) {
    02174       if (IsStatueTile(t)) {
    02175         _m[t].m2 = CalcClosestTownFromTile(t, (uint)-1)->index;
    02176       }
    02177     }
    02178   }
    02179
    02180   /* A patch option containing the proportion of towns that grow twice as
    02181    * fast was added in version 54. From version 56 this is now saved in the
    02182    * town as cities can be built specifically in the scenario editor. */
    02183   if (CheckSavegameVersion(56)) {
    02184     Town *t;
    02185
    02186     FOR_ALL_TOWNS(t) {
    02187       if (_patches.larger_towns != 0 && (t->index % _patches.larger_towns) == 0) {
    02188         t->larger_town = true;
    02189       }
    02190     }
    02191   }
    02192
    02193   if (CheckSavegameVersion(57)) {
    02194     Vehicle *v;
    02195     /* Added a FIFO queue of vehicles loading at stations */
    02196     FOR_ALL_VEHICLES(v) {
    02197       if ((v->type != VEH_TRAIN || IsFrontEngine(v)) &&  // for all locs
    02198           !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
    02199           v->current_order.type == OT_LOADING) {         // loading
    02200         GetStation(v->last_station_visited)->loading_vehicles.push_back(v);
    02201
    02202         /* The loading finished flag is *only* set when actually completely
    02203          * finished. Because the vehicle is loading, it is not finished. */
    02204         ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
    02205       }
    02206     }
    02207   } else if (CheckSavegameVersion(59)) {
    02208     /* For some reason non-loading vehicles could be in the station's loading vehicle list */
    02209
    02210     Station *st;
    02211     FOR_ALL_STATIONS(st) {
    02212       std::list<Vehicle *>::iterator iter;
    02213       for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
    02214         Vehicle *v = *iter;
    02215         iter++;
    02216         if (v->current_order.type != OT_LOADING) st->loading_vehicles.remove(v);
    02217       }
    02218     }
    02219   }
    02220
    02221   if (CheckSavegameVersion(58)) {
    02222     /* patch difficulty number_industries other then zero get bumped to +1
    02223      * since a new option (very low at position1) has been added */
    02224     if (_opt.diff.number_industries > 0) {
    02225       _opt.diff.number_industries++;
    02226     }
    02227
    02228     /* Same goes for number of towns, although no test is needed, just an increment */
    02229     _opt.diff.number_towns++;
    02230   }
    02231
    02232   if (CheckSavegameVersion(64)) {
    02233     /* copy the signal type/variant and move signal states bits */
    02234     for (TileIndex t = 0; t < map_size; t++) {
    02235       if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
    02236         SetSignalStates(t, GB(_m[t].m2, 4, 4));
    02237         SetSignalVariant(t, INVALID_TRACK, GetSignalVariant(t, TRACK_X));
    02238         SetSignalType(t, INVALID_TRACK, GetSignalType(t, TRACK_X));
    02239         ClrBit(_m[t].m2, 7);
    02240       }
    02241     }
    02242   }
    02243
    02244   if (CheckSavegameVersion(69)) {
    02245     /* In some old savegames a bit was cleared when it should not be cleared */
    02246     Vehicle *v;
    02247     FOR_ALL_VEHICLES(v) {
    02248       if (v->type == VEH_ROAD && (v->u.road.state == 250 || v->u.road.state == 251)) {
    02249         SetBit(v->u.road.state, RVS_IS_STOPPING);
    02250       }
    02251     }
    02252   }
    02253
    02254   if (CheckSavegameVersion(70)) {
    02255     /* Added variables to support newindustries */
    02256     Industry *i;
    02257     FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
    02258   }
    02259
    02260   /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
    02261       Replace the owner for those by OWNER_NONE. */
    02262   if (CheckSavegameVersion(82)) {
    02263     for (TileIndex t = 0; t < map_size; t++) {
    02264       if (IsTileType(t, MP_WATER) &&
    02265           GetWaterTileType(t) == WATER_TILE_CLEAR &&
    02266           GetTileOwner(t) == OWNER_WATER &&
    02267           TileHeight(t) != 0) {
    02268         SetTileOwner(t, OWNER_NONE);
    02269       }
    02270     }
    02271   }
    02272
    02273   /*
    02274    * Add the 'previous' owner to the ship depots so we can reset it with
    02275    * the correct values when it gets destroyed. This prevents that
    02276    * someone can remove canals owned by somebody else and it prevents
    02277    * making floods using the removal of ship depots.
    02278    */
    02279   if (CheckSavegameVersion(83)) {
    02280     for (TileIndex t = 0; t < map_size; t++) {
    02281       if (IsTileType(t, MP_WATER) && IsShipDepot(t)) {
    02282         _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
    02283       }
    02284     }
    02285   }
    02286
    02287   if (CheckSavegameVersion(74)) {
    02288     Station *st;
    02289     FOR_ALL_STATIONS(st) {
    02290       for (CargoID c = 0; c < NUM_CARGO; c++) {
    02291         st->goods[c].last_speed = 0;
    02292         if (st->goods[c].cargo.Count() != 0) SetBit(st->goods[c].acceptance_pickup, GoodsEntry::PICKUP);
    02293       }
    02294     }
    02295   }
    02296
    02297   if (CheckSavegameVersion(78)) {
    02298     Industry *i;
    02299     uint j;
    02300     FOR_ALL_INDUSTRIES(i) {
    02301       const IndustrySpec *indsp = GetIndustrySpec(i->type);
    02302       for (j = 0; j < lengthof(i->produced_cargo); j++) {
    02303         i->produced_cargo[j] = indsp->produced_cargo[j];
    02304       }
    02305       for (j = 0; j < lengthof(i->accepts_cargo); j++) {
    02306         i->accepts_cargo[j] = indsp->accepts_cargo[j];
    02307       }
    02308     }
    02309   }
    02310
    02311   /* Before version 81, the density of grass was always stored as zero, and
    02312    * grassy trees were always drawn fully grassy. Furthermore, trees on rough
    02313    * land used to have zero density, now they have full density. Therefore,
    02314    * make all grassy/rough land trees have a density of 3. */
    02315   if (CheckSavegameVersion(81)) {
    02316     for (TileIndex t = 0; t < map_size; t++) {
    02317       if (GetTileType(t) == MP_TREES) {
    02318         TreeGround groundType = GetTreeGround(t);
    02319         if (groundType != TREE_GROUND_SNOW_DESERT) SetTreeGroundDensity(t, groundType, 3);
    02320       }
    02321     }
    02322   }
    02323
    02324   if (CheckSavegameVersion(84)) {
    02325     /* Update go to buoy orders because they are just waypoints */
    02326     Order *order;
    02327     FOR_ALL_ORDERS(order) {
    02328       if (order->type == OT_GOTO_STATION && GetStation(order->dest)->IsBuoy()) {
    02329         order->flags = 0;
    02330       }
    02331     }
    02332
    02333     /* Set all share owners to PLAYER_SPECTATOR for
    02334      * 1) all inactive players
    02335      *     (when inactive players were stored in the savegame - TTD, TTDP and some
    02336      *      *really* old revisions of OTTD; else it is already set in InitializePlayers())
    02337      * 2) shares that are owned by inactive players or self
    02338      *     (caused by cheating players in earlier revisions) */
    02339     Player *p;
    02340     FOR_ALL_PLAYERS(p) {
    02341       if (!p->is_active) {
    02342         for (uint i = 0; i < 4; i++) { p->share_owners[i] = PLAYER_SPECTATOR; }
    02343       } else {
    02344         for (uint i = 0; i < 4; i++) {
    02345           PlayerID o = p->share_owners[i];
    02346           if (o == PLAYER_SPECTATOR) continue;
    02347           if (!IsValidPlayer(o) || o == p->index || !GetPlayer(o)->is_active) p->share_owners[i] = PLAYER_SPECTATOR;
    02348         }
    02349       }
    02350     }
    02351   }
    02352
    02353   if (CheckSavegameVersion(86)) {
    02354     for (TileIndex t = 0; t < map_size; t++) {
    02355       /* Now all crossings should be in correct state */
    02356       if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
    02357
    02358       /* Move river flag and update canals to use water class */
    02359       if (IsTileType(t, MP_WATER)) {
    02360         if (GetWaterClass(t) != WATER_CLASS_RIVER) {
    02361           if (IsWater(t)) {
    02362             Owner o = GetTileOwner(t);
    02363             if (o == OWNER_WATER) {
    02364               MakeWater(t);
    02365             } else {
    02366               MakeCanal(t, o, Random());
    02367             }
    02368           } else if (IsShipDepot(t)) {
    02369             Owner o = (Owner)_m[t].m4; // Original water owner
    02370             SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
    02371           }
    02372         }
    02373       }
    02374     }
    02375
    02376     /* Update locks, depots, docks and buoys to have a water class based
    02377      * on its neighbouring tiles. Done after river and canal updates to
    02378      * ensure neighbours are correct. */
    02379     for (TileIndex t = 0; t < map_size; t++) {
    02380       if (GetTileSlope(t, NULL) != SLOPE_FLAT) continue;
    02381
    02382       if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t);
    02383       if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t);
    02384     }
    02385   }
    02386
    02387   if (CheckSavegameVersion(87)) {
    02388     for (TileIndex t = 0; t < map_size; t++) {
    02389       /* skip oil rigs at borders! */
    02390       if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
    02391           (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
    02392         /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
    02393          * This conversion has to be done before buoys with invalid owner are removed. */
    02394         SetWaterClass(t, WATER_CLASS_SEA);
    02395       }
    02396
    02397       if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
    02398         Owner o = GetTileOwner(t);
    02399         if (IsValidPlayer(o) && !GetPlayer(o)->is_active) {
    02400           _current_player = o;
    02401           ChangeTileOwner(t, o, PLAYER_SPECTATOR);
    02402         }
    02403         if (IsBuoyTile(t)) {
    02404           /* reset buoy owner to OWNER_NONE in the station struct
    02405            * (even if it is owned by active player) */
    02406           GetStationByTile(t)->owner = OWNER_NONE;
    02407         }
    02408       } else if (IsTileType(t, MP_ROAD)) {
    02409         /* works for all RoadTileType */
    02410         for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
    02411           /* update even non-existing road types to update tile owner too */
    02412           Owner o = GetRoadOwner(t, rt);
    02413           if (IsValidPlayer(o) && !GetPlayer(o)->is_active) SetRoadOwner(t, rt, OWNER_NONE);
    02414         }
    02415         if (IsLevelCrossing(t)) {
    02416           Owner o = GetTileOwner(t);
    02417           if (!GetPlayer(o)->is_active) {
    02418             /* remove leftover rail piece from crossing (from very old savegames) */
    02419             _current_player = o;
    02420             DoCommand(t, 0, GetCrossingRailTrack(t), DC_EXEC | DC_BANKRUPT, CMD_REMOVE_SINGLE_RAIL);
    02421           }
    02422         }
    02423       }
    02424     }
    02425
    02426     /* Convert old PF settings to new */
    02427     if (_patches.yapf.rail_use_yapf || CheckSavegameVersion(28)) {
    02428       _patches.pathfinder_for_trains = VPF_YAPF;
    02429     } else {
    02430       _patches.pathfinder_for_trains = (_patches.new_pathfinding_all ? VPF_NPF : VPF_NTP);
    02431     }
    02432
    02433     if (_patches.yapf.road_use_yapf || CheckSavegameVersion(28)) {
    02434       _patches.pathfinder_for_roadvehs = VPF_YAPF;
    02435     } else {
    02436       _patches.pathfinder_for_roadvehs = (_patches.new_pathfinding_all ? VPF_NPF : VPF_OPF);
    02437     }
    02438
    02439     if (_patches.yapf.ship_use_yapf) {
    02440       _patches.pathfinder_for_ships = VPF_YAPF;
    02441     } else {
    02442       _patches.pathfinder_for_ships = (_patches.new_pathfinding_all ? VPF_NPF : VPF_OPF);
    02443     }
    02444   }
    02445
    02446   if (CheckSavegameVersion(88)) {
    02447     /* Profits are now with 8 bit fract */
    02448     Vehicle *v;
    02449     FOR_ALL_VEHICLES(v) {
    02450       v->profit_this_year <<= 8;
    02451       v->profit_last_year <<= 8;
    02452       v->running_ticks = 0;
    02453     }
    02454   }
    02455
    02456   if (CheckSavegameVersion(91)) {
    02457     /* Increase HouseAnimationFrame from 5 to 7 bits */
    02458     for (TileIndex t = 0; t < map_size; t++) {
    02459       if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
    02460         SetHouseAnimationFrame(t, GB(_m[t].m6, 3, 5));
    02461       }
    02462     }
    02463   }
    02464
    02465   if (CheckSavegameVersion(62)) {
    02466     /* Remove all trams from savegames without tram support.
    02467      * There would be trams without tram track under causing crashes sooner or later. */
    02468     Vehicle *v;
    02469     FOR_ALL_VEHICLES(v) {
    02470       if (v->type == VEH_ROAD && v->First() == v &&
    02471           HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
    02472         if (_switch_mode_errorstr == INVALID_STRING_ID || _switch_mode_errorstr == STR_NEWGRF_COMPATIBLE_LOAD_WARNING) {
    02473           _switch_mode_errorstr = STR_LOADGAME_REMOVED_TRAMS;
    02474         }
    02475         delete v;
    02476       }
    02477     }
    02478   }
    02479
    02480   /* Just always run this for 0.6. Doesn't hurt to fix the owners a second time. */
    02481   if (CheckSavegameVersion(103)) {
    02482     /* signs with invalid owner left from older savegames */
    02483     Sign *si;
    02484     FOR_ALL_SIGNS(si) {
    02485       if (si->owner != OWNER_NONE && !IsValidPlayer(si->owner) && GetPlayer(si->owner)->is_active) si->owner = OWNER_NONE;
    02486     }
    02487   }
    02488
    02489   return InitializeWindowsAndCaches();
    02490 }
    02491
    02498 void ReloadNewGRFData()
    02499 {
    02500   /* reload grf data */
    02501   GfxLoadSprites();
    02502   LoadStringWidthTable();
    02503   /* reload vehicles */
    02504   ResetVehiclePosHash();
    02505   AfterLoadVehicles(false);
    02506   StartupEngines();
    02507   /* update station and waypoint graphics */
    02508   AfterLoadWaypoints();
    02509   AfterLoadStations();
    02510   /* Check and update house and town values */
    02511   UpdateHousesAndTowns();
    02512   /* redraw the whole screen */
    02513   MarkWholeScreenDirty();
    02514   CheckTrainsLengths();
    02515 }