# afterload.cpp

Go to the documentation of this file.

    00001 /* $Id: afterload.cpp 17346 2009-09-01 13:16:53Z rubidium $ */
    00002
    00005 #include "../stdafx.h"
    00006 #include "../void_map.h"
    00007 #include "../signs_base.h"
    00008 #include "../window_func.h"
    00009 #include "../fios.h"
    00010 #include "../train.h"
    00011 #include "../roadveh.h"
    00012 #include "../string_func.h"
    00013 #include "../gamelog.h"
    00014 #include "../gamelog_internal.h"
    00015 #include "../network/network.h"
    00016 #include "../gfxinit.h"
    00017 #include "../functions.h"
    00018 #include "../industry_map.h"
    00019 #include "../town_map.h"
    00020 #include "../clear_map.h"
    00021 #include "../vehicle_func.h"
    00022 #include "../newgrf_station.h"
    00023 #include "../yapf/yapf.hpp"
    00024 #include "../elrail_func.h"
    00025 #include "../signs_func.h"
    00026 #include "../aircraft.h"
    00027 #include "../unmovable_map.h"
    00028 #include "../tree_map.h"
    00029 #include "../company_func.h"
    00030 #include "../road_cmd.h"
    00031 #include "../ai/ai.hpp"
    00032 #include "../animated_tile_func.h"
    00033
    00034 #include "../economy_base.h"
    00035 #include "table/strings.h"
    00036
    00037 #include "saveload_internal.h"
    00038
    00039 #include <signal.h>
    00040
    00041 extern StringID _switch_mode_errorstr;
    00042 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
    00043 extern void InitializeRailGUI();
    00044
    00056 void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
    00057 {
    00058   /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
    00059    * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
    00060   if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
    00061     if (include_invalid_water_class) {
    00062       SetWaterClass(t, WATER_CLASS_INVALID);
    00063       return;
    00064     } else {
    00065       NOT_REACHED();
    00066     }
    00067   }
    00068
    00069   /* Mark tile dirty in all cases */
    00070   MarkTileDirtyByTile(t);
    00071
    00072   if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
    00073     /* tiles at map borders are always WATER_CLASS_SEA */
    00074     SetWaterClass(t, WATER_CLASS_SEA);
    00075     return;
    00076   }
    00077
    00078   bool has_water = false;
    00079   bool has_canal = false;
    00080   bool has_river = false;
    00081
    00082   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
    00083     TileIndex neighbour = TileAddByDiagDir(t, dir);
    00084     switch (GetTileType(neighbour)) {
    00085       case MP_WATER:
    00086         /* clear water and shipdepots have already a WaterClass associated */
    00087         if (IsCoast(neighbour)) {
    00088           has_water = true;
    00089         } else if (!IsLock(neighbour)) {
    00090           switch (GetWaterClass(neighbour)) {
    00091             case WATER_CLASS_SEA:   has_water = true; break;
    00092             case WATER_CLASS_CANAL: has_canal = true; break;
    00093             case WATER_CLASS_RIVER: has_river = true; break;
    00094             default: NOT_REACHED();
    00095           }
    00096         }
    00097         break;
    00098
    00099       case MP_RAILWAY:
    00100         /* Shore or flooded halftile */
    00101         has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
    00102         break;
    00103
    00104       case MP_TREES:
    00105         /* trees on shore */
    00106         has_water |= (GetTreeGround(neighbour) == TREE_GROUND_SHORE);
    00107         break;
    00108
    00109       default: break;
    00110     }
    00111   }
    00112
    00113   if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
    00114     SetWaterClass(t, WATER_CLASS_INVALID);
    00115     return;
    00116   }
    00117
    00118   if (has_river && !has_canal) {
    00119     SetWaterClass(t, WATER_CLASS_RIVER);
    00120   } else if (has_canal || !has_water) {
    00121     SetWaterClass(t, WATER_CLASS_CANAL);
    00122   } else {
    00123     SetWaterClass(t, WATER_CLASS_SEA);
    00124   }
    00125 }
    00126
    00127 static void ConvertTownOwner()
    00128 {
    00129   for (TileIndex tile = 0; tile != MapSize(); tile++) {
    00130     switch (GetTileType(tile)) {
    00131       case MP_ROAD:
    00132         if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
    00133           _m[tile].m3 = OWNER_TOWN;
    00134         }
    00135         /* FALLTHROUGH */
    00136
    00137       case MP_TUNNELBRIDGE:
    00138         if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN);
    00139         break;
    00140
    00141       default: break;
    00142     }
    00143   }
    00144 }
    00145
    00146 /* since savegame version 4.1, exclusive transport rights are stored at towns */
    00147 static void UpdateExclusiveRights()
    00148 {
    00149   Town *t;
    00150
    00151   FOR_ALL_TOWNS(t) {
    00152     t->exclusivity = INVALID_COMPANY;
    00153   }
    00154
    00155   /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
    00156    *   could be implemented this way:
    00157    * 1.) Go through all stations
    00158    *     Build an array town_blocked[ town_id ][ company_id ]
    00159    *     that stores if at least one station in that town is blocked for a company
    00160    * 2.) Go through that array, if you find a town that is not blocked for
    00161    *     one company, but for all others, then give him exclusivity.
    00162    */
    00163 }
    00164
    00165 static const byte convert_currency[] = {
    00166    0,  1, 12,  8,  3,
    00167   10, 14, 19,  4,  5,
    00168    9, 11, 13,  6, 17,
    00169   16, 22, 21,  7, 15,
    00170   18,  2, 20,
    00171 };
    00172
    00173 /* since savegame version 4.2 the currencies are arranged differently */
    00174 static void UpdateCurrencies()
    00175 {
    00176   _settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
    00177 }
    00178
    00179 /* Up to revision 1413 the invisible tiles at the southern border have not been
    00180  * MP_VOID, even though they should have. This is fixed by this function
    00181  */
    00182 static void UpdateVoidTiles()
    00183 {
    00184   uint i;
    00185
    00186   for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
    00187   for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
    00188 }
    00189
    00190 static inline RailType UpdateRailType(RailType rt, RailType min)
    00191 {
    00192   return rt >= min ? (RailType)(rt + 1): rt;
    00193 }
    00194
    00206 static bool InitializeWindowsAndCaches()
    00207 {
    00208   /* Initialize windows */
    00209   ResetWindowSystem();
    00210   SetupColoursAndInitialWindow();
    00211
    00212   ResetViewportAfterLoadGame();
    00213
    00214   /* Update coordinates of the signs. */
    00215   UpdateAllStationVirtCoord();
    00216   UpdateAllSignVirtCoords();
    00217   UpdateAllTownVirtCoords();
    00218   UpdateAllWaypointSigns();
    00219
    00220   Company *c;
    00221   FOR_ALL_COMPANIES(c) {
    00222     /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
    00223      * accordingly if it is not the case.  No need to set it on companies that are not been used already,
    00224      * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
    00225     if (_file_to_saveload.filetype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
    00226       c->inaugurated_year = _cur_year;
    00227     }
    00228   }
    00229
    00230   SetCachedEngineCounts();
    00231
    00232   /* Towns have a noise controlled number of airports system
    00233    * So each airport's noise value must be added to the town->noise_reached value
    00234    * Reset each town's noise_reached value to '0' before. */
    00235   UpdateAirportsNoise();
    00236
    00237   CheckTrainsLengths();
    00238
    00239   return true;
    00240 }
    00241
    00242 typedef void (CDECL *SignalHandlerPointer)(int);
    00243 static SignalHandlerPointer _prev_segfault = NULL;
    00244 static SignalHandlerPointer _prev_abort    = NULL;
    00245 static SignalHandlerPointer _prev_fpe      = NULL;
    00246
    00247 static void CDECL HandleSavegameLoadCrash(int signum);
    00248
    00253 static void SetSignalHandlers()
    00254 {
    00255   _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
    00256   _prev_abort    = signal(SIGABRT, HandleSavegameLoadCrash);
    00257   _prev_fpe      = signal(SIGFPE,  HandleSavegameLoadCrash);
    00258 }
    00259
    00263 static void ResetSignalHandlers()
    00264 {
    00265   signal(SIGSEGV, _prev_segfault);
    00266   signal(SIGABRT, _prev_abort);
    00267   signal(SIGFPE,  _prev_fpe);
    00268 }
    00269
    00275 static const GRFIdentifier *GetOverriddenIdentifier(const GRFConfig *c)
    00276 {
    00277   const LoggedAction *la = &_gamelog_action[_gamelog_actions - 1];
    00278   if (la->at != GLAT_LOAD) return c;
    00279
    00280   const LoggedChange *lcend = &la->change[la->changes];
    00281   for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
    00282     if (lc->ct == GLCT_GRFCOMPAT && lc->grfcompat.grfid == c->grfid) return &lc->grfcompat;
    00283   }
    00284
    00285   return c;
    00286 }
    00287
    00294 static void CDECL HandleSavegameLoadCrash(int signum)
    00295 {
    00296   ResetSignalHandlers();
    00297
    00298   char buffer[8192];
    00299   char *p = buffer;
    00300   p += seprintf(p, lastof(buffer),
    00301       "Loading your savegame caused OpenTTD to crash.\n"
    00302       "This is most likely caused by a missing NewGRF or a NewGRF that has been\n"
    00303       "loaded as replacement for a missing NewGRF. OpenTTD cannot easily\n"
    00304       "determine whether a replacement NewGRF is of a newer or older version.\n"
    00305       "It will load a NewGRF with the same GRF ID as the missing NewGRF. This\n"
    00306       "means that if the author makes incompatible NewGRFs with the same GRF ID\n"
    00307       "OpenTTD cannot magically do the right thing. In most cases OpenTTD will\n"
    00308       "load the savegame and not crash, but this is an exception.\n"
    00309       "Please load the savegame with the appropriate NewGRFs. When loading a\n"
    00310       "savegame still crashes when all NewGRFs are found you should file a\n"
    00311       "bug report. The missing NewGRFs are:\n");
    00312
    00313   for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
    00314     if (HasBit(c->flags, GCF_COMPATIBLE)) {
    00315       const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
    00316       char buf[40];
    00317       md5sumToString(buf, lastof(buf), replaced->md5sum);
    00318       p += seprintf(p, lastof(buffer), "NewGRF %08X (checksum %s) not found.\n  Loaded NewGRF \"%s\" with same GRF ID instead.\n", BSWAP32(c->grfid), buf, c->filename);
    00319     }
    00320     if (c->status == GCS_NOT_FOUND) {
    00321       char buf[40];
    00322       md5sumToString(buf, lastof(buf), c->md5sum);
    00323       p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s.\n", BSWAP32(c->grfid), c->filename, buf);
    00324     }
    00325   }
    00326
    00327   ShowInfo(buffer);
    00328
    00329   SignalHandlerPointer call = NULL;
    00330   switch (signum) {
    00331     case SIGSEGV: call = _prev_segfault; break;
    00332     case SIGABRT: call = _prev_abort; break;
    00333     case SIGFPE:  call = _prev_fpe; break;
    00334     default: NOT_REACHED();
    00335   }
    00336   if (call != NULL) call(signum);
    00337 }
    00338
    00344 static void FixOwnerOfRailTrack(TileIndex t)
    00345 {
    00346   assert(!IsValidCompanyID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
    00347
    00348   /* remove leftover rail piece from crossing (from very old savegames) */
    00349   Vehicle *v = NULL, *w;
    00350   FOR_ALL_VEHICLES(w) {
    00351     if (w->type == VEH_TRAIN && w->tile == t) {
    00352       v = w;
    00353       break;
    00354     }
    00355   }
    00356
    00357   if (v != NULL) {
    00358     /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
    00359     SetTileOwner(t, v->owner);
    00360     return;
    00361   }
    00362
    00363   /* try to find any connected rail */
    00364   for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
    00365     TileIndex tt = t + TileOffsByDiagDir(dd);
    00366     if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
    00367         GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
    00368         IsValidCompanyID(GetTileOwner(tt))) {
    00369       SetTileOwner(t, GetTileOwner(tt));
    00370       return;
    00371     }
    00372   }
    00373
    00374   if (IsLevelCrossingTile(t)) {
    00375     /* else change the crossing to normal road (road vehicles won't care) */
    00376     MakeRoadNormal(t, GetCrossingRoadBits(t), GetRoadTypes(t), GetTownIndex(t),
    00377       GetRoadOwner(t, ROADTYPE_ROAD), GetRoadOwner(t, ROADTYPE_TRAM));
    00378     return;
    00379   }
    00380
    00381   /* if it's not a crossing, make it clean land */
    00382   MakeClear(t, CLEAR_GRASS, 0);
    00383 }
    00384
    00385 bool AfterLoadGame()
    00386 {
    00387   SetSignalHandlers();
    00388
    00389   TileIndex map_size = MapSize();
    00390   Company *c;
    00391
    00392   if (CheckSavegameVersion(98)) GamelogOldver();
    00393
    00394   GamelogTestRevision();
    00395   GamelogTestMode();
    00396
    00397   if (CheckSavegameVersion(98)) GamelogGRFAddList(_grfconfig);
    00398
    00399   /* in very old versions, size of train stations was stored differently */
    00400   if (CheckSavegameVersion(2)) {
    00401     Station *st;
    00402     FOR_ALL_STATIONS(st) {
    00403       if (st->train_tile != 0 && st->trainst_h == 0) {
    00404         uint n = _savegame_type == SGT_OTTD ? 4 : 3; // OTTD uses 4 bits per dimensions, TTD 3 bits
    00405         uint w = GB(st->trainst_w, n, n);
    00406         uint h = GB(st->trainst_w, 0, n);
    00407
    00408         if (GetRailStationAxis(st->train_tile) != AXIS_X) Swap(w, h);
    00409
    00410         st->trainst_w = w;
    00411         st->trainst_h = h;
    00412
    00413         assert(GetStationIndex(st->train_tile + TileDiffXY(w - 1, h - 1)) == st->index);
    00414       }
    00415     }
    00416   }
    00417
    00418   /* in version 2.1 of the savegame, town owner was unified. */
    00419   if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
    00420
    00421   /* from version 4.1 of the savegame, exclusive rights are stored at towns */
    00422   if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
    00423
    00424   /* from version 4.2 of the savegame, currencies are in a different order */
    00425   if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
    00426
    00427   /* In old version there seems to be a problem that water is owned by
    00428    * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
    00429    * (4.3) version, so I just check when versions are older, and then
    00430    * walk through the whole map.. */
    00431   if (CheckSavegameVersionOldStyle(4, 3)) {
    00432     for (TileIndex t = 0; t < map_size; t++) {
    00433       if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
    00434         SetTileOwner(t, OWNER_WATER);
    00435       }
    00436     }
    00437   }
    00438
    00439   /* Update all waypoints */
    00440   if (CheckSavegameVersion(12)) FixOldWaypoints();
    00441
    00442   if (CheckSavegameVersion(84)) {
    00443     FOR_ALL_COMPANIES(c) {
    00444       c->name = CopyFromOldName(c->name_1);
    00445       if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
    00446       c->president_name = CopyFromOldName(c->president_name_1);
    00447       if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
    00448     }
    00449
    00450     Station *st;
    00451     FOR_ALL_STATIONS(st) {
    00452       st->name = CopyFromOldName(st->string_id);
    00453       /* generating new name would be too much work for little effect, use the station name fallback */
    00454       if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
    00455     }
    00456
    00457     Town *t;
    00458     FOR_ALL_TOWNS(t) {
    00459       t->name = CopyFromOldName(t->townnametype);
    00460       if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
    00461     }
    00462
    00463     Waypoint *wp;
    00464     FOR_ALL_WAYPOINTS(wp) {
    00465       wp->name = CopyFromOldName(wp->string);
    00466       wp->string = STR_NULL;
    00467     }
    00468   }
    00469
    00470   /* From this point the old names array is cleared. */
    00471   ResetOldNames();
    00472
    00473   if (CheckSavegameVersion(106)) {
    00474     /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
    00475     Station *st;
    00476     FOR_ALL_STATIONS(st) {
    00477       if (st->airport_tile == 0) st->airport_tile = INVALID_TILE;
    00478       if (st->dock_tile    == 0) st->dock_tile    = INVALID_TILE;
    00479       if (st->train_tile   == 0) st->train_tile   = INVALID_TILE;
    00480     }
    00481
    00482     /* the same applies to Company::location_of_HQ */
    00483     Company *c;
    00484     FOR_ALL_COMPANIES(c) {
    00485       if (c->location_of_HQ == 0 || (CheckSavegameVersion(4) && c->location_of_HQ == 0xFFFF)) {
    00486         c->location_of_HQ = INVALID_TILE;
    00487       }
    00488     }
    00489   }
    00490
    00491   /* convert road side to my format. */
    00492   if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
    00493
    00494   /* Check if all NewGRFs are present, we are very strict in MP mode */
    00495   GRFListCompatibility gcf_res = IsGoodGRFConfigList();
    00496   if (_networking && gcf_res != GLC_ALL_GOOD) {
    00497     SetSaveLoadError(STR_NETWORK_ERR_CLIENT_NEWGRF_MISMATCH);
    00498     /* Restore the signals */
    00499     ResetSignalHandlers();
    00500     return false;
    00501   }
    00502
    00503   switch (gcf_res) {
    00504     case GLC_COMPATIBLE: _switch_mode_errorstr = STR_NEWGRF_COMPATIBLE_LOAD_WARNING; break;
    00505     case GLC_NOT_FOUND: _switch_mode_errorstr = STR_NEWGRF_DISABLED_WARNING; _pause_game = -1; break;
    00506     default: break;
    00507   }
    00508
    00509   /* Update current year
    00510    * must be done before loading sprites as some newgrfs check it */
    00511   SetDate(_date);
    00512
    00513   /* Force dynamic engines off when loading older savegames */
    00514   if (CheckSavegameVersion(95)) _settings_game.vehicle.dynamic_engines = 0;
    00515
    00516   /* Load the sprites */
    00517   GfxLoadSprites();
    00518   LoadStringWidthTable();
    00519
    00520   /* Copy temporary data to Engine pool */
    00521   CopyTempEngineData();
    00522
    00523   /* Connect front and rear engines of multiheaded trains and converts
    00524    * subtype to the new format */
    00525   if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
    00526
    00527   /* Connect front and rear engines of multiheaded trains */
    00528   ConnectMultiheadedTrains();
    00529
    00530   /* reinit the landscape variables (landscape might have changed) */
    00531   InitializeLandscapeVariables(true);
    00532
    00533   /* Update all vehicles */
    00534   AfterLoadVehicles(true);
    00535
    00536   /* Make sure there is an AI attached to an AI company */
    00537   {
    00538     Company *c;
    00539     FOR_ALL_COMPANIES(c) {
    00540       if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
    00541     }
    00542   }
    00543
    00544   /* make sure there is a town in the game */
    00545   if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, UINT_MAX)) {
    00546     SetSaveLoadError(STR_NO_TOWN_IN_SCENARIO);
    00547     /* Restore the signals */
    00548     ResetSignalHandlers();
    00549     return false;
    00550   }
    00551
    00552   /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
    00553    * This problem appears in savegame version 21 too, see r3455. But after loading the
    00554    * savegame and saving again, the buggy map array could be converted to new savegame
    00555    * version. It didn't show up before r12070. */
    00556   if (CheckSavegameVersion(87)) UpdateVoidTiles();
    00557
    00558   /* If Load Scenario / New (Scenario) Game is used,
    00559    *  a company does not exist yet. So create one here.
    00560    * 1 exeption: network-games. Those can have 0 companies
    00561    *   But this exeption is not true for non dedicated network_servers! */
    00562   if (!IsValidCompanyID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated)))
    00563     DoStartupNewCompany(false);
    00564
    00565   /* Fix the cache for cargo payments. */
    00566   CargoPayment *cp;
    00567   FOR_ALL_CARGO_PAYMENTS(cp) {
    00568     cp->front->cargo_payment = cp;
    00569     cp->current_station = cp->front->last_station_visited;
    00570   }
    00571
    00572   if (CheckSavegameVersion(72)) {
    00573     /* Locks/shiplifts in very old savegames had OWNER_WATER as owner */
    00574     for (TileIndex t = 0; t < MapSize(); t++) {
    00575       switch (GetTileType(t)) {
    00576         default: break;
    00577
    00578         case MP_WATER:
    00579           if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
    00580           break;
    00581
    00582         case MP_STATION: {
    00583           if (HasBit(_m[t].m6, 3)) SetBit(_m[t].m6, 2);
    00584           StationGfx gfx = GetStationGfx(t);
    00585           StationType st;
    00586           if (       IsInsideMM(gfx,   0,   8)) { // Railway station
    00587             st = STATION_RAIL;
    00588             SetStationGfx(t, gfx - 0);
    00589           } else if (IsInsideMM(gfx,   8,  67)) { // Airport
    00590             st = STATION_AIRPORT;
    00591             SetStationGfx(t, gfx - 8);
    00592           } else if (IsInsideMM(gfx,  67,  71)) { // Truck
    00593             st = STATION_TRUCK;
    00594             SetStationGfx(t, gfx - 67);
    00595           } else if (IsInsideMM(gfx,  71,  75)) { // Bus
    00596             st = STATION_BUS;
    00597             SetStationGfx(t, gfx - 71);
    00598           } else if (gfx == 75) {                    // Oil rig
    00599             st = STATION_OILRIG;
    00600             SetStationGfx(t, gfx - 75);
    00601           } else if (IsInsideMM(gfx,  76,  82)) { // Dock
    00602             st = STATION_DOCK;
    00603             SetStationGfx(t, gfx - 76);
    00604           } else if (gfx == 82) {                    // Buoy
    00605             st = STATION_BUOY;
    00606             SetStationGfx(t, gfx - 82);
    00607           } else if (IsInsideMM(gfx,  83, 168)) { // Extended airport
    00608             st = STATION_AIRPORT;
    00609             SetStationGfx(t, gfx - 83 + 67 - 8);
    00610           } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
    00611             st = STATION_TRUCK;
    00612             SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
    00613           } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
    00614             st = STATION_BUS;
    00615             SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
    00616           } else {
    00617             /* Restore the signals */
    00618             ResetSignalHandlers();
    00619             return false;
    00620           }
    00621           SB(_m[t].m6, 3, 3, st);
    00622         } break;
    00623       }
    00624     }
    00625   }
    00626
    00627   for (TileIndex t = 0; t < map_size; t++) {
    00628     switch (GetTileType(t)) {
    00629       case MP_STATION: {
    00630         Station *st = GetStationByTile(t);
    00631
    00632         /* Set up station spread; buoys do not have one */
    00633         if (!IsBuoy(t)) st->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
    00634
    00635         switch (GetStationType(t)) {
    00636           case STATION_TRUCK:
    00637           case STATION_BUS:
    00638             if (CheckSavegameVersion(6)) {
    00639               /* From this version on there can be multiple road stops of the
    00640                * same type per station. Convert the existing stops to the new
    00641                * internal data structure. */
    00642               RoadStop *rs = new RoadStop(t);
    00643               if (rs == NULL) error("Too many road stops in savegame");
    00644
    00645               RoadStop **head =
    00646                 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
    00647               *head = rs;
    00648             }
    00649             break;
    00650
    00651           case STATION_OILRIG: {
    00652             /* Very old savegames sometimes have phantom oil rigs, i.e.
    00653              * an oil rig which got shut down, but not completly removed from
    00654              * the map
    00655              */
    00656             TileIndex t1 = TILE_ADDXY(t, 0, 1);
    00657             if (IsTileType(t1, MP_INDUSTRY) &&
    00658                 GetIndustryGfx(t1) == GFX_OILRIG_1) {
    00659               /* The internal encoding of oil rigs was changed twice.
    00660                * It was 3 (till 2.2) and later 5 (till 5.1).
    00661                * Setting it unconditionally does not hurt.
    00662                */
    00663               GetStationByTile(t)->airport_type = AT_OILRIG;
    00664             } else {
    00665               DeleteOilRig(t);
    00666             }
    00667             break;
    00668           }
    00669
    00670           default: break;
    00671         }
    00672         break;
    00673       }
    00674
    00675       default: break;
    00676     }
    00677   }
    00678
    00679   /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
    00680    * This has to be called after the oilrig airport_type update above ^^^ ! */
    00681   if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
    00682
    00683   /* In version 6.1 we put the town index in the map-array. To do this, we need
    00684    *  to use m2 (16bit big), so we need to clean m2, and that is where this is
    00685    *  all about ;) */
    00686   if (CheckSavegameVersionOldStyle(6, 1)) {
    00687     for (TileIndex t = 0; t < map_size; t++) {
    00688       switch (GetTileType(t)) {
    00689         case MP_HOUSE:
    00690           _m[t].m4 = _m[t].m2;
    00691           SetTownIndex(t, CalcClosestTownFromTile(t)->index);
    00692           break;
    00693
    00694         case MP_ROAD:
    00695           _m[t].m4 |= (_m[t].m2 << 4);
    00696           if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
    00697             SetTownIndex(t, CalcClosestTownFromTile(t)->index);
    00698           } else {
    00699             SetTownIndex(t, 0);
    00700           }
    00701           break;
    00702
    00703         default: break;
    00704       }
    00705     }
    00706   }
    00707
    00708   /* Force the freeform edges to false for old savegames. */
    00709   if (CheckSavegameVersion(111)) {
    00710     _settings_game.construction.freeform_edges = false;
    00711   }
    00712
    00713   /* From version 9.0, we update the max passengers of a town (was sometimes negative
    00714    *  before that. */
    00715   if (CheckSavegameVersion(9)) {
    00716     Town *t;
    00717     FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
    00718   }
    00719
    00720   /* From version 16.0, we included autorenew on engines, which are now saved, but
    00721    *  of course, we do need to initialize them for older savegames. */
    00722   if (CheckSavegameVersion(16)) {
    00723     FOR_ALL_COMPANIES(c) {
    00724       c->engine_renew_list   = NULL;
    00725       c->engine_renew        = false;
    00726       c->engine_renew_months = -6;
    00727       c->engine_renew_money  = 100000;
    00728     }
    00729
    00730     /* When loading a game, _local_company is not yet set to the correct value.
    00731      * However, in a dedicated server we are a spectator, so nothing needs to
    00732      * happen. In case we are not a dedicated server, the local company always
    00733      * becomes company 0, unless we are in the scenario editor where all the
    00734      * companies are 'invalid'.
    00735      */
    00736     if (!_network_dedicated && IsValidCompanyID(COMPANY_FIRST)) {
    00737       c = GetCompany(COMPANY_FIRST);
    00738       c->engine_renew        = _settings_client.gui.autorenew;
    00739       c->engine_renew_months = _settings_client.gui.autorenew_months;
    00740       c->engine_renew_money  = _settings_client.gui.autorenew_money;
    00741     }
    00742   }
    00743
    00744   if (CheckSavegameVersion(48)) {
    00745     for (TileIndex t = 0; t < map_size; t++) {
    00746       switch (GetTileType(t)) {
    00747         case MP_RAILWAY:
    00748           if (IsPlainRail(t)) {
    00749             /* Swap ground type and signal type for plain rail tiles, so the
    00750              * ground type uses the same bits as for depots and waypoints. */
    00751             uint tmp = GB(_m[t].m4, 0, 4);
    00752             SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
    00753             SB(_m[t].m2, 0, 4, tmp);
    00754           } else if (HasBit(_m[t].m5, 2)) {
    00755             /* Split waypoint and depot rail type and remove the subtype. */
    00756             ClrBit(_m[t].m5, 2);
    00757             ClrBit(_m[t].m5, 6);
    00758           }
    00759           break;
    00760
    00761         case MP_ROAD:
    00762           /* Swap m3 and m4, so the track type for rail crossings is the
    00763            * same as for normal rail. */
    00764           Swap(_m[t].m3, _m[t].m4);
    00765           break;
    00766
    00767         default: break;
    00768       }
    00769     }
    00770   }
    00771
    00772   if (CheckSavegameVersion(61)) {
    00773     /* Added the RoadType */
    00774     bool old_bridge = CheckSavegameVersion(42);
    00775     for (TileIndex t = 0; t < map_size; t++) {
    00776       switch (GetTileType(t)) {
    00777         case MP_ROAD:
    00778           SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
    00779           switch (GetRoadTileType(t)) {
    00780             default: NOT_REACHED();
    00781             case ROAD_TILE_NORMAL:
    00782               SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
    00783               SB(_m[t].m4, 4, 4, 0);
    00784               SB(_m[t].m6, 2, 4, 0);
    00785               break;
    00786             case ROAD_TILE_CROSSING:
    00787               SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
    00788               break;
    00789             case ROAD_TILE_DEPOT:    break;
    00790           }
    00791           SetRoadTypes(t, ROADTYPES_ROAD);
    00792           break;
    00793
    00794         case MP_STATION:
    00795           if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
    00796           break;
    00797
    00798         case MP_TUNNELBRIDGE:
    00799           /* Middle part of "old" bridges */
    00800           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
    00801           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
    00802             SetRoadTypes(t, ROADTYPES_ROAD);
    00803           }
    00804           break;
    00805
    00806         default: break;
    00807       }
    00808     }
    00809   }
    00810
    00811   if (CheckSavegameVersion(114)) {
    00812     bool fix_roadtypes = !CheckSavegameVersion(61);
    00813     bool old_bridge = CheckSavegameVersion(42);
    00814
    00815     for (TileIndex t = 0; t < map_size; t++) {
    00816       switch (GetTileType(t)) {
    00817         case MP_ROAD:
    00818           if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
    00819           SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
    00820           switch (GetRoadTileType(t)) {
    00821             default: NOT_REACHED();
    00822             case ROAD_TILE_NORMAL:
    00823               SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
    00824               SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3));  // ground
    00825               SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4));  // tram bits
    00826               SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4));  // tram owner
    00827               SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4));  // road bits
    00828               break;
    00829
    00830             case ROAD_TILE_CROSSING:
    00831               SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
    00832               SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3));  // ground
    00833               SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4));  // tram owner
    00834               SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1));  // road axis
    00835               SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1));  // crossing state
    00836               break;
    00837
    00838             case ROAD_TILE_DEPOT:
    00839               break;
    00840           }
    00841           if (!HasTownOwnedRoad(t)) {
    00842             const Town *town = CalcClosestTownFromTile(t);
    00843             if (town != NULL) SetTownIndex(t, town->index);
    00844           }
    00845           _m[t].m4 = 0;
    00846           break;
    00847
    00848         case MP_STATION:
    00849           if (!IsRoadStop(t)) break;
    00850
    00851           if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
    00852           SB(_me[t].m7, 0, 5, HasBit(_m[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
    00853           SB(_m[t].m3, 4, 4, _m[t].m1);
    00854           _m[t].m4 = 0;
    00855           break;
    00856
    00857         case MP_TUNNELBRIDGE:
    00858           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
    00859           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
    00860             if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
    00861
    00862             Owner o = GetTileOwner(t);
    00863             SB(_me[t].m7, 0, 5, o); // road owner
    00864             SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
    00865           }
    00866           SB(_m[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
    00867           SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
    00868
    00869           _m[t].m2 = 0;
    00870           _m[t].m4 = 0;
    00871           break;
    00872
    00873         default: break;
    00874       }
    00875     }
    00876   }
    00877
    00878   if (CheckSavegameVersion(42)) {
    00879     Vehicle *v;
    00880
    00881     for (TileIndex t = 0; t < map_size; t++) {
    00882       if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
    00883       if (IsBridgeTile(t)) {
    00884         if (HasBit(_m[t].m5, 6)) { // middle part
    00885           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
    00886
    00887           if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
    00888             if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
    00889               MakeRailNormal(
    00890                 t,
    00891                 GetTileOwner(t),
    00892                 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
    00893                 GetRailType(t)
    00894               );
    00895             } else {
    00896               TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
    00897
    00898               MakeRoadNormal(
    00899                 t,
    00900                 axis == AXIS_X ? ROAD_Y : ROAD_X,
    00901                 ROADTYPES_ROAD,
    00902                 town,
    00903                 GetTileOwner(t), OWNER_NONE
    00904               );
    00905             }
    00906           } else {
    00907             if (GB(_m[t].m5, 3, 2) == 0) {
    00908               MakeClear(t, CLEAR_GRASS, 3);
    00909             } else {
    00910               if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
    00911                 MakeShore(t);
    00912               } else {
    00913                 if (GetTileOwner(t) == OWNER_WATER) {
    00914                   MakeWater(t);
    00915                 } else {
    00916                   MakeCanal(t, GetTileOwner(t), Random());
    00917                 }
    00918               }
    00919             }
    00920           }
    00921           SetBridgeMiddle(t, axis);
    00922         } else { // ramp
    00923           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
    00924           uint north_south = GB(_m[t].m5, 5, 1);
    00925           DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
    00926           TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
    00927
    00928           _m[t].m5 = 1 << 7 | type << 2 | dir;
    00929         }
    00930       }
    00931     }
    00932
    00933     FOR_ALL_VEHICLES(v) {
    00934       if (v->type != VEH_TRAIN && v->type != VEH_ROAD) continue;
    00935       if (IsBridgeTile(v->tile)) {
    00936         DiagDirection dir = GetTunnelBridgeDirection(v->tile);
    00937
    00938         if (dir != DirToDiagDir(v->direction)) continue;
    00939         switch (dir) {
    00940           default: NOT_REACHED();
    00941           case DIAGDIR_NE: if ((v->x_pos & 0xF) !=  0)            continue; break;
    00942           case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
    00943           case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
    00944           case DIAGDIR_NW: if ((v->y_pos & 0xF) !=  0)            continue; break;
    00945         }
    00946       } else if (v->z_pos > GetSlopeZ(v->x_pos, v->y_pos)) {
    00947         v->tile = GetNorthernBridgeEnd(v->tile);
    00948       } else {
    00949         continue;
    00950       }
    00951       if (v->type == VEH_TRAIN) {
    00952         v->u.rail.track = TRACK_BIT_WORMHOLE;
    00953       } else {
    00954         v->u.road.state = RVSB_WORMHOLE;
    00955       }
    00956     }
    00957   }
    00958
    00959   /* Elrails got added in rev 24 */
    00960   if (CheckSavegameVersion(24)) {
    00961     Vehicle *v;
    00962     RailType min_rail = RAILTYPE_ELECTRIC;
    00963
    00964     FOR_ALL_VEHICLES(v) {
    00965       if (v->type == VEH_TRAIN) {
    00966         RailType rt = RailVehInfo(v->engine_type)->railtype;
    00967
    00968         v->u.rail.railtype = rt;
    00969         if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
    00970       }
    00971     }
    00972
    00973     /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
    00974     for (TileIndex t = 0; t < map_size; t++) {
    00975       switch (GetTileType(t)) {
    00976         case MP_RAILWAY:
    00977           SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    00978           break;
    00979
    00980         case MP_ROAD:
    00981           if (IsLevelCrossing(t)) {
    00982             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    00983           }
    00984           break;
    00985
    00986         case MP_STATION:
    00987           if (IsRailwayStation(t)) {
    00988             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    00989           }
    00990           break;
    00991
    00992         case MP_TUNNELBRIDGE:
    00993           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
    00994             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    00995           }
    00996           break;
    00997
    00998         default:
    00999           break;
    01000       }
    01001     }
    01002
    01003     FOR_ALL_VEHICLES(v) {
    01004       if (v->type == VEH_TRAIN && (IsFrontEngine(v) || IsFreeWagon(v))) TrainConsistChanged(v, true);
    01005     }
    01006
    01007   }
    01008
    01009   /* In version 16.1 of the savegame a company can decide if trains, which get
    01010    * replaced, shall keep their old length. In all prior versions, just default
    01011    * to false */
    01012   if (CheckSavegameVersionOldStyle(16, 1)) {
    01013     FOR_ALL_COMPANIES(c) c->renew_keep_length = false;
    01014   }
    01015
    01016   /* In version 17, ground type is moved from m2 to m4 for depots and
    01017    * waypoints to make way for storing the index in m2. The custom graphics
    01018    * id which was stored in m4 is now saved as a grf/id reference in the
    01019    * waypoint struct. */
    01020   if (CheckSavegameVersion(17)) {
    01021     Waypoint *wp;
    01022
    01023     FOR_ALL_WAYPOINTS(wp) {
    01024       if (wp->deleted == 0) {
    01025         const StationSpec *statspec = NULL;
    01026
    01027         if (HasBit(_m[wp->xy].m3, 4))
    01028           statspec = GetCustomStationSpec(STAT_CLASS_WAYP, _m[wp->xy].m4 + 1);
    01029
    01030         if (statspec != NULL) {
    01031           wp->stat_id = _m[wp->xy].m4 + 1;
    01032           wp->grfid = statspec->grffile->grfid;
    01033           wp->localidx = statspec->localidx;
    01034         } else {
    01035           /* No custom graphics set, so set to default. */
    01036           wp->stat_id = 0;
    01037           wp->grfid = 0;
    01038           wp->localidx = 0;
    01039         }
    01040
    01041         /* Move ground type bits from m2 to m4. */
    01042         _m[wp->xy].m4 = GB(_m[wp->xy].m2, 0, 4);
    01043         /* Store waypoint index in the tile. */
    01044         _m[wp->xy].m2 = wp->index;
    01045       }
    01046     }
    01047   } else {
    01048     /* As of version 17, we recalculate the custom graphic ID of waypoints
    01049      * from the GRF ID / station index. */
    01050     AfterLoadWaypoints();
    01051   }
    01052
    01053   /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
    01054    *  room for PBS. Now in version 21 move it back :P. */
    01055   if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
    01056     for (TileIndex t = 0; t < map_size; t++) {
    01057       switch (GetTileType(t)) {
    01058         case MP_RAILWAY:
    01059           if (HasSignals(t)) {
    01060             /* convert PBS signals to combo-signals */
    01061             if (HasBit(_m[t].m2, 2)) SetSignalType(t, TRACK_X, SIGTYPE_COMBO);
    01062
    01063             /* move the signal variant back */
    01064             SetSignalVariant(t, TRACK_X, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
    01065             ClrBit(_m[t].m2, 3);
    01066           }
    01067
    01068           /* Clear PBS reservation on track */
    01069           if (!IsRailDepotTile(t)) {
    01070             SB(_m[t].m4, 4, 4, 0);
    01071           } else {
    01072             ClrBit(_m[t].m3, 6);
    01073           }
    01074           break;
    01075
    01076         case MP_STATION: // Clear PBS reservation on station
    01077           ClrBit(_m[t].m3, 6);
    01078           break;
    01079
    01080         default: break;
    01081       }
    01082     }
    01083   }
    01084
    01085   if (CheckSavegameVersion(25)) {
    01086     Vehicle *v;
    01087     FOR_ALL_VEHICLES(v) {
    01088       if (v->type == VEH_ROAD) {
    01089         v->vehstatus &= ~0x40;
    01090         v->u.road.slot = NULL;
    01091         v->u.road.slot_age = 0;
    01092       }
    01093     }
    01094   } else {
    01095     Vehicle *v;
    01096     FOR_ALL_VEHICLES(v) {
    01097       if (v->type == VEH_ROAD && v->u.road.slot != NULL) v->u.road.slot->num_vehicles++;
    01098     }
    01099   }
    01100
    01101   if (CheckSavegameVersion(26)) {
    01102     Station *st;
    01103     FOR_ALL_STATIONS(st) {
    01104       st->last_vehicle_type = VEH_INVALID;
    01105     }
    01106   }
    01107
    01108   YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
    01109
    01110   if (CheckSavegameVersion(34)) FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
    01111
    01112   FOR_ALL_COMPANIES(c) {
    01113     c->avail_railtypes = GetCompanyRailtypes(c->index);
    01114     c->avail_roadtypes = GetCompanyRoadtypes(c->index);
    01115   }
    01116
    01117   if (!CheckSavegameVersion(27)) AfterLoadStations();
    01118
    01119   /* Time starts at 0 instead of 1920.
    01120    * Account for this in older games by adding an offset */
    01121   if (CheckSavegameVersion(31)) {
    01122     Station *st;
    01123     Waypoint *wp;
    01124     Engine *e;
    01125     Industry *i;
    01126     Vehicle *v;
    01127
    01128     _date += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01129     _cur_year += ORIGINAL_BASE_YEAR;
    01130
    01131     FOR_ALL_STATIONS(st)  st->build_date      += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01132     FOR_ALL_WAYPOINTS(wp) wp->build_date      += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01133     FOR_ALL_ENGINES(e)    e->intro_date       += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01134     FOR_ALL_COMPANIES(c)  c->inaugurated_year += ORIGINAL_BASE_YEAR;
    01135     FOR_ALL_INDUSTRIES(i) i->last_prod_year   += ORIGINAL_BASE_YEAR;
    01136
    01137     FOR_ALL_VEHICLES(v) {
    01138       v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01139       v->build_year += ORIGINAL_BASE_YEAR;
    01140     }
    01141   }
    01142
    01143   /* From 32 on we save the industry who made the farmland.
    01144    *  To give this prettyness to old savegames, we remove all farmfields and
    01145    *  plant new ones. */
    01146   if (CheckSavegameVersion(32)) {
    01147     Industry *i;
    01148
    01149     for (TileIndex t = 0; t < map_size; t++) {
    01150       if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
    01151         /* remove fields */
    01152         MakeClear(t, CLEAR_GRASS, 3);
    01153       } else if (IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES)) {
    01154         /* remove fences around fields */
    01155         SetFenceSE(t, 0);
    01156         SetFenceSW(t, 0);
    01157       }
    01158     }
    01159
    01160     FOR_ALL_INDUSTRIES(i) {
    01161       uint j;
    01162
    01163       if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
    01164         for (j = 0; j != 50; j++) PlantRandomFarmField(i);
    01165       }
    01166     }
    01167   }
    01168
    01169   /* Setting no refit flags to all orders in savegames from before refit in orders were added */
    01170   if (CheckSavegameVersion(36)) {
    01171     Order *order;
    01172     Vehicle *v;
    01173
    01174     FOR_ALL_ORDERS(order) {
    01175       order->SetRefit(CT_NO_REFIT);
    01176     }
    01177
    01178     FOR_ALL_VEHICLES(v) {
    01179       v->current_order.SetRefit(CT_NO_REFIT);
    01180     }
    01181   }
    01182
    01183   /* from version 38 we have optional elrails, since we cannot know the
    01184    * preference of a user, let elrails enabled; it can be disabled manually */
    01185   if (CheckSavegameVersion(38)) _settings_game.vehicle.disable_elrails = false;
    01186   /* do the same as when elrails were enabled/disabled manually just now */
    01187   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
    01188   InitializeRailGUI();
    01189
    01190   /* From version 53, the map array was changed for house tiles to allow
    01191    * space for newhouses grf features. A new byte, m7, was also added. */
    01192   if (CheckSavegameVersion(53)) {
    01193     for (TileIndex t = 0; t < map_size; t++) {
    01194       if (IsTileType(t, MP_HOUSE)) {
    01195         if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
    01196           /* Move the construction stage from m3[7..6] to m5[5..4].
    01197            * The construction counter does not have to move. */
    01198           SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
    01199           SB(_m[t].m3, 6, 2, 0);
    01200
    01201           /* The "house is completed" bit is now in m6[2]. */
    01202           SetHouseCompleted(t, false);
    01203         } else {
    01204           /* The "lift has destination" bit has been moved from
    01205            * m5[7] to m7[0]. */
    01206           SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
    01207           ClrBit(_m[t].m5, 7);
    01208
    01209           /* The "lift is moving" bit has been removed, as it does
    01210            * the same job as the "lift has destination" bit. */
    01211           ClrBit(_m[t].m1, 7);
    01212
    01213           /* The position of the lift goes from m1[7..0] to m6[7..2],
    01214            * making m1 totally free, now. The lift position does not
    01215            * have to be a full byte since the maximum value is 36. */
    01216           SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
    01217
    01218           _m[t].m1 = 0;
    01219           _m[t].m3 = 0;
    01220           SetHouseCompleted(t, true);
    01221         }
    01222       }
    01223     }
    01224   }
    01225
    01226   /* Check and update house and town values */
    01227   UpdateHousesAndTowns();
    01228
    01229   if (CheckSavegameVersion(43)) {
    01230     for (TileIndex t = 0; t < map_size; t++) {
    01231       if (IsTileType(t, MP_INDUSTRY)) {
    01232         switch (GetIndustryGfx(t)) {
    01233           case GFX_POWERPLANT_SPARKS:
    01234             SetIndustryAnimationState(t, GB(_m[t].m1, 2, 5));
    01235             break;
    01236
    01237           case GFX_OILWELL_ANIMATED_1:
    01238           case GFX_OILWELL_ANIMATED_2:
    01239           case GFX_OILWELL_ANIMATED_3:
    01240             SetIndustryAnimationState(t, GB(_m[t].m1, 0, 2));
    01241             break;
    01242
    01243           case GFX_COAL_MINE_TOWER_ANIMATED:
    01244           case GFX_COPPER_MINE_TOWER_ANIMATED:
    01245           case GFX_GOLD_MINE_TOWER_ANIMATED:
    01246              SetIndustryAnimationState(t, _m[t].m1);
    01247              break;
    01248
    01249           default: // No animation states to change
    01250             break;
    01251         }
    01252       }
    01253     }
    01254   }
    01255
    01256   if (CheckSavegameVersion(44)) {
    01257     Vehicle *v;
    01258     /* If we remove a station while cargo from it is still enroute, payment calculation will assume
    01259      * 0, 0 to be the source of the cargo, resulting in very high payments usually. v->source_xy
    01260      * stores the coordinates, preserving them even if the station is removed. However, if a game is loaded
    01261      * where this situation exists, the cargo-source information is lost. in this case, we set the source
    01262      * to the current tile of the vehicle to prevent excessive profits
    01263      */
    01264     FOR_ALL_VEHICLES(v) {
    01265       const CargoList::List *packets = v->cargo.Packets();
    01266       for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
    01267         CargoPacket *cp = *it;
    01268         cp->source_xy = IsValidStationID(cp->source) ? GetStation(cp->source)->xy : v->tile;
    01269         cp->loaded_at_xy = cp->source_xy;
    01270       }
    01271       v->cargo.InvalidateCache();
    01272     }
    01273
    01274     /* Store position of the station where the goods come from, so there
    01275      * are no very high payments when stations get removed. However, if the
    01276      * station where the goods came from is already removed, the source
    01277      * information is lost. In that case we set it to the position of this
    01278      * station */
    01279     Station *st;
    01280     FOR_ALL_STATIONS(st) {
    01281       for (CargoID c = 0; c < NUM_CARGO; c++) {
    01282         GoodsEntry *ge = &st->goods[c];
    01283
    01284         const CargoList::List *packets = ge->cargo.Packets();
    01285         for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
    01286           CargoPacket *cp = *it;
    01287           cp->source_xy = IsValidStationID(cp->source) ? GetStation(cp->source)->xy : st->xy;
    01288           cp->loaded_at_xy = cp->source_xy;
    01289         }
    01290       }
    01291     }
    01292   }
    01293
    01294   if (CheckSavegameVersion(45)) {
    01295     Vehicle *v;
    01296     /* Originally just the fact that some cargo had been paid for was
    01297      * stored to stop people cheating and cashing in several times. This
    01298      * wasn't enough though as it was cleared when the vehicle started
    01299      * loading again, even if it didn't actually load anything, so now the
    01300      * amount that has been paid is stored. */
    01301     FOR_ALL_VEHICLES(v) {
    01302       ClrBit(v->vehicle_flags, 2);
    01303       v->cargo.InvalidateCache();
    01304     }
    01305   }
    01306
    01307   /* Buoys do now store the owner of the previous water tile, which can never
    01308    * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
    01309   if (CheckSavegameVersion(46)) {
    01310     Station *st;
    01311     FOR_ALL_STATIONS(st) {
    01312       if (st->IsBuoy() && IsTileOwner(st->xy, OWNER_NONE) && TileHeight(st->xy) == 0) SetTileOwner(st->xy, OWNER_WATER);
    01313     }
    01314   }
    01315
    01316   if (CheckSavegameVersion(50)) {
    01317     Vehicle *v;
    01318     /* Aircraft units changed from 8 mph to 1 km/h */
    01319     FOR_ALL_VEHICLES(v) {
    01320       if (v->type == VEH_AIRCRAFT && v->subtype <= AIR_AIRCRAFT) {
    01321         const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
    01322         v->cur_speed *= 129;
    01323         v->cur_speed /= 10;
    01324         v->max_speed = avi->max_speed;
    01325         v->acceleration = avi->acceleration;
    01326       }
    01327     }
    01328   }
    01329
    01330   if (CheckSavegameVersion(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
    01331
    01332   if (CheckSavegameVersion(52)) {
    01333     for (TileIndex t = 0; t < map_size; t++) {
    01334       if (IsStatueTile(t)) {
    01335         _m[t].m2 = CalcClosestTownFromTile(t)->index;
    01336       }
    01337     }
    01338   }
    01339
    01340   /* A setting containing the proportion of towns that grow twice as
    01341    * fast was added in version 54. From version 56 this is now saved in the
    01342    * town as cities can be built specifically in the scenario editor. */
    01343   if (CheckSavegameVersion(56)) {
    01344     Town *t;
    01345
    01346     FOR_ALL_TOWNS(t) {
    01347       if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
    01348         t->larger_town = true;
    01349       }
    01350     }
    01351   }
    01352
    01353   if (CheckSavegameVersion(57)) {
    01354     Vehicle *v;
    01355     /* Added a FIFO queue of vehicles loading at stations */
    01356     FOR_ALL_VEHICLES(v) {
    01357       if ((v->type != VEH_TRAIN || IsFrontEngine(v)) &&  // for all locs
    01358           !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
    01359           v->current_order.IsType(OT_LOADING)) {         // loading
    01360         GetStation(v->last_station_visited)->loading_vehicles.push_back(v);
    01361
    01362         /* The loading finished flag is *only* set when actually completely
    01363          * finished. Because the vehicle is loading, it is not finished. */
    01364         ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
    01365       }
    01366     }
    01367   } else if (CheckSavegameVersion(59)) {
    01368     /* For some reason non-loading vehicles could be in the station's loading vehicle list */
    01369
    01370     Station *st;
    01371     FOR_ALL_STATIONS(st) {
    01372       std::list<Vehicle *>::iterator iter;
    01373       for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
    01374         Vehicle *v = *iter;
    01375         iter++;
    01376         if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
    01377       }
    01378     }
    01379   }
    01380
    01381   if (CheckSavegameVersion(58)) {
    01382     /* Setting difficulty number_industries other than zero get bumped to +1
    01383      * since a new option (very low at position1) has been added */
    01384     if (_settings_game.difficulty.number_industries > 0) {
    01385       _settings_game.difficulty.number_industries++;
    01386     }
    01387
    01388     /* Same goes for number of towns, although no test is needed, just an increment */
    01389     _settings_game.difficulty.number_towns++;
    01390   }
    01391
    01392   if (CheckSavegameVersion(64)) {
    01393     /* copy the signal type/variant and move signal states bits */
    01394     for (TileIndex t = 0; t < map_size; t++) {
    01395       if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
    01396         SetSignalStates(t, GB(_m[t].m2, 4, 4));
    01397         SetSignalVariant(t, INVALID_TRACK, GetSignalVariant(t, TRACK_X));
    01398         SetSignalType(t, INVALID_TRACK, GetSignalType(t, TRACK_X));
    01399         ClrBit(_m[t].m2, 7);
    01400       }
    01401     }
    01402   }
    01403
    01404   if (CheckSavegameVersion(69)) {
    01405     /* In some old savegames a bit was cleared when it should not be cleared */
    01406     Vehicle *v;
    01407     FOR_ALL_VEHICLES(v) {
    01408       if (v->type == VEH_ROAD && (v->u.road.state == 250 || v->u.road.state == 251)) {
    01409         SetBit(v->u.road.state, RVS_IS_STOPPING);
    01410       }
    01411     }
    01412   }
    01413
    01414   if (CheckSavegameVersion(70)) {
    01415     /* Added variables to support newindustries */
    01416     Industry *i;
    01417     FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
    01418   }
    01419
    01420   /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
    01421       Replace the owner for those by OWNER_NONE. */
    01422   if (CheckSavegameVersion(82)) {
    01423     for (TileIndex t = 0; t < map_size; t++) {
    01424       if (IsTileType(t, MP_WATER) &&
    01425           GetWaterTileType(t) == WATER_TILE_CLEAR &&
    01426           GetTileOwner(t) == OWNER_WATER &&
    01427           TileHeight(t) != 0) {
    01428         SetTileOwner(t, OWNER_NONE);
    01429       }
    01430     }
    01431   }
    01432
    01433   /*
    01434    * Add the 'previous' owner to the ship depots so we can reset it with
    01435    * the correct values when it gets destroyed. This prevents that
    01436    * someone can remove canals owned by somebody else and it prevents
    01437    * making floods using the removal of ship depots.
    01438    */
    01439   if (CheckSavegameVersion(83)) {
    01440     for (TileIndex t = 0; t < map_size; t++) {
    01441       if (IsTileType(t, MP_WATER) && IsShipDepot(t)) {
    01442         _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
    01443       }
    01444     }
    01445   }
    01446
    01447   if (CheckSavegameVersion(74)) {
    01448     Station *st;
    01449     FOR_ALL_STATIONS(st) {
    01450       for (CargoID c = 0; c < NUM_CARGO; c++) {
    01451         st->goods[c].last_speed = 0;
    01452         if (st->goods[c].cargo.Count() != 0) SetBit(st->goods[c].acceptance_pickup, GoodsEntry::PICKUP);
    01453       }
    01454     }
    01455   }
    01456
    01457   if (CheckSavegameVersion(78)) {
    01458     Industry *i;
    01459     uint j;
    01460     FOR_ALL_INDUSTRIES(i) {
    01461       const IndustrySpec *indsp = GetIndustrySpec(i->type);
    01462       for (j = 0; j < lengthof(i->produced_cargo); j++) {
    01463         i->produced_cargo[j] = indsp->produced_cargo[j];
    01464       }
    01465       for (j = 0; j < lengthof(i->accepts_cargo); j++) {
    01466         i->accepts_cargo[j] = indsp->accepts_cargo[j];
    01467       }
    01468     }
    01469   }
    01470
    01471   /* Before version 81, the density of grass was always stored as zero, and
    01472    * grassy trees were always drawn fully grassy. Furthermore, trees on rough
    01473    * land used to have zero density, now they have full density. Therefore,
    01474    * make all grassy/rough land trees have a density of 3. */
    01475   if (CheckSavegameVersion(81)) {
    01476     for (TileIndex t = 0; t < map_size; t++) {
    01477       if (GetTileType(t) == MP_TREES) {
    01478         TreeGround groundType = GetTreeGround(t);
    01479         if (groundType != TREE_GROUND_SNOW_DESERT) SetTreeGroundDensity(t, groundType, 3);
    01480       }
    01481     }
    01482   }
    01483
    01484
    01485   if (CheckSavegameVersion(93)) {
    01486     /* Rework of orders. */
    01487     Order *order;
    01488     FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
    01489
    01490     Vehicle *v;
    01491     FOR_ALL_VEHICLES(v) {
    01492       if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && !v->orders.list->GetFirstOrder()->IsValid()) {
    01493         v->orders.list->FreeChain();
    01494         v->orders.list = NULL;
    01495       }
    01496
    01497       v->current_order.ConvertFromOldSavegame();
    01498       if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
    01499         FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
    01500       }
    01501     }
    01502   } else if (CheckSavegameVersion(94)) {
    01503     /* Unload and transfer are now mutual exclusive. */
    01504     Order *order;
    01505     FOR_ALL_ORDERS(order) {
    01506       if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
    01507         order->SetUnloadType(OUFB_TRANSFER);
    01508         order->SetLoadType(OLFB_NO_LOAD);
    01509       }
    01510     }
    01511
    01512     Vehicle *v;
    01513     FOR_ALL_VEHICLES(v) {
    01514       if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
    01515         v->current_order.SetUnloadType(OUFB_TRANSFER);
    01516         v->current_order.SetLoadType(OLFB_NO_LOAD);
    01517       }
    01518     }
    01519   }
    01520
    01521   if (CheckSavegameVersion(84)) {
    01522     /* Update go to buoy orders because they are just waypoints */
    01523     Order *order;
    01524     FOR_ALL_ORDERS(order) {
    01525       if (order->IsType(OT_GOTO_STATION) && GetStation(order->GetDestination())->IsBuoy()) {
    01526         order->SetLoadType(OLF_LOAD_IF_POSSIBLE);
    01527         order->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE);
    01528       }
    01529     }
    01530
    01531     /* Set all share owners to INVALID_COMPANY for
    01532      * 1) all inactive companies
    01533      *     (when inactive companies were stored in the savegame - TTD, TTDP and some
    01534      *      *really* old revisions of OTTD; else it is already set in InitializeCompanies())
    01535      * 2) shares that are owned by inactive companies or self
    01536      *     (caused by cheating clients in earlier revisions) */
    01537     FOR_ALL_COMPANIES(c) {
    01538       for (uint i = 0; i < 4; i++) {
    01539         CompanyID company = c->share_owners[i];
    01540         if (company == INVALID_COMPANY) continue;
    01541         if (!IsValidCompanyID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
    01542       }
    01543     }
    01544   }
    01545
    01546   if (CheckSavegameVersion(86)) {
    01547     for (TileIndex t = 0; t < map_size; t++) {
    01548       /* Move river flag and update canals to use water class */
    01549       if (IsTileType(t, MP_WATER)) {
    01550         if (GetWaterClass(t) != WATER_CLASS_RIVER) {
    01551           if (IsWater(t)) {
    01552             Owner o = GetTileOwner(t);
    01553             if (o == OWNER_WATER) {
    01554               MakeWater(t);
    01555             } else {
    01556               MakeCanal(t, o, Random());
    01557             }
    01558           } else if (IsShipDepot(t)) {
    01559             Owner o = (Owner)_m[t].m4; // Original water owner
    01560             SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
    01561           }
    01562         }
    01563       }
    01564     }
    01565
    01566     /* Update locks, depots, docks and buoys to have a water class based
    01567      * on its neighbouring tiles. Done after river and canal updates to
    01568      * ensure neighbours are correct. */
    01569     for (TileIndex t = 0; t < map_size; t++) {
    01570       if (GetTileSlope(t, NULL) != SLOPE_FLAT) continue;
    01571
    01572       if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
    01573       if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
    01574     }
    01575   }
    01576
    01577   if (CheckSavegameVersion(87)) {
    01578     for (TileIndex t = 0; t < map_size; t++) {
    01579       /* skip oil rigs at borders! */
    01580       if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
    01581           (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
    01582         /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
    01583          * This conversion has to be done before buoys with invalid owner are removed. */
    01584         SetWaterClass(t, WATER_CLASS_SEA);
    01585       }
    01586
    01587       if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
    01588         Owner o = GetTileOwner(t);
    01589         if (o < MAX_COMPANIES && !IsValidCompanyID(o)) {
    01590           _current_company = o;
    01591           ChangeTileOwner(t, o, INVALID_OWNER);
    01592         }
    01593         if (IsBuoyTile(t)) {
    01594           /* reset buoy owner to OWNER_NONE in the station struct
    01595            * (even if it is owned by active company) */
    01596           GetStationByTile(t)->owner = OWNER_NONE;
    01597         }
    01598       } else if (IsTileType(t, MP_ROAD)) {
    01599         /* works for all RoadTileType */
    01600         for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
    01601           /* update even non-existing road types to update tile owner too */
    01602           Owner o = GetRoadOwner(t, rt);
    01603           if (o < MAX_COMPANIES && !IsValidCompanyID(o)) SetRoadOwner(t, rt, OWNER_NONE);
    01604         }
    01605         if (IsLevelCrossing(t)) {
    01606           if (!IsValidCompanyID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
    01607         }
    01608       } else if (IsPlainRailTile(t)) {
    01609         if (!IsValidCompanyID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
    01610       }
    01611     }
    01612
    01613     /* Convert old PF settings to new */
    01614     if (_settings_game.pf.yapf.rail_use_yapf || CheckSavegameVersion(28)) {
    01615       _settings_game.pf.pathfinder_for_trains = VPF_YAPF;
    01616     } else {
    01617       _settings_game.pf.pathfinder_for_trains = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_NTP);
    01618     }
    01619
    01620     if (_settings_game.pf.yapf.road_use_yapf || CheckSavegameVersion(28)) {
    01621       _settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
    01622     } else {
    01623       _settings_game.pf.pathfinder_for_roadvehs = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
    01624     }
    01625
    01626     if (_settings_game.pf.yapf.ship_use_yapf) {
    01627       _settings_game.pf.pathfinder_for_ships = VPF_YAPF;
    01628     } else {
    01629       _settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
    01630     }
    01631   }
    01632
    01633   if (CheckSavegameVersion(88)) {
    01634     /* Profits are now with 8 bit fract */
    01635     Vehicle *v;
    01636     FOR_ALL_VEHICLES(v) {
    01637       v->profit_this_year <<= 8;
    01638       v->profit_last_year <<= 8;
    01639       v->running_ticks = 0;
    01640     }
    01641   }
    01642
    01643   if (CheckSavegameVersion(91)) {
    01644     /* Increase HouseAnimationFrame from 5 to 7 bits */
    01645     for (TileIndex t = 0; t < map_size; t++) {
    01646       if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
    01647         SetHouseAnimationFrame(t, GB(_m[t].m6, 3, 5));
    01648       }
    01649     }
    01650   }
    01651
    01652   if (CheckSavegameVersion(62)) {
    01653     /* Remove all trams from savegames without tram support.
    01654      * There would be trams without tram track under causing crashes sooner or later. */
    01655     Vehicle *v;
    01656     FOR_ALL_VEHICLES(v) {
    01657       if (v->type == VEH_ROAD && v->First() == v &&
    01658           HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
    01659         if (_switch_mode_errorstr == INVALID_STRING_ID || _switch_mode_errorstr == STR_NEWGRF_COMPATIBLE_LOAD_WARNING) {
    01660           _switch_mode_errorstr = STR_LOADGAME_REMOVED_TRAMS;
    01661         }
    01662         delete v;
    01663       }
    01664     }
    01665   }
    01666
    01667   if (CheckSavegameVersion(99)) {
    01668     for (TileIndex t = 0; t < map_size; t++) {
    01669       /* Set newly introduced WaterClass of industry tiles */
    01670       if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
    01671         SetWaterClassDependingOnSurroundings(t, true);
    01672       }
    01673       if (IsTileType(t, MP_INDUSTRY)) {
    01674         if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
    01675           SetWaterClassDependingOnSurroundings(t, true);
    01676         } else {
    01677           SetWaterClass(t, WATER_CLASS_INVALID);
    01678         }
    01679       }
    01680
    01681       /* Replace "house construction year" with "house age" */
    01682       if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
    01683         _m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
    01684       }
    01685     }
    01686   }
    01687
    01688   /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
    01689    * format here, as an old layout wouldn't work properly anyway. To be safe, we
    01690    * clear any possible PBS reservations as well. */
    01691   if (CheckSavegameVersion(100)) {
    01692     for (TileIndex t = 0; t < map_size; t++) {
    01693       switch (GetTileType(t)) {
    01694         case MP_RAILWAY:
    01695           if (HasSignals(t)) {
    01696             /* move the signal variant */
    01697             SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
    01698             SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
    01699             ClrBit(_m[t].m2, 2);
    01700             ClrBit(_m[t].m2, 6);
    01701           }
    01702
    01703           /* Clear PBS reservation on track */
    01704           if (IsRailDepot(t) ||IsRailWaypoint(t)) {
    01705             SetDepotWaypointReservation(t, false);
    01706           } else {
    01707             SetTrackReservation(t, TRACK_BIT_NONE);
    01708           }
    01709           break;
    01710
    01711         case MP_ROAD: // Clear PBS reservation on crossing
    01712           if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
    01713           break;
    01714
    01715         case MP_STATION: // Clear PBS reservation on station
    01716           if (IsRailwayStation(t)) SetRailwayStationReservation(t, false);
    01717           break;
    01718
    01719         case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/birdges
    01720           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
    01721           break;
    01722
    01723         default: break;
    01724       }
    01725     }
    01726   }
    01727
    01728   /* Reserve all tracks trains are currently on. */
    01729   if (CheckSavegameVersion(101)) {
    01730     Vehicle *v;
    01731     FOR_ALL_VEHICLES(v) {
    01732       if (v->type == VEH_TRAIN) {
    01733         if ((v->u.rail.track & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
    01734           TryReserveRailTrack(v->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(v->tile)));
    01735         } else if ((v->u.rail.track & TRACK_BIT_MASK) != TRACK_BIT_NONE) {
    01736           TryReserveRailTrack(v->tile, TrackBitsToTrack(v->u.rail.track));
    01737         }
    01738       }
    01739     }
    01740   }
    01741
    01742   if (CheckSavegameVersion(102)) {
    01743     for (TileIndex t = 0; t < map_size; t++) {
    01744       /* Now all crossings should be in correct state */
    01745       if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
    01746     }
    01747   }
    01748
    01749   if (CheckSavegameVersion(103)) {
    01750     /* Non-town-owned roads now store the closest town */
    01751     UpdateNearestTownForRoadTiles(false);
    01752
    01753     /* signs with invalid owner left from older savegames */
    01754     Sign *si;
    01755     FOR_ALL_SIGNS(si) {
    01756       if (si->owner != OWNER_NONE && !IsValidCompanyID(si->owner)) si->owner = OWNER_NONE;
    01757     }
    01758
    01759     /* Station can get named based on an industry type, but the current ones
    01760      * are not, so mark them as if they are not named by an industry. */
    01761     Station *st;
    01762     FOR_ALL_STATIONS(st) {
    01763       st->indtype = IT_INVALID;
    01764     }
    01765   }
    01766
    01767   if (CheckSavegameVersion(104)) {
    01768     Vehicle *v;
    01769     FOR_ALL_VEHICLES(v) {
    01770       /* Set engine_type of shadow and rotor */
    01771       if (v->type == VEH_AIRCRAFT && !IsNormalAircraft(v)) {
    01772         v->engine_type = v->First()->engine_type;
    01773       }
    01774     }
    01775
    01776     /* More companies ... */
    01777     Company *c;
    01778     FOR_ALL_COMPANIES(c) {
    01779       if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
    01780     }
    01781
    01782     Engine *e;
    01783     FOR_ALL_ENGINES(e) {
    01784       if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
    01785     }
    01786
    01787     Town *t;
    01788     FOR_ALL_TOWNS(t) {
    01789       if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
    01790       for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
    01791     }
    01792   }
    01793
    01794   if (CheckSavegameVersion(112)) {
    01795     for (TileIndex t = 0; t < map_size; t++) {
    01796       /* Check for HQ bit being set, instead of using map accessor,
    01797        * since we've already changed it code-wise */
    01798       if (IsTileType(t, MP_UNMOVABLE) && HasBit(_m[t].m5, 7)) {
    01799         /* Move size and part identification of HQ out of the m5 attribute,
    01800          * on new locations */
    01801         uint8 old_m5 = _m[t].m5;
    01802         _m[t].m5 = UNMOVABLE_HQ;
    01803         SetCompanyHQSize(t, GB(old_m5, 2, 3));
    01804         SetCompanyHQSection(t, GB(old_m5, 0, 2));
    01805       }
    01806     }
    01807   }
    01808
    01809   if (CheckSavegameVersion(113)) {
    01810     /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
    01811     if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
    01812       _settings_game.economy.allow_town_roads = false;
    01813       _settings_game.economy.town_layout = TL_BETTER_ROADS;
    01814     } else {
    01815       _settings_game.economy.allow_town_roads = true;
    01816       _settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
    01817     }
    01818
    01819     /* Initialize layout of all towns. Older versions were using different
    01820      * generator for random town layout, use it if needed. */
    01821     Town *t;
    01822     FOR_ALL_TOWNS(t) {
    01823       if (_settings_game.economy.town_layout != TL_RANDOM) {
    01824         t->layout = _settings_game.economy.town_layout;
    01825         continue;
    01826       }
    01827
    01828       /* Use old layout randomizer code */
    01829       byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
    01830       switch (layout) {
    01831         default: break;
    01832         case 5: layout = 1; break;
    01833         case 0: layout = 2; break;
    01834       }
    01835       t->layout = layout - 1;
    01836     }
    01837   }
    01838
    01839   if (CheckSavegameVersion(114)) {
    01840     /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
    01841      * The conversion affects oil rigs and buoys too, but it doesn't matter as
    01842      * they have st->owner == OWNER_NONE already. */
    01843     Station *st;
    01844     FOR_ALL_STATIONS(st) {
    01845       if (!IsValidCompanyID(st->owner)) st->owner = OWNER_NONE;
    01846     }
    01847
    01848     /* Give owners to waypoints, based on rail tracks it is sitting on.
    01849      * If none is available, specify OWNER_NONE.
    01850      * This code was in CheckSavegameVersion(101) in the past, but in some cases,
    01851      * the owner of waypoints could be incorrect. */
    01852     Waypoint *wp;
    01853     FOR_ALL_WAYPOINTS(wp) {
    01854       Owner owner = IsTileType(wp->xy, MP_RAILWAY) ? GetTileOwner(wp->xy) : OWNER_NONE;
    01855       wp->owner = IsValidCompanyID(owner) ? owner : OWNER_NONE;
    01856     }
    01857   }
    01858
    01859   if (CheckSavegameVersion(121)) {
    01860     /* Delete small ufos heading for non-existing vehicles */
    01861     Vehicle *v;
    01862     FOR_ALL_VEHICLES(v) {
    01863       if (v->type == VEH_DISASTER && v->subtype == 2/*ST_SMALL_UFO*/ && v->current_order.GetDestination() != 0) {
    01864         const Vehicle *u = IsValidVehicleID(v->dest_tile) ? GetVehicle(v->dest_tile) : NULL;
    01865         if (u == NULL || u->type != VEH_ROAD || !IsRoadVehFront(u)) {
    01866           delete v;
    01867         }
    01868       }
    01869     }
    01870   }
    01871
    01872   if (!_cargo_payment_savegame) {
    01873     /* We didn't store cargo payment yet, so make them for vehicles that are
    01874      * currently at a station and loading/unloading. If they don't get any
    01875      * payment anymore they just removed in the next load/unload cycle.
    01876      */
    01877     Station *st;
    01878     FOR_ALL_STATIONS(st) {
    01879       std::list<Vehicle *>::iterator iter;
    01880       for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
    01881         Vehicle *v = *iter;
    01882         assert(v->cargo_payment == NULL);
    01883         v->cargo_payment = new CargoPayment(v);
    01884       }
    01885     }
    01886   }
    01887
    01888   if (CheckSavegameVersion(122)) {
    01889     /* Animated tiles would sometimes not be actually animated or
    01890      * in case of old savegames duplicate. */
    01891
    01892     extern TileIndex *_animated_tile_list;
    01893     extern uint _animated_tile_count;
    01894
    01895     for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
    01896       /* Remove if tile is not animated */
    01897       bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == NULL;
    01898
    01899       /* and remove if duplicate */
    01900       for (uint j = 0; !remove && j < i; j++) {
    01901         remove = _animated_tile_list[i] == _animated_tile_list[j];
    01902       }
    01903
    01904       if (remove) {
    01905         DeleteAnimatedTile(_animated_tile_list[i]);
    01906       } else {
    01907         i++;
    01908       }
    01909     }
    01910
    01911     /* Delete invalid subsidies possibly present in old versions (but converted to new savegame) */
    01912     for (Subsidy *s = _subsidies; s < endof(_subsidies); s++) {
    01913       if (s->cargo_type == CT_INVALID) continue;
    01914       if (s->age >= 12) {
    01915         /* Station -> Station */
    01916         const Station *from = IsValidStationID(s->from) ? GetStation(s->from) : NULL;
    01917         const Station *to = IsValidStationID(s->to) ? GetStation(s->to) : NULL;
    01918         if (from != NULL && to != NULL && from->owner == to->owner && IsValidCompanyID(from->owner)) continue;
    01919       } else {
    01920         const CargoSpec *cs = GetCargo(s->cargo_type);
    01921         switch (cs->town_effect) {
    01922           case TE_PASSENGERS:
    01923           case TE_MAIL:
    01924             /* Town -> Town */
    01925             if (IsValidTownID(s->from) && IsValidTownID(s->to)) continue;
    01926             break;
    01927           case TE_GOODS:
    01928           case TE_FOOD:
    01929             /* Industry -> Town */
    01930             if (IsValidIndustryID(s->from) && IsValidTownID(s->to)) continue;
    01931             break;
    01932           default:
    01933             /* Industry -> Industry */
    01934             if (IsValidIndustryID(s->from) && IsValidIndustryID(s->to)) continue;
    01935             break;
    01936         }
    01937       }
    01938       s->cargo_type = CT_INVALID;
    01939     }
    01940   }
    01941
    01942   GamelogPrintDebug(1);
    01943
    01944   bool ret = InitializeWindowsAndCaches();
    01945   /* Restore the signals */
    01946   ResetSignalHandlers();
    01947   return ret;
    01948 }
    01949
    01956 void ReloadNewGRFData()
    01957 {
    01958   /* reload grf data */
    01959   GfxLoadSprites();
    01960   LoadStringWidthTable();
    01961   ResetEconomy();
    01962   /* reload vehicles */
    01963   ResetVehiclePosHash();
    01964   AfterLoadVehicles(false);
    01965   StartupEngines();
    01966   SetCachedEngineCounts();
    01967   /* update station and waypoint graphics */
    01968
    01969   AfterLoadWaypoints();
    01970   AfterLoadStations();
    01971   /* Check and update house and town values */
    01972   UpdateHousesAndTowns();
    01973   /* Update livery selection windows */
    01974   for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i);
    01975   /* redraw the whole screen */
    01976   MarkWholeScreenDirty();
    01977   CheckTrainsLengths();
    01978 }