openttd.cpp

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

Generated on Wed Oct 1 17:03:22 2008 for openttd by  doxygen 1.5.6