afterload.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "../stdafx.h"
00013 #include "../void_map.h"
00014 #include "../signs_base.h"
00015 #include "../depot_base.h"
00016 #include "../window_func.h"
00017 #include "../fios.h"
00018 #include "../gamelog_internal.h"
00019 #include "../network/network.h"
00020 #include "../gfxinit.h"
00021 #include "../viewport_func.h"
00022 #include "../industry.h"
00023 #include "../clear_map.h"
00024 #include "../vehicle_func.h"
00025 #include "../string_func.h"
00026 #include "../date_func.h"
00027 #include "../roadveh.h"
00028 #include "../train.h"
00029 #include "../station_base.h"
00030 #include "../waypoint_base.h"
00031 #include "../roadstop_base.h"
00032 #include "../tunnelbridge_map.h"
00033 #include "../pathfinder/yapf/yapf_cache.h"
00034 #include "../elrail_func.h"
00035 #include "../signs_func.h"
00036 #include "../aircraft.h"
00037 #include "../object_map.h"
00038 #include "../object_base.h"
00039 #include "../tree_map.h"
00040 #include "../company_func.h"
00041 #include "../road_cmd.h"
00042 #include "../ai/ai.hpp"
00043 #include "../ai/ai_gui.hpp"
00044 #include "../town.h"
00045 #include "../economy_base.h"
00046 #include "../animated_tile_func.h"
00047 #include "../subsidy_base.h"
00048 #include "../subsidy_func.h"
00049 #include "../newgrf.h"
00050 #include "../engine_func.h"
00051 #include "../rail_gui.h"
00052 #include "../core/backup_type.hpp"
00053 #include "../smallmap_gui.h"
00054 #include "../news_func.h"
00055 #include "../core/mem_func.hpp"
00056 #include "../trafficlight_func.h"
00057 #include "../cheat_type.h"
00058 
00059 #include "table/strings.h"
00060 
00061 #include "saveload_internal.h"
00062 
00063 #include <signal.h>
00064 
00065 extern StringID _switch_mode_errorstr;
00066 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
00067 
00078 void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
00079 {
00080   /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
00081    * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
00082   if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
00083     if (include_invalid_water_class) {
00084       SetWaterClass(t, WATER_CLASS_INVALID);
00085       return;
00086     } else {
00087       SlErrorCorrupt("Invalid water class for dry tile");
00088     }
00089   }
00090 
00091   /* Mark tile dirty in all cases */
00092   MarkTileDirtyByTile(t);
00093 
00094   if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
00095     /* tiles at map borders are always WATER_CLASS_SEA */
00096     SetWaterClass(t, WATER_CLASS_SEA);
00097     return;
00098   }
00099 
00100   bool has_water = false;
00101   bool has_canal = false;
00102   bool has_river = false;
00103 
00104   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00105     TileIndex neighbour = TileAddByDiagDir(t, dir);
00106     switch (GetTileType(neighbour)) {
00107       case MP_WATER:
00108         /* clear water and shipdepots have already a WaterClass associated */
00109         if (IsCoast(neighbour)) {
00110           has_water = true;
00111         } else if (!IsLock(neighbour)) {
00112           switch (GetWaterClass(neighbour)) {
00113             case WATER_CLASS_SEA:   has_water = true; break;
00114             case WATER_CLASS_CANAL: has_canal = true; break;
00115             case WATER_CLASS_RIVER: has_river = true; break;
00116             default: SlErrorCorrupt("Invalid water class for tile");
00117           }
00118         }
00119         break;
00120 
00121       case MP_RAILWAY:
00122         /* Shore or flooded halftile */
00123         has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
00124         break;
00125 
00126       case MP_TREES:
00127         /* trees on shore */
00128         has_water |= (GB(_m[neighbour].m2, 4, 2) == TREE_GROUND_SHORE);
00129         break;
00130 
00131       default: break;
00132     }
00133   }
00134 
00135   if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
00136     SetWaterClass(t, WATER_CLASS_INVALID);
00137     return;
00138   }
00139 
00140   if (has_river && !has_canal) {
00141     SetWaterClass(t, WATER_CLASS_RIVER);
00142   } else if (has_canal || !has_water) {
00143     SetWaterClass(t, WATER_CLASS_CANAL);
00144   } else {
00145     SetWaterClass(t, WATER_CLASS_SEA);
00146   }
00147 }
00148 
00149 static void ConvertTownOwner()
00150 {
00151   for (TileIndex tile = 0; tile != MapSize(); tile++) {
00152     switch (GetTileType(tile)) {
00153       case MP_ROAD:
00154         if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
00155           _m[tile].m3 = OWNER_TOWN;
00156         }
00157         /* FALL THROUGH */
00158 
00159       case MP_TUNNELBRIDGE:
00160         if (_m[tile].m1 & 0x80) SetTileOwner(tile, OWNER_TOWN);
00161         break;
00162 
00163       default: break;
00164     }
00165   }
00166 }
00167 
00168 /* since savegame version 4.1, exclusive transport rights are stored at towns */
00169 static void UpdateExclusiveRights()
00170 {
00171   Town *t;
00172 
00173   FOR_ALL_TOWNS(t) {
00174     t->exclusivity = INVALID_COMPANY;
00175   }
00176 
00177   /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
00178    *   could be implemented this way:
00179    * 1.) Go through all stations
00180    *     Build an array town_blocked[ town_id ][ company_id ]
00181    *     that stores if at least one station in that town is blocked for a company
00182    * 2.) Go through that array, if you find a town that is not blocked for
00183    *     one company, but for all others, then give him exclusivity.
00184    */
00185 }
00186 
00187 static const byte convert_currency[] = {
00188    0,  1, 12,  8,  3,
00189   10, 14, 19,  4,  5,
00190    9, 11, 13,  6, 17,
00191   16, 22, 21,  7, 15,
00192   18,  2, 20,
00193 };
00194 
00195 /* since savegame version 4.2 the currencies are arranged differently */
00196 static void UpdateCurrencies()
00197 {
00198   _settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
00199 }
00200 
00201 /* Up to revision 1413 the invisible tiles at the southern border have not been
00202  * MP_VOID, even though they should have. This is fixed by this function
00203  */
00204 static void UpdateVoidTiles()
00205 {
00206   uint i;
00207 
00208   for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
00209   for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
00210 }
00211 
00212 static inline RailType UpdateRailType(RailType rt, RailType min)
00213 {
00214   return rt >= min ? (RailType)(rt + 1): rt;
00215 }
00216 
00220 void UpdateAllVirtCoords()
00221 {
00222   UpdateAllStationVirtCoords();
00223   UpdateAllSignVirtCoords();
00224   UpdateAllTownVirtCoords();
00225 }
00226 
00236 static void InitializeWindowsAndCaches()
00237 {
00238   /* Initialize windows */
00239   ResetWindowSystem();
00240   SetupColoursAndInitialWindow();
00241 
00242   /* Update coordinates of the signs. */
00243   UpdateAllVirtCoords();
00244   ResetViewportAfterLoadGame();
00245 
00246   Company *c;
00247   FOR_ALL_COMPANIES(c) {
00248     /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
00249      * accordingly if it is not the case.  No need to set it on companies that are not been used already,
00250      * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
00251     if (_file_to_saveload.filetype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
00252       c->inaugurated_year = _cur_year;
00253     }
00254   }
00255 
00256   RecomputePrices();
00257 
00258   SetCachedEngineCounts();
00259 
00260   Station::RecomputeIndustriesNearForAll();
00261   RebuildSubsidisedSourceAndDestinationCache();
00262 
00263   /* Towns have a noise controlled number of airports system
00264    * So each airport's noise value must be added to the town->noise_reached value
00265    * Reset each town's noise_reached value to '0' before. */
00266   UpdateAirportsNoise();
00267 
00268   CheckTrainsLengths();
00269   ShowNewGRFError();
00270   ShowAIDebugWindowIfAIError();
00271 
00272   /* Rebuild the smallmap list of owners. */
00273   BuildOwnerLegend();
00274 }
00275 
00276 typedef void (CDECL *SignalHandlerPointer)(int);
00277 static SignalHandlerPointer _prev_segfault = NULL;
00278 static SignalHandlerPointer _prev_abort    = NULL;
00279 static SignalHandlerPointer _prev_fpe      = NULL;
00280 
00281 static void CDECL HandleSavegameLoadCrash(int signum);
00282 
00287 static void SetSignalHandlers()
00288 {
00289   _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
00290   _prev_abort    = signal(SIGABRT, HandleSavegameLoadCrash);
00291   _prev_fpe      = signal(SIGFPE,  HandleSavegameLoadCrash);
00292 }
00293 
00297 static void ResetSignalHandlers()
00298 {
00299   signal(SIGSEGV, _prev_segfault);
00300   signal(SIGABRT, _prev_abort);
00301   signal(SIGFPE,  _prev_fpe);
00302 }
00303 
00309 static const GRFIdentifier *GetOverriddenIdentifier(const GRFConfig *c)
00310 {
00311   const LoggedAction *la = &_gamelog_action[_gamelog_actions - 1];
00312   if (la->at != GLAT_LOAD) return &c->ident;
00313 
00314   const LoggedChange *lcend = &la->change[la->changes];
00315   for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
00316     if (lc->ct == GLCT_GRFCOMPAT && lc->grfcompat.grfid == c->ident.grfid) return &lc->grfcompat;
00317   }
00318 
00319   return &c->ident;
00320 }
00321 
00323 static bool _saveload_crash_with_missing_newgrfs = false;
00324 
00330 bool SaveloadCrashWithMissingNewGRFs()
00331 {
00332   return _saveload_crash_with_missing_newgrfs;
00333 }
00334 
00341 static void CDECL HandleSavegameLoadCrash(int signum)
00342 {
00343   ResetSignalHandlers();
00344 
00345   char buffer[8192];
00346   char *p = buffer;
00347   p += seprintf(p, lastof(buffer), "Loading your savegame caused OpenTTD to crash.\n");
00348 
00349   for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != NULL; c = c->next) {
00350     _saveload_crash_with_missing_newgrfs = HasBit(c->flags, GCF_COMPATIBLE) || c->status == GCS_NOT_FOUND;
00351   }
00352 
00353   if (_saveload_crash_with_missing_newgrfs) {
00354     p += seprintf(p, lastof(buffer),
00355       "This is most likely caused by a missing NewGRF or a NewGRF that\n"
00356       "has been loaded as replacement for a missing NewGRF. OpenTTD\n"
00357       "cannot easily determine whether a replacement NewGRF is of a newer\n"
00358       "or older version.\n"
00359       "It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
00360       "This means that if the author makes incompatible NewGRFs with the\n"
00361       "same GRF ID OpenTTD cannot magically do the right thing. In most\n"
00362       "cases OpenTTD will load the savegame and not crash, but this is an\n"
00363       "exception.\n"
00364       "Please load the savegame with the appropriate NewGRFs installed.\n"
00365       "The missing/compatible NewGRFs are:\n");
00366 
00367     for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
00368       if (HasBit(c->flags, GCF_COMPATIBLE)) {
00369         const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
00370         char buf[40];
00371         md5sumToString(buf, lastof(buf), replaced->md5sum);
00372         p += seprintf(p, lastof(buffer), "NewGRF %08X (checksum %s) not found.\n  Loaded NewGRF \"%s\" with same GRF ID instead.\n", BSWAP32(c->ident.grfid), buf, c->filename);
00373       }
00374       if (c->status == GCS_NOT_FOUND) {
00375         char buf[40];
00376         md5sumToString(buf, lastof(buf), c->ident.md5sum);
00377         p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s.\n", BSWAP32(c->ident.grfid), c->filename, buf);
00378       }
00379     }
00380   } else {
00381     p += seprintf(p, lastof(buffer),
00382       "This is probably caused by a corruption in the savegame.\n"
00383       "Please file a bug report and attach this savegame.\n");
00384   }
00385 
00386   ShowInfo(buffer);
00387 
00388   SignalHandlerPointer call = NULL;
00389   switch (signum) {
00390     case SIGSEGV: call = _prev_segfault; break;
00391     case SIGABRT: call = _prev_abort; break;
00392     case SIGFPE:  call = _prev_fpe; break;
00393     default: NOT_REACHED();
00394   }
00395   if (call != NULL) call(signum);
00396 }
00397 
00403 static void FixOwnerOfRailTrack(TileIndex t)
00404 {
00405   assert(!Company::IsValidID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
00406 
00407   /* remove leftover rail piece from crossing (from very old savegames) */
00408   Train *v = NULL, *w;
00409   FOR_ALL_TRAINS(w) {
00410     if (w->tile == t) {
00411       v = w;
00412       break;
00413     }
00414   }
00415 
00416   if (v != NULL) {
00417     /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
00418     SetTileOwner(t, v->owner);
00419     return;
00420   }
00421 
00422   /* try to find any connected rail */
00423   for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
00424     TileIndex tt = t + TileOffsByDiagDir(dd);
00425     if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
00426         GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
00427         Company::IsValidID(GetTileOwner(tt))) {
00428       SetTileOwner(t, GetTileOwner(tt));
00429       return;
00430     }
00431   }
00432 
00433   if (IsLevelCrossingTile(t)) {
00434     /* else change the crossing to normal road (road vehicles won't care) */
00435     MakeRoadNormal(t, GetCrossingRoadBits(t), GetRoadTypes(t), GetTownIndex(t),
00436       GetRoadOwner(t, ROADTYPE_ROAD), GetRoadOwner(t, ROADTYPE_TRAM));
00437     return;
00438   }
00439 
00440   /* if it's not a crossing, make it clean land */
00441   MakeClear(t, CLEAR_GRASS, 0);
00442 }
00443 
00450 static uint FixVehicleInclination(Vehicle *v, Direction dir)
00451 {
00452   /* Compute place where this vehicle entered the tile */
00453   int entry_x = v->x_pos;
00454   int entry_y = v->y_pos;
00455   switch (dir) {
00456     case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
00457     case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
00458     case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
00459     case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
00460     case INVALID_DIR: break;
00461     default: NOT_REACHED();
00462   }
00463   byte entry_z = GetSlopeZ(entry_x, entry_y);
00464 
00465   /* Compute middle of the tile. */
00466   int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + HALF_TILE_SIZE;
00467   int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + HALF_TILE_SIZE;
00468   byte middle_z = GetSlopeZ(middle_x, middle_y);
00469 
00470   /* middle_z == entry_z, no height change. */
00471   if (middle_z == entry_z) return 0;
00472 
00473   /* middle_z < entry_z, we are going downwards. */
00474   if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
00475 
00476   /* middle_z > entry_z, we are going upwards. */
00477   return 1U << GVF_GOINGUP_BIT;
00478 }
00479 
00485 bool AfterLoadGame()
00486 {
00487   /* Put this at the very beginning, since the subsequent code in
00488    * AfterLoadGame sometimes uses heightlevel information.
00489    * So that code might fail if we load a savegame without extended
00490    * heightlevel data, but allow_more_heightlevels is still true
00491    * because it was not yet overwritten since the previous game.
00492    *
00493    * This especially applies when exiting a game and switching
00494    * to the intro game. */
00495   if (IsSavegameVersionBefore(MORE_HEIGHTLEVEL_SAVEGAME_VERSION)) {
00496     /* Maybe it is still filled from the previous game. If the currently loaded
00497      * game was saved with an OpenTTD version where the allow more heightlevels
00498      * patch was not yet introduced, we know for sure that it was NOT filled
00499      * during SlLoadChunks (because no MAPH chunk can exist in such a savegame). */
00500     free(_map_heightdata);
00501     _map_heightdata = NULL;
00502 
00503     /* Also, the default for such a game is that this patch is turned off.
00504      * However, the player may turn it on using the menu afterwards. */
00505     _settings_game.construction.allow_more_heightlevels = false;
00506   }
00507 
00508   /* Assure that configuration setting is consistent to the data. */
00509   assert(AllowMoreHeightlevels() == (_map_heightdata != NULL));
00510 
00511   SetSignalHandlers();
00512 
00513   TileIndex map_size = MapSize();
00514 
00515   if (IsSavegameVersionBefore(98)) GamelogOldver();
00516 
00517   GamelogTestRevision();
00518   GamelogTestMode();
00519 
00520   if (IsSavegameVersionBefore(98)) GamelogGRFAddList(_grfconfig);
00521 
00522   if (IsSavegameVersionBefore(119)) {
00523     _pause_mode = (_pause_mode == 2) ? PM_PAUSED_NORMAL : PM_UNPAUSED;
00524   } else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
00525     DEBUG(net, 0, "The loading savegame was paused due to an error state.");
00526     DEBUG(net, 0, "  The savegame cannot be used for multiplayer!");
00527     /* Restore the signals */
00528     ResetSignalHandlers();
00529     return false;
00530   } else if (!_networking || _network_server) {
00531     /* If we are in single player, i.e. not networking, and loading the
00532      * savegame or we are loading the savegame as network server we do
00533      * not want to be bothered by being paused because of the automatic
00534      * reason of a network server, e.g. joining clients or too few
00535      * active clients. Note that resetting these values for a network
00536      * client are very bad because then the client is going to execute
00537      * the game loop when the server is not, i.e. it desyncs. */
00538     _pause_mode &= ~PMB_PAUSED_NETWORK;
00539   }
00540 
00541   /* In very old versions, size of train stations was stored differently.
00542    * They had swapped width and height if station was built along the Y axis.
00543    * TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
00544    * Because the data stored by TTDPatch are unusable for rail stations > 7x7,
00545    * recompute the width and height. Doing this unconditionally for all old
00546    * savegames simplifies the code. */
00547   if (IsSavegameVersionBefore(2)) {
00548     Station *st;
00549     FOR_ALL_STATIONS(st) {
00550       st->train_station.w = st->train_station.h = 0;
00551     }
00552     for (TileIndex t = 0; t < map_size; t++) {
00553       if (!IsTileType(t, MP_STATION)) continue;
00554       if (_m[t].m5 > 7) continue; // is it a rail station tile?
00555       st = Station::Get(_m[t].m2);
00556       assert(st->train_station.tile != 0);
00557       int dx = TileX(t) - TileX(st->train_station.tile);
00558       int dy = TileY(t) - TileY(st->train_station.tile);
00559       assert(dx >= 0 && dy >= 0);
00560       st->train_station.w = max<uint>(st->train_station.w, dx + 1);
00561       st->train_station.h = max<uint>(st->train_station.h, dy + 1);
00562     }
00563   }
00564 
00565   /* in version 2.1 of the savegame, town owner was unified. */
00566   if (IsSavegameVersionBefore(2, 1)) ConvertTownOwner();
00567 
00568   /* from version 4.1 of the savegame, exclusive rights are stored at towns */
00569   if (IsSavegameVersionBefore(4, 1)) UpdateExclusiveRights();
00570 
00571   /* from version 4.2 of the savegame, currencies are in a different order */
00572   if (IsSavegameVersionBefore(4, 2)) UpdateCurrencies();
00573 
00574   /* In old version there seems to be a problem that water is owned by
00575    * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
00576    * (4.3) version, so I just check when versions are older, and then
00577    * walk through the whole map.. */
00578   if (IsSavegameVersionBefore(4, 3)) {
00579     for (TileIndex t = 0; t < map_size; t++) {
00580       if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
00581         SetTileOwner(t, OWNER_WATER);
00582       }
00583     }
00584   }
00585 
00586   if (IsSavegameVersionBefore(84)) {
00587     Company *c;
00588     FOR_ALL_COMPANIES(c) {
00589       c->name = CopyFromOldName(c->name_1);
00590       if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
00591       c->president_name = CopyFromOldName(c->president_name_1);
00592       if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
00593     }
00594 
00595     Station *st;
00596     FOR_ALL_STATIONS(st) {
00597       st->name = CopyFromOldName(st->string_id);
00598       /* generating new name would be too much work for little effect, use the station name fallback */
00599       if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
00600     }
00601 
00602     Town *t;
00603     FOR_ALL_TOWNS(t) {
00604       t->name = CopyFromOldName(t->townnametype);
00605       if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
00606     }
00607   }
00608 
00609   /* From this point the old names array is cleared. */
00610   ResetOldNames();
00611 
00612   if (IsSavegameVersionBefore(106)) {
00613     /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
00614     Station *st;
00615     FOR_ALL_STATIONS(st) {
00616       if (st->airport.tile       == 0) st->airport.tile = INVALID_TILE;
00617       if (st->dock_tile          == 0) st->dock_tile    = INVALID_TILE;
00618       if (st->train_station.tile == 0) st->train_station.tile   = INVALID_TILE;
00619     }
00620 
00621     /* the same applies to Company::location_of_HQ */
00622     Company *c;
00623     FOR_ALL_COMPANIES(c) {
00624       if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(4) && c->location_of_HQ == 0xFFFF)) {
00625         c->location_of_HQ = INVALID_TILE;
00626       }
00627     }
00628   }
00629 
00630   /* convert road side to my format. */
00631   if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
00632 
00633   /* Check if all NewGRFs are present, we are very strict in MP mode */
00634   GRFListCompatibility gcf_res = IsGoodGRFConfigList(_grfconfig);
00635   for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
00636     if (c->status == GCS_NOT_FOUND) {
00637       GamelogGRFRemove(c->ident.grfid);
00638     } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
00639       GamelogGRFCompatible(&c->ident);
00640     }
00641   }
00642 
00643   if (_networking && gcf_res != GLC_ALL_GOOD) {
00644     SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
00645     /* Restore the signals */
00646     ResetSignalHandlers();
00647     return false;
00648   }
00649 
00650   switch (gcf_res) {
00651     case GLC_COMPATIBLE: _switch_mode_errorstr = STR_NEWGRF_COMPATIBLE_LOAD_WARNING; break;
00652     case GLC_NOT_FOUND:  _switch_mode_errorstr = STR_NEWGRF_DISABLED_WARNING; _pause_mode = PM_PAUSED_ERROR; break;
00653     default: break;
00654   }
00655 
00656   /* The value of _date_fract got divided, so make sure that old games are converted correctly. */
00657   if (IsSavegameVersionBefore(11, 1) || (IsSavegameVersionBefore(KEEP_COMPATIBLE_1_SV) && _date_fract > DAY_TICKS)) _date_fract /= 885;
00658 
00659   /* Update current year
00660    * must be done before loading sprites as some newgrfs check it */
00661   SetDate(_date, _date_fract);
00662 
00663   /* Force dynamic engines off when loading older savegames */
00664   if (IsSavegameVersionBefore(95)) _settings_game.vehicle.dynamic_engines = 0;
00665 
00666   /* Load the sprites */
00667   GfxLoadSprites();
00668   LoadStringWidthTable();
00669 
00670   /* Copy temporary data to Engine pool */
00671   CopyTempEngineData();
00672 
00673   /* Connect front and rear engines of multiheaded trains and converts
00674    * subtype to the new format */
00675   if (IsSavegameVersionBefore(17, 1)) ConvertOldMultiheadToNew();
00676 
00677   /* Connect front and rear engines of multiheaded trains */
00678   ConnectMultiheadedTrains();
00679 
00680   /* Fix the CargoPackets *and* fix the caches of CargoLists.
00681    * If this isn't done before Stations and especially Vehicles are
00682    * running their AfterLoad we might get in trouble. In the case of
00683    * vehicles we could give the wrong (cached) count of items in a
00684    * vehicle which causes different results when getting their caches
00685    * filled; and that could eventually lead to desyncs. */
00686   CargoPacket::AfterLoad();
00687 
00688   /* Oilrig was moved from id 15 to 9. We have to do this conversion
00689    * here as AfterLoadVehicles can check it indirectly via the newgrf
00690    * code. */
00691   if (IsSavegameVersionBefore(139)) {
00692     Station *st;
00693     FOR_ALL_STATIONS(st) {
00694       if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
00695         st->airport.type = AT_OILRIG;
00696       }
00697     }
00698   }
00699 
00700   /* Update all vehicles */
00701   AfterLoadVehicles(true);
00702 
00703   /* Make sure there is an AI attached to an AI company */
00704   {
00705     Company *c;
00706     FOR_ALL_COMPANIES(c) {
00707       if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
00708     }
00709   }
00710 
00711   /* make sure there is a town in the game */
00712   if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
00713     SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
00714     /* Restore the signals */
00715     ResetSignalHandlers();
00716     return false;
00717   }
00718 
00719   /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
00720    * This problem appears in savegame version 21 too, see r3455. But after loading the
00721    * savegame and saving again, the buggy map array could be converted to new savegame
00722    * version. It didn't show up before r12070. */
00723   if (IsSavegameVersionBefore(87)) UpdateVoidTiles();
00724 
00725   /* If Load Scenario / New (Scenario) Game is used,
00726    *  a company does not exist yet. So create one here.
00727    * 1 exeption: network-games. Those can have 0 companies
00728    *   But this exeption is not true for non dedicated network_servers! */
00729   if (!Company::IsValidID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated))) {
00730     DoStartupNewCompany(false);
00731   }
00732 
00733   /* Fix the cache for cargo payments. */
00734   CargoPayment *cp;
00735   FOR_ALL_CARGO_PAYMENTS(cp) {
00736     cp->front->cargo_payment = cp;
00737     cp->current_station = cp->front->last_station_visited;
00738   }
00739 
00740   if (IsSavegameVersionBefore(72)) {
00741     /* Locks in very old savegames had OWNER_WATER as owner */
00742     for (TileIndex t = 0; t < MapSize(); t++) {
00743       switch (GetTileType(t)) {
00744         default: break;
00745 
00746         case MP_WATER:
00747           if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
00748           break;
00749 
00750         case MP_STATION: {
00751           if (HasBit(_m[t].m6, 3)) SetBit(_m[t].m6, 2);
00752           StationGfx gfx = GetStationGfx(t);
00753           StationType st;
00754           if (       IsInsideMM(gfx,   0,   8)) { // Rail station
00755             st = STATION_RAIL;
00756             SetStationGfx(t, gfx - 0);
00757           } else if (IsInsideMM(gfx,   8,  67)) { // Airport
00758             st = STATION_AIRPORT;
00759             SetStationGfx(t, gfx - 8);
00760           } else if (IsInsideMM(gfx,  67,  71)) { // Truck
00761             st = STATION_TRUCK;
00762             SetStationGfx(t, gfx - 67);
00763           } else if (IsInsideMM(gfx,  71,  75)) { // Bus
00764             st = STATION_BUS;
00765             SetStationGfx(t, gfx - 71);
00766           } else if (gfx == 75) {                 // Oil rig
00767             st = STATION_OILRIG;
00768             SetStationGfx(t, gfx - 75);
00769           } else if (IsInsideMM(gfx,  76,  82)) { // Dock
00770             st = STATION_DOCK;
00771             SetStationGfx(t, gfx - 76);
00772           } else if (gfx == 82) {                 // Buoy
00773             st = STATION_BUOY;
00774             SetStationGfx(t, gfx - 82);
00775           } else if (IsInsideMM(gfx,  83, 168)) { // Extended airport
00776             st = STATION_AIRPORT;
00777             SetStationGfx(t, gfx - 83 + 67 - 8);
00778           } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
00779             st = STATION_TRUCK;
00780             SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
00781           } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
00782             st = STATION_BUS;
00783             SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
00784           } else {
00785             /* Restore the signals */
00786             ResetSignalHandlers();
00787             return false;
00788           }
00789           SB(_m[t].m6, 3, 3, st);
00790           break;
00791         }
00792       }
00793     }
00794   }
00795 
00796   for (TileIndex t = 0; t < map_size; t++) {
00797     switch (GetTileType(t)) {
00798       case MP_STATION: {
00799         BaseStation *bst = BaseStation::GetByTile(t);
00800 
00801         /* Set up station spread */
00802         bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
00803 
00804         /* Waypoints don't have road stops/oil rigs in the old format */
00805         if (!Station::IsExpected(bst)) break;
00806         Station *st = Station::From(bst);
00807 
00808         switch (GetStationType(t)) {
00809           case STATION_TRUCK:
00810           case STATION_BUS:
00811             if (IsSavegameVersionBefore(6)) {
00812               /* Before version 5 you could not have more than 250 stations.
00813                * Version 6 adds large maps, so you could only place 253*253
00814                * road stops on a map (no freeform edges) = 64009. So, yes
00815                * someone could in theory create such a full map to trigger
00816                * this assertion, it's safe to assume that's only something
00817                * theoretical and does not happen in normal games. */
00818               assert(RoadStop::CanAllocateItem());
00819 
00820               /* From this version on there can be multiple road stops of the
00821                * same type per station. Convert the existing stops to the new
00822                * internal data structure. */
00823               RoadStop *rs = new RoadStop(t);
00824 
00825               RoadStop **head =
00826                 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
00827               *head = rs;
00828             }
00829             break;
00830 
00831           case STATION_OILRIG: {
00832             /* Very old savegames sometimes have phantom oil rigs, i.e.
00833              * an oil rig which got shut down, but not completly removed from
00834              * the map
00835              */
00836             TileIndex t1 = TILE_ADDXY(t, 0, 1);
00837             if (IsTileType(t1, MP_INDUSTRY) &&
00838                 GetIndustryGfx(t1) == GFX_OILRIG_1) {
00839               /* The internal encoding of oil rigs was changed twice.
00840                * It was 3 (till 2.2) and later 5 (till 5.1).
00841                * Setting it unconditionally does not hurt.
00842                */
00843               Station::GetByTile(t)->airport.type = AT_OILRIG;
00844             } else {
00845               DeleteOilRig(t);
00846             }
00847             break;
00848           }
00849 
00850           default: break;
00851         }
00852         break;
00853       }
00854 
00855       default: break;
00856     }
00857   }
00858 
00859   /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
00860    * This has to be called after the oilrig airport_type update above ^^^ ! */
00861   if (IsSavegameVersionBefore(2, 2)) UpdateOldAircraft();
00862 
00863   /* In version 6.1 we put the town index in the map-array. To do this, we need
00864    *  to use m2 (16bit big), so we need to clean m2, and that is where this is
00865    *  all about ;) */
00866   if (IsSavegameVersionBefore(6, 1)) {
00867     for (TileIndex t = 0; t < map_size; t++) {
00868       switch (GetTileType(t)) {
00869         case MP_HOUSE:
00870           _m[t].m4 = _m[t].m2;
00871           SetTownIndex(t, CalcClosestTownFromTile(t)->index);
00872           break;
00873 
00874         case MP_ROAD:
00875           _m[t].m4 |= (_m[t].m2 << 4);
00876           if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
00877             SetTownIndex(t, CalcClosestTownFromTile(t)->index);
00878           } else {
00879             SetTownIndex(t, 0);
00880           }
00881           break;
00882 
00883         default: break;
00884       }
00885     }
00886   }
00887 
00888   /* Force the freeform edges to false for old savegames. */
00889   if (IsSavegameVersionBefore(111)) {
00890     _settings_game.construction.freeform_edges = false;
00891   }
00892 
00893   /* From version 9.0, we update the max passengers of a town (was sometimes negative
00894    *  before that. */
00895   if (IsSavegameVersionBefore(9)) {
00896     Town *t;
00897     FOR_ALL_TOWNS(t) {
00898       UpdateTownGenCargo(t);
00899     }
00900   }
00901 
00902   /* From now on we have a demand for goods from towns. */
00903   if (IsSavegameVersionBefore(TOWN_GROWTH_SV)) {
00904     Town *t;
00905     FOR_ALL_TOWNS(t) {
00906       UpdateTownDemands(t);
00907     }
00908   }
00909 
00910   /* From version 16.0, we included autorenew on engines, which are now saved, but
00911    *  of course, we do need to initialize them for older savegames. */
00912   if (IsSavegameVersionBefore(16)) {
00913     Company *c;
00914     FOR_ALL_COMPANIES(c) {
00915       c->engine_renew_list            = NULL;
00916       c->settings.engine_renew        = false;
00917       c->settings.engine_renew_months = 6;
00918       c->settings.engine_renew_money  = 100000;
00919     }
00920 
00921     /* When loading a game, _local_company is not yet set to the correct value.
00922      * However, in a dedicated server we are a spectator, so nothing needs to
00923      * happen. In case we are not a dedicated server, the local company always
00924      * becomes company 0, unless we are in the scenario editor where all the
00925      * companies are 'invalid'.
00926      */
00927     c = Company::GetIfValid(COMPANY_FIRST);
00928     if (!_network_dedicated && c != NULL) {
00929       c->settings = _settings_client.company;
00930     }
00931   }
00932 
00933   if (IsSavegameVersionBefore(48)) {
00934     for (TileIndex t = 0; t < map_size; t++) {
00935       switch (GetTileType(t)) {
00936         case MP_RAILWAY:
00937           if (IsPlainRail(t)) {
00938             /* Swap ground type and signal type for plain rail tiles, so the
00939              * ground type uses the same bits as for depots and waypoints. */
00940             uint tmp = GB(_m[t].m4, 0, 4);
00941             SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
00942             SB(_m[t].m2, 0, 4, tmp);
00943           } else if (HasBit(_m[t].m5, 2)) {
00944             /* Split waypoint and depot rail type and remove the subtype. */
00945             ClrBit(_m[t].m5, 2);
00946             ClrBit(_m[t].m5, 6);
00947           }
00948           break;
00949 
00950         case MP_ROAD:
00951           /* Swap m3 and m4, so the track type for rail crossings is the
00952            * same as for normal rail. */
00953           Swap(_m[t].m3, _m[t].m4);
00954           break;
00955 
00956         default: break;
00957       }
00958     }
00959   }
00960 
00961   if (IsSavegameVersionBefore(61)) {
00962     /* Added the RoadType */
00963     bool old_bridge = IsSavegameVersionBefore(42);
00964     for (TileIndex t = 0; t < map_size; t++) {
00965       switch (GetTileType(t)) {
00966         case MP_ROAD:
00967           SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
00968           switch (GetRoadTileType(t)) {
00969             default: SlErrorCorrupt("Invalid road tile type");
00970             case ROAD_TILE_NORMAL:
00971               SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
00972               SB(_m[t].m4, 4, 4, 0);
00973               SB(_m[t].m6, 2, 4, 0);
00974               break;
00975             case ROAD_TILE_CROSSING:
00976               SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
00977               break;
00978             case ROAD_TILE_DEPOT:    break;
00979           }
00980           SetRoadTypes(t, ROADTYPES_ROAD);
00981           break;
00982 
00983         case MP_STATION:
00984           if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
00985           break;
00986 
00987         case MP_TUNNELBRIDGE:
00988           /* Middle part of "old" bridges */
00989           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
00990           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
00991             SetRoadTypes(t, ROADTYPES_ROAD);
00992           }
00993           break;
00994 
00995         default: break;
00996       }
00997     }
00998   }
00999 
01000   if (IsSavegameVersionBefore(114)) {
01001     bool fix_roadtypes = !IsSavegameVersionBefore(61);
01002     bool old_bridge = IsSavegameVersionBefore(42);
01003 
01004     for (TileIndex t = 0; t < map_size; t++) {
01005       switch (GetTileType(t)) {
01006         case MP_ROAD:
01007           if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
01008           SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
01009           switch (GetRoadTileType(t)) {
01010             default: SlErrorCorrupt("Invalid road tile type");
01011             case ROAD_TILE_NORMAL:
01012               SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
01013               SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3));  // ground
01014               SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4));  // tram bits
01015               SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4));  // tram owner
01016               SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4));  // road bits
01017               break;
01018 
01019             case ROAD_TILE_CROSSING:
01020               SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
01021               SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3));  // ground
01022               SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4));  // tram owner
01023               SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1));  // road axis
01024               SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1));  // crossing state
01025               break;
01026 
01027             case ROAD_TILE_DEPOT:
01028               break;
01029           }
01030           if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
01031             const Town *town = CalcClosestTownFromTile(t);
01032             if (town != NULL) SetTownIndex(t, town->index);
01033           }
01034           _m[t].m4 = 0;
01035           break;
01036 
01037         case MP_STATION:
01038           if (!IsRoadStop(t)) break;
01039 
01040           if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
01041           SB(_me[t].m7, 0, 5, HasBit(_m[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
01042           SB(_m[t].m3, 4, 4, _m[t].m1);
01043           _m[t].m4 = 0;
01044           break;
01045 
01046         case MP_TUNNELBRIDGE:
01047           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
01048           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
01049             if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
01050 
01051             Owner o = GetTileOwner(t);
01052             SB(_me[t].m7, 0, 5, o); // road owner
01053             SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
01054           }
01055           SB(_m[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
01056           SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
01057 
01058           _m[t].m2 = 0;
01059           _m[t].m4 = 0;
01060           break;
01061 
01062         default: break;
01063       }
01064     }
01065   }
01066 
01067   if (IsSavegameVersionBefore(42)) {
01068     Vehicle *v;
01069 
01070     for (TileIndex t = 0; t < map_size; t++) {
01071       if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
01072       if (IsBridgeTile(t)) {
01073         if (HasBit(_m[t].m5, 6)) { // middle part
01074           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
01075 
01076           if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
01077             if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
01078               MakeRailNormal(
01079                 t,
01080                 GetTileOwner(t),
01081                 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
01082                 GetRailType(t)
01083               );
01084             } else {
01085               TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
01086 
01087               MakeRoadNormal(
01088                 t,
01089                 axis == AXIS_X ? ROAD_Y : ROAD_X,
01090                 ROADTYPES_ROAD,
01091                 town,
01092                 GetTileOwner(t), OWNER_NONE
01093               );
01094             }
01095           } else {
01096             if (GB(_m[t].m5, 3, 2) == 0) {
01097               MakeClear(t, CLEAR_GRASS, 3);
01098             } else {
01099               if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
01100                 MakeShore(t);
01101               } else {
01102                 if (GetTileOwner(t) == OWNER_WATER) {
01103                   MakeSea(t);
01104                 } else {
01105                   MakeCanal(t, GetTileOwner(t), Random());
01106                 }
01107               }
01108             }
01109           }
01110           SetBridgeMiddle(t, axis);
01111         } else { // ramp
01112           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
01113           uint north_south = GB(_m[t].m5, 5, 1);
01114           DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
01115           TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
01116 
01117           _m[t].m5 = 1 << 7 | type << 2 | dir;
01118         }
01119       }
01120     }
01121 
01122     FOR_ALL_VEHICLES(v) {
01123       int z = GetSlopeZ(v->x_pos, v->y_pos);
01124       if (!v->IsGroundVehicle()) continue;
01125       if (IsBridgeTile(v->tile)) {
01126         DiagDirection dir = GetTunnelBridgeDirection(v->tile);
01127 
01128         if (dir != DirToDiagDir(v->direction)) continue;
01129         switch (dir) {
01130           default: SlErrorCorrupt("Invalid vehicle direction");
01131           case DIAGDIR_NE: if ((v->x_pos & 0xF) !=  0)            continue; break;
01132           case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
01133           case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
01134           case DIAGDIR_NW: if ((v->y_pos & 0xF) !=  0)            continue; break;
01135         }
01136       } else if (v->z_pos > z) {
01137         v->tile = GetNorthernBridgeEnd(v->tile);
01138       } else {
01139         continue;
01140       }
01141       if (v->type == VEH_TRAIN) {
01142         Train::From(v)->track = TRACK_BIT_WORMHOLE;
01143       } else {
01144         RoadVehicle::From(v)->state = RVSB_WORMHOLE;
01145       }
01146     }
01147   }
01148 
01149   /* Elrails got added in rev 24 */
01150   if (IsSavegameVersionBefore(24)) {
01151     RailType min_rail = RAILTYPE_ELECTRIC;
01152 
01153     Train *v;
01154     FOR_ALL_TRAINS(v) {
01155       RailType rt = RailVehInfo(v->engine_type)->railtype;
01156 
01157       v->railtype = rt;
01158       if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
01159     }
01160 
01161     /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
01162     for (TileIndex t = 0; t < map_size; t++) {
01163       switch (GetTileType(t)) {
01164         case MP_RAILWAY:
01165           SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
01166           break;
01167 
01168         case MP_ROAD:
01169           if (IsLevelCrossing(t)) {
01170             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
01171           }
01172           break;
01173 
01174         case MP_STATION:
01175           if (HasStationRail(t)) {
01176             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
01177           }
01178           break;
01179 
01180         case MP_TUNNELBRIDGE:
01181           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
01182             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
01183           }
01184           break;
01185 
01186         default:
01187           break;
01188       }
01189     }
01190 
01191     FOR_ALL_TRAINS(v) {
01192       if (v->IsFrontEngine() || v->IsFreeWagon()) v->ConsistChanged(true);
01193     }
01194 
01195   }
01196 
01197   /* In version 16.1 of the savegame a company can decide if trains, which get
01198    * replaced, shall keep their old length. In all prior versions, just default
01199    * to false */
01200   if (IsSavegameVersionBefore(16, 1)) {
01201     Company *c;
01202     FOR_ALL_COMPANIES(c) c->settings.renew_keep_length = false;
01203   }
01204 
01205   if (IsSavegameVersionBefore(123)) {
01206     /* Waypoints became subclasses of stations ... */
01207     MoveWaypointsToBaseStations();
01208     /* ... and buoys were moved to waypoints. */
01209     MoveBuoysToWaypoints();
01210   }
01211 
01212   /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
01213    *  room for PBS. Now in version 21 move it back :P. */
01214   if (IsSavegameVersionBefore(21) && !IsSavegameVersionBefore(15)) {
01215     for (TileIndex t = 0; t < map_size; t++) {
01216       switch (GetTileType(t)) {
01217         case MP_RAILWAY:
01218           if (HasSignals(t)) {
01219             /* convert PBS signals to combo-signals */
01220             if (HasBit(_m[t].m2, 2)) SetSignalType(t, TRACK_X, SIGTYPE_COMBO);
01221 
01222             /* move the signal variant back */
01223             SetSignalVariant(t, TRACK_X, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
01224             ClrBit(_m[t].m2, 3);
01225           }
01226 
01227           /* Clear PBS reservation on track */
01228           if (!IsRailDepotTile(t)) {
01229             SB(_m[t].m4, 4, 4, 0);
01230           } else {
01231             ClrBit(_m[t].m3, 6);
01232           }
01233           break;
01234 
01235         case MP_STATION: // Clear PBS reservation on station
01236           ClrBit(_m[t].m3, 6);
01237           break;
01238 
01239         default: break;
01240       }
01241     }
01242   }
01243 
01244   if (IsSavegameVersionBefore(25)) {
01245     RoadVehicle *rv;
01246     FOR_ALL_ROADVEHICLES(rv) {
01247       rv->vehstatus &= ~0x40;
01248     }
01249   }
01250 
01251   if (IsSavegameVersionBefore(26)) {
01252     Station *st;
01253     FOR_ALL_STATIONS(st) {
01254       st->last_vehicle_type = VEH_INVALID;
01255     }
01256   }
01257 
01258   YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
01259 
01260   if (IsSavegameVersionBefore(34)) {
01261     Company *c;
01262     FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
01263   }
01264 
01265   Company *c;
01266   FOR_ALL_COMPANIES(c) {
01267     c->avail_railtypes = GetCompanyRailtypes(c->index);
01268     c->avail_roadtypes = GetCompanyRoadtypes(c->index);
01269   }
01270 
01271   if (!IsSavegameVersionBefore(27)) AfterLoadStations();
01272 
01273   /* Time starts at 0 instead of 1920.
01274    * Account for this in older games by adding an offset */
01275   if (IsSavegameVersionBefore(31)) {
01276     Station *st;
01277     Waypoint *wp;
01278     Engine *e;
01279     Industry *i;
01280     Vehicle *v;
01281 
01282     _date += DAYS_TILL_ORIGINAL_BASE_YEAR;
01283     _cur_year += ORIGINAL_BASE_YEAR;
01284 
01285     FOR_ALL_STATIONS(st)  st->build_date      += DAYS_TILL_ORIGINAL_BASE_YEAR;
01286     FOR_ALL_WAYPOINTS(wp) wp->build_date      += DAYS_TILL_ORIGINAL_BASE_YEAR;
01287     FOR_ALL_ENGINES(e)    e->intro_date       += DAYS_TILL_ORIGINAL_BASE_YEAR;
01288     FOR_ALL_COMPANIES(c)  c->inaugurated_year += ORIGINAL_BASE_YEAR;
01289     FOR_ALL_INDUSTRIES(i) i->last_prod_year   += ORIGINAL_BASE_YEAR;
01290 
01291     FOR_ALL_VEHICLES(v) {
01292       v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
01293       v->build_year += ORIGINAL_BASE_YEAR;
01294     }
01295   }
01296 
01297   /* From 32 on we save the industry who made the farmland.
01298    *  To give this prettyness to old savegames, we remove all farmfields and
01299    *  plant new ones. */
01300   if (IsSavegameVersionBefore(32)) {
01301     Industry *i;
01302 
01303     for (TileIndex t = 0; t < map_size; t++) {
01304       if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
01305         /* remove fields */
01306         MakeClear(t, CLEAR_GRASS, 3);
01307       } else if (IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES)) {
01308         /* remove fences around fields */
01309         SetFenceSE(t, 0);
01310         SetFenceSW(t, 0);
01311       }
01312     }
01313 
01314     FOR_ALL_INDUSTRIES(i) {
01315       uint j;
01316 
01317       if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
01318         for (j = 0; j != 50; j++) PlantRandomFarmField(i);
01319       }
01320     }
01321   }
01322 
01323   /* Setting no refit flags to all orders in savegames from before refit in orders were added */
01324   if (IsSavegameVersionBefore(36)) {
01325     Order *order;
01326     Vehicle *v;
01327 
01328     FOR_ALL_ORDERS(order) {
01329       order->SetRefit(CT_NO_REFIT);
01330     }
01331 
01332     FOR_ALL_VEHICLES(v) {
01333       v->current_order.SetRefit(CT_NO_REFIT);
01334     }
01335   }
01336 
01337   /* from version 38 we have optional elrails, since we cannot know the
01338    * preference of a user, let elrails enabled; it can be disabled manually */
01339   if (IsSavegameVersionBefore(38)) _settings_game.vehicle.disable_elrails = false;
01340   /* do the same as when elrails were enabled/disabled manually just now */
01341   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
01342   InitializeRailGUI();
01343 
01344   /* From version 53, the map array was changed for house tiles to allow
01345    * space for newhouses grf features. A new byte, m7, was also added. */
01346   if (IsSavegameVersionBefore(53)) {
01347     for (TileIndex t = 0; t < map_size; t++) {
01348       if (IsTileType(t, MP_HOUSE)) {
01349         if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
01350           /* Move the construction stage from m3[7..6] to m5[5..4].
01351            * The construction counter does not have to move. */
01352           SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
01353           SB(_m[t].m3, 6, 2, 0);
01354 
01355           /* The "house is completed" bit is now in m6[2]. */
01356           SetHouseCompleted(t, false);
01357         } else {
01358           /* The "lift has destination" bit has been moved from
01359            * m5[7] to m7[0]. */
01360           SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
01361           ClrBit(_m[t].m5, 7);
01362 
01363           /* The "lift is moving" bit has been removed, as it does
01364            * the same job as the "lift has destination" bit. */
01365           ClrBit(_m[t].m1, 7);
01366 
01367           /* The position of the lift goes from m1[7..0] to m6[7..2],
01368            * making m1 totally free, now. The lift position does not
01369            * have to be a full byte since the maximum value is 36. */
01370           SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
01371 
01372           _m[t].m1 = 0;
01373           _m[t].m3 = 0;
01374           SetHouseCompleted(t, true);
01375         }
01376       }
01377     }
01378   }
01379 
01380   /* Check and update house and town values */
01381   UpdateHousesAndTowns();
01382 
01383   if (IsSavegameVersionBefore(43)) {
01384     for (TileIndex t = 0; t < map_size; t++) {
01385       if (IsTileType(t, MP_INDUSTRY)) {
01386         switch (GetIndustryGfx(t)) {
01387           case GFX_POWERPLANT_SPARKS:
01388             _m[t].m3 = GB(_m[t].m1, 2, 5);
01389             break;
01390 
01391           case GFX_OILWELL_ANIMATED_1:
01392           case GFX_OILWELL_ANIMATED_2:
01393           case GFX_OILWELL_ANIMATED_3:
01394             _m[t].m3 = GB(_m[t].m1, 0, 2);
01395             break;
01396 
01397           case GFX_COAL_MINE_TOWER_ANIMATED:
01398           case GFX_COPPER_MINE_TOWER_ANIMATED:
01399           case GFX_GOLD_MINE_TOWER_ANIMATED:
01400              _m[t].m3 = _m[t].m1;
01401              break;
01402 
01403           default: // No animation states to change
01404             break;
01405         }
01406       }
01407     }
01408   }
01409 
01410   if (IsSavegameVersionBefore(45)) {
01411     Vehicle *v;
01412     /* Originally just the fact that some cargo had been paid for was
01413      * stored to stop people cheating and cashing in several times. This
01414      * wasn't enough though as it was cleared when the vehicle started
01415      * loading again, even if it didn't actually load anything, so now the
01416      * amount that has been paid is stored. */
01417     FOR_ALL_VEHICLES(v) {
01418       ClrBit(v->vehicle_flags, 2);
01419     }
01420   }
01421 
01422   /* Buoys do now store the owner of the previous water tile, which can never
01423    * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
01424   if (IsSavegameVersionBefore(46)) {
01425     Waypoint *wp;
01426     FOR_ALL_WAYPOINTS(wp) {
01427       if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
01428     }
01429   }
01430 
01431   if (IsSavegameVersionBefore(50)) {
01432     Aircraft *v;
01433     /* Aircraft units changed from 8 mph to 1 km-ish/h */
01434     FOR_ALL_AIRCRAFT(v) {
01435       if (v->subtype <= AIR_AIRCRAFT) {
01436         const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
01437         v->cur_speed *= 128;
01438         v->cur_speed /= 10;
01439         v->acceleration = avi->acceleration;
01440       }
01441     }
01442   }
01443 
01444   if (IsSavegameVersionBefore(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
01445 
01446   if (IsSavegameVersionBefore(52)) {
01447     for (TileIndex t = 0; t < map_size; t++) {
01448       if (IsStatueTile(t)) {
01449         _m[t].m2 = CalcClosestTownFromTile(t)->index;
01450       }
01451     }
01452   }
01453 
01454   /* A setting containing the proportion of towns that grow twice as
01455    * fast was added in version 54. From version 56 this is now saved in the
01456    * town as cities can be built specifically in the scenario editor. */
01457   if (IsSavegameVersionBefore(56)) {
01458     Town *t;
01459 
01460     FOR_ALL_TOWNS(t) {
01461       if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
01462         t->larger_town = true;
01463       }
01464     }
01465   }
01466 
01467   if (IsSavegameVersionBefore(57)) {
01468     Vehicle *v;
01469     /* Added a FIFO queue of vehicles loading at stations */
01470     FOR_ALL_VEHICLES(v) {
01471       if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) &&  // for all locs
01472           !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
01473           v->current_order.IsType(OT_LOADING)) {         // loading
01474         Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
01475 
01476         /* The loading finished flag is *only* set when actually completely
01477          * finished. Because the vehicle is loading, it is not finished. */
01478         ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
01479       }
01480     }
01481   } else if (IsSavegameVersionBefore(59)) {
01482     /* For some reason non-loading vehicles could be in the station's loading vehicle list */
01483 
01484     Station *st;
01485     FOR_ALL_STATIONS(st) {
01486       std::list<Vehicle *>::iterator iter;
01487       for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
01488         Vehicle *v = *iter;
01489         iter++;
01490         if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
01491       }
01492     }
01493   }
01494 
01495   if (IsSavegameVersionBefore(58)) {
01496     /* Setting difficulty industry_density other than zero get bumped to +1
01497      * since a new option (very low at position 1) has been added */
01498     if (_settings_game.difficulty.industry_density > 0) {
01499       _settings_game.difficulty.industry_density++;
01500     }
01501 
01502     /* Same goes for number of towns, although no test is needed, just an increment */
01503     _settings_game.difficulty.number_towns++;
01504   }
01505 
01506   if (IsSavegameVersionBefore(64)) {
01507     /* copy the signal type/variant and move signal states bits */
01508     for (TileIndex t = 0; t < map_size; t++) {
01509       if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
01510         SetSignalStates(t, GB(_m[t].m2, 4, 4));
01511         SetSignalVariant(t, INVALID_TRACK, GetSignalVariant(t, TRACK_X));
01512         SetSignalType(t, INVALID_TRACK, GetSignalType(t, TRACK_X));
01513         ClrBit(_m[t].m2, 7);
01514       }
01515     }
01516   }
01517 
01518   if (IsSavegameVersionBefore(69)) {
01519     /* In some old savegames a bit was cleared when it should not be cleared */
01520     RoadVehicle *rv;
01521     FOR_ALL_ROADVEHICLES(rv) {
01522       if (rv->state == 250 || rv->state == 251) {
01523         SetBit(rv->state, 2);
01524       }
01525     }
01526   }
01527 
01528   if (IsSavegameVersionBefore(70)) {
01529     /* Added variables to support newindustries */
01530     Industry *i;
01531     FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
01532   }
01533 
01534   /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
01535       Replace the owner for those by OWNER_NONE. */
01536   if (IsSavegameVersionBefore(82)) {
01537     for (TileIndex t = 0; t < map_size; t++) {
01538       if (IsTileType(t, MP_WATER) &&
01539           GetWaterTileType(t) == WATER_TILE_CLEAR &&
01540           GetTileOwner(t) == OWNER_WATER &&
01541           TileHeight(t) != 0) {
01542         SetTileOwner(t, OWNER_NONE);
01543       }
01544     }
01545   }
01546 
01547   /*
01548    * Add the 'previous' owner to the ship depots so we can reset it with
01549    * the correct values when it gets destroyed. This prevents that
01550    * someone can remove canals owned by somebody else and it prevents
01551    * making floods using the removal of ship depots.
01552    */
01553   if (IsSavegameVersionBefore(83)) {
01554     for (TileIndex t = 0; t < map_size; t++) {
01555       if (IsShipDepotTile(t)) {
01556         _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
01557       }
01558     }
01559   }
01560 
01561   if (IsSavegameVersionBefore(74)) {
01562     Station *st;
01563     FOR_ALL_STATIONS(st) {
01564       for (CargoID c = 0; c < NUM_CARGO; c++) {
01565         st->goods[c].last_speed = 0;
01566         if (st->goods[c].cargo.Count() != 0) SetBit(st->goods[c].acceptance_pickup, GoodsEntry::GES_PICKUP);
01567       }
01568     }
01569   }
01570 
01571   if (IsSavegameVersionBefore(78)) {
01572     Industry *i;
01573     uint j;
01574     FOR_ALL_INDUSTRIES(i) {
01575       const IndustrySpec *indsp = GetIndustrySpec(i->type);
01576       for (j = 0; j < lengthof(i->produced_cargo); j++) {
01577         i->produced_cargo[j] = indsp->produced_cargo[j];
01578       }
01579       for (j = 0; j < lengthof(i->accepts_cargo); j++) {
01580         i->accepts_cargo[j] = indsp->accepts_cargo[j];
01581       }
01582     }
01583   }
01584 
01585   /* Before version 81, the density of grass was always stored as zero, and
01586    * grassy trees were always drawn fully grassy. Furthermore, trees on rough
01587    * land used to have zero density, now they have full density. Therefore,
01588    * make all grassy/rough land trees have a density of 3. */
01589   if (IsSavegameVersionBefore(81)) {
01590     for (TileIndex t = 0; t < map_size; t++) {
01591       if (GetTileType(t) == MP_TREES) {
01592         TreeGround groundType = (TreeGround)GB(_m[t].m2, 4, 2);
01593         if (groundType != TREE_GROUND_SNOW_DESERT) SB(_m[t].m2, 6, 2, 3);
01594       }
01595     }
01596   }
01597 
01598 
01599   if (IsSavegameVersionBefore(93)) {
01600     /* Rework of orders. */
01601     Order *order;
01602     FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
01603 
01604     Vehicle *v;
01605     FOR_ALL_VEHICLES(v) {
01606       if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && v->orders.list->GetFirstOrder()->IsType(OT_NOTHING)) {
01607         v->orders.list->FreeChain();
01608         v->orders.list = NULL;
01609       }
01610 
01611       v->current_order.ConvertFromOldSavegame();
01612       if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
01613         FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
01614       }
01615     }
01616   } else if (IsSavegameVersionBefore(94)) {
01617     /* Unload and transfer are now mutual exclusive. */
01618     Order *order;
01619     FOR_ALL_ORDERS(order) {
01620       if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
01621         order->SetUnloadType(OUFB_TRANSFER);
01622         order->SetLoadType(OLFB_NO_LOAD);
01623       }
01624     }
01625 
01626     Vehicle *v;
01627     FOR_ALL_VEHICLES(v) {
01628       if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
01629         v->current_order.SetUnloadType(OUFB_TRANSFER);
01630         v->current_order.SetLoadType(OLFB_NO_LOAD);
01631       }
01632     }
01633   }
01634 
01635   if (IsSavegameVersionBefore(84)) {
01636     /* Set all share owners to INVALID_COMPANY for
01637      * 1) all inactive companies
01638      *     (when inactive companies were stored in the savegame - TTD, TTDP and some
01639      *      *really* old revisions of OTTD; else it is already set in InitializeCompanies())
01640      * 2) shares that are owned by inactive companies or self
01641      *     (caused by cheating clients in earlier revisions) */
01642     FOR_ALL_COMPANIES(c) {
01643       for (uint i = 0; i < 4; i++) {
01644         CompanyID company = c->share_owners[i];
01645         if (company == INVALID_COMPANY) continue;
01646         if (!Company::IsValidID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
01647       }
01648     }
01649   }
01650 
01651   /* The water class was moved/unified. */
01652   if (IsSavegameVersionBefore(146)) {
01653     for (TileIndex t = 0; t < map_size; t++) {
01654       switch (GetTileType(t)) {
01655         case MP_STATION:
01656           switch (GetStationType(t)) {
01657             case STATION_OILRIG:
01658             case STATION_DOCK:
01659             case STATION_BUOY:
01660               SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
01661               SB(_m[t].m3, 0, 2, 0);
01662               break;
01663 
01664             default:
01665               SetWaterClass(t, WATER_CLASS_INVALID);
01666               break;
01667           }
01668           break;
01669 
01670         case MP_WATER:
01671           SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
01672           SB(_m[t].m3, 0, 2, 0);
01673           break;
01674 
01675         case MP_OBJECT:
01676           SetWaterClass(t, WATER_CLASS_INVALID);
01677           break;
01678 
01679         default:
01680           /* No water class. */
01681           break;
01682       }
01683     }
01684   }
01685 
01686   if (IsSavegameVersionBefore(86)) {
01687     for (TileIndex t = 0; t < map_size; t++) {
01688       /* Move river flag and update canals to use water class */
01689       if (IsTileType(t, MP_WATER)) {
01690         if (GetWaterClass(t) != WATER_CLASS_RIVER) {
01691           if (IsWater(t)) {
01692             Owner o = GetTileOwner(t);
01693             if (o == OWNER_WATER) {
01694               MakeSea(t);
01695             } else {
01696               MakeCanal(t, o, Random());
01697             }
01698           } else if (IsShipDepot(t)) {
01699             Owner o = (Owner)_m[t].m4; // Original water owner
01700             SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
01701           }
01702         }
01703       }
01704     }
01705 
01706     /* Update locks, depots, docks and buoys to have a water class based
01707      * on its neighbouring tiles. Done after river and canal updates to
01708      * ensure neighbours are correct. */
01709     for (TileIndex t = 0; t < map_size; t++) {
01710       if (GetTileSlope(t, NULL) != SLOPE_FLAT) continue;
01711 
01712       if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
01713       if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
01714     }
01715   }
01716 
01717   if (IsSavegameVersionBefore(87)) {
01718     for (TileIndex t = 0; t < map_size; t++) {
01719       /* skip oil rigs at borders! */
01720       if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
01721           (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
01722         /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
01723          * This conversion has to be done before buoys with invalid owner are removed. */
01724         SetWaterClass(t, WATER_CLASS_SEA);
01725       }
01726 
01727       if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
01728         Owner o = GetTileOwner(t);
01729         if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
01730           Backup<CompanyByte> cur_company(_current_company, o, FILE_LINE);
01731           ChangeTileOwner(t, o, INVALID_OWNER);
01732           cur_company.Restore();
01733         }
01734         if (IsBuoyTile(t)) {
01735           /* reset buoy owner to OWNER_NONE in the station struct
01736            * (even if it is owned by active company) */
01737           Waypoint::GetByTile(t)->owner = OWNER_NONE;
01738         }
01739       } else if (IsTileType(t, MP_ROAD)) {
01740         /* works for all RoadTileType */
01741         for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01742           /* update even non-existing road types to update tile owner too */
01743           Owner o = GetRoadOwner(t, rt);
01744           if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rt, OWNER_NONE);
01745         }
01746         if (IsLevelCrossing(t)) {
01747           if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
01748         }
01749       } else if (IsPlainRailTile(t)) {
01750         if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
01751       }
01752     }
01753 
01754     /* Convert old PF settings to new */
01755     if (_settings_game.pf.yapf.rail_use_yapf || IsSavegameVersionBefore(28)) {
01756       _settings_game.pf.pathfinder_for_trains = VPF_YAPF;
01757     } else {
01758       _settings_game.pf.pathfinder_for_trains = VPF_NPF;
01759     }
01760 
01761     if (_settings_game.pf.yapf.road_use_yapf || IsSavegameVersionBefore(28)) {
01762       _settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
01763     } else {
01764       _settings_game.pf.pathfinder_for_roadvehs = VPF_NPF;
01765     }
01766 
01767     if (_settings_game.pf.yapf.ship_use_yapf) {
01768       _settings_game.pf.pathfinder_for_ships = VPF_YAPF;
01769     } else {
01770       _settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
01771     }
01772   }
01773 
01774   if (IsSavegameVersionBefore(88)) {
01775     /* Profits are now with 8 bit fract */
01776     Vehicle *v;
01777     FOR_ALL_VEHICLES(v) {
01778       v->profit_this_year <<= 8;
01779       v->profit_last_year <<= 8;
01780       v->running_ticks = 0;
01781     }
01782   }
01783 
01784   if (IsSavegameVersionBefore(91)) {
01785     /* Increase HouseAnimationFrame from 5 to 7 bits */
01786     for (TileIndex t = 0; t < map_size; t++) {
01787       if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
01788         SB(_m[t].m6, 2, 6, GB(_m[t].m6, 3, 5));
01789         SB(_m[t].m3, 5, 1, 0);
01790       }
01791     }
01792   }
01793 
01794   if (IsSavegameVersionBefore(62)) {
01795     /* Remove all trams from savegames without tram support.
01796      * There would be trams without tram track under causing crashes sooner or later. */
01797     RoadVehicle *v;
01798     FOR_ALL_ROADVEHICLES(v) {
01799       if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
01800         if (_switch_mode_errorstr == INVALID_STRING_ID || _switch_mode_errorstr == STR_NEWGRF_COMPATIBLE_LOAD_WARNING) {
01801           _switch_mode_errorstr = STR_WARNING_LOADGAME_REMOVED_TRAMS;
01802         }
01803         delete v;
01804       }
01805     }
01806   }
01807 
01808   if (IsSavegameVersionBefore(99)) {
01809     for (TileIndex t = 0; t < map_size; t++) {
01810       /* Set newly introduced WaterClass of industry tiles */
01811       if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
01812         SetWaterClassDependingOnSurroundings(t, true);
01813       }
01814       if (IsTileType(t, MP_INDUSTRY)) {
01815         if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
01816           SetWaterClassDependingOnSurroundings(t, true);
01817         } else {
01818           SetWaterClass(t, WATER_CLASS_INVALID);
01819         }
01820       }
01821 
01822       /* Replace "house construction year" with "house age" */
01823       if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
01824         _m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
01825       }
01826     }
01827   }
01828 
01829   /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
01830    * format here, as an old layout wouldn't work properly anyway. To be safe, we
01831    * clear any possible PBS reservations as well. */
01832   if (IsSavegameVersionBefore(100)) {
01833     for (TileIndex t = 0; t < map_size; t++) {
01834       switch (GetTileType(t)) {
01835         case MP_RAILWAY:
01836           if (HasSignals(t)) {
01837             /* move the signal variant */
01838             SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
01839             SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
01840             ClrBit(_m[t].m2, 2);
01841             ClrBit(_m[t].m2, 6);
01842           }
01843 
01844           /* Clear PBS reservation on track */
01845           if (IsRailDepot(t)) {
01846             SetDepotReservation(t, false);
01847           } else {
01848             SetTrackReservation(t, TRACK_BIT_NONE);
01849           }
01850           break;
01851 
01852         case MP_ROAD: // Clear PBS reservation on crossing
01853           if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
01854           break;
01855 
01856         case MP_STATION: // Clear PBS reservation on station
01857           if (HasStationRail(t)) SetRailStationReservation(t, false);
01858           break;
01859 
01860         case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/birdges
01861           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
01862           break;
01863 
01864         default: break;
01865       }
01866     }
01867   }
01868 
01869   /* Reserve all tracks trains are currently on. */
01870   if (IsSavegameVersionBefore(101)) {
01871     const Train *t;
01872     FOR_ALL_TRAINS(t) {
01873       if (t->First() == t) t->ReserveTrackUnderConsist();
01874     }
01875   }
01876 
01877   if (IsSavegameVersionBefore(102)) {
01878     for (TileIndex t = 0; t < map_size; t++) {
01879       /* Now all crossings should be in correct state */
01880       if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
01881     }
01882   }
01883 
01884   if (IsSavegameVersionBefore(103)) {
01885     /* Non-town-owned roads now store the closest town */
01886     UpdateNearestTownForRoadTiles(false);
01887 
01888     /* signs with invalid owner left from older savegames */
01889     Sign *si;
01890     FOR_ALL_SIGNS(si) {
01891       if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
01892     }
01893 
01894     /* Station can get named based on an industry type, but the current ones
01895      * are not, so mark them as if they are not named by an industry. */
01896     Station *st;
01897     FOR_ALL_STATIONS(st) {
01898       st->indtype = IT_INVALID;
01899     }
01900   }
01901 
01902   if (IsSavegameVersionBefore(104)) {
01903     Aircraft *a;
01904     FOR_ALL_AIRCRAFT(a) {
01905       /* Set engine_type of shadow and rotor */
01906       if (!a->IsNormalAircraft()) {
01907         a->engine_type = a->First()->engine_type;
01908       }
01909     }
01910 
01911     /* More companies ... */
01912     Company *c;
01913     FOR_ALL_COMPANIES(c) {
01914       if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
01915     }
01916 
01917     Engine *e;
01918     FOR_ALL_ENGINES(e) {
01919       if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
01920     }
01921 
01922     Town *t;
01923     FOR_ALL_TOWNS(t) {
01924       if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
01925       for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01926     }
01927   }
01928 
01929   if (IsSavegameVersionBefore(112)) {
01930     for (TileIndex t = 0; t < map_size; t++) {
01931       /* Check for HQ bit being set, instead of using map accessor,
01932        * since we've already changed it code-wise */
01933       if (IsTileType(t, MP_OBJECT) && HasBit(_m[t].m5, 7)) {
01934         /* Move size and part identification of HQ out of the m5 attribute,
01935          * on new locations */
01936         _m[t].m3 = GB(_m[t].m5, 0, 5);
01937         _m[t].m5 = OBJECT_HQ;
01938       }
01939     }
01940   }
01941   if (IsSavegameVersionBefore(144)) {
01942     for (TileIndex t = 0; t < map_size; t++) {
01943       if (!IsTileType(t, MP_OBJECT)) continue;
01944 
01945       /* Reordering/generalisation of the object bits. */
01946       ObjectType type = GetObjectType(t);
01947       SB(_m[t].m6, 2, 4, type == OBJECT_HQ ? GB(_m[t].m3, 2, 3) : 0);
01948       _m[t].m3 = type == OBJECT_HQ ? GB(_m[t].m3, 1, 1) | GB(_m[t].m3, 0, 1) << 4 : 0;
01949 
01950       /* Make sure those bits are clear as well! */
01951       _m[t].m4 = 0;
01952       _me[t].m7 = 0;
01953     }
01954   }
01955 
01956   if (IsSavegameVersionBefore(KEEP_COMPATIBLE_1_SV) && Object::GetNumItems() == 0) {
01957     /* Make real objects for object tiles. */
01958     for (TileIndex t = 0; t < map_size; t++) {
01959       if (!IsTileType(t, MP_OBJECT)) continue;
01960 
01961       if (Town::GetNumItems() == 0) {
01962         /* No towns, so remove all objects! */
01963         DoClearSquare(t);
01964       } else {
01965         uint offset = _m[t].m3;
01966 
01967         /* Also move the animation state. */
01968         _m[t].m3 = GB(_m[t].m6, 2, 4);
01969         SB(_m[t].m6, 2, 4, 0);
01970 
01971         if (offset == 0) {
01972           /* No offset, so make the object. */
01973           ObjectType type = GetObjectType(t);
01974           int size = type == OBJECT_HQ ? 2 : 1;
01975 
01976           if (!Object::CanAllocateItem()) {
01977             /* Nice... you managed to place 64k lighthouses and
01978              * antennae on the map... boohoo. */
01979             SlError(STR_ERROR_TOO_MANY_OBJECTS);
01980           }
01981 
01982           Object *o = new Object();
01983           o->location.tile = t;
01984           o->location.w    = size;
01985           o->location.h    = size;
01986           o->build_date    = _date;
01987           o->town          = type == OBJECT_STATUE ? Town::Get(_m[t].m2) : CalcClosestTownFromTile(t, UINT_MAX);
01988           _m[t].m2 = o->index;
01989           Object::IncTypeCount(type);
01990         } else {
01991           /* We're at an offset, so get the ID from our "root". */
01992           TileIndex northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
01993           assert(IsTileType(northern_tile, MP_OBJECT));
01994           _m[t].m2 = _m[northern_tile].m2;
01995         }
01996       }
01997     }
01998   }
01999 
02000   if (IsSavegameVersionBefore(113)) {
02001     /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
02002     if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
02003       _settings_game.economy.allow_town_roads = false;
02004       _settings_game.economy.town_layout = TL_BETTER_ROADS;
02005     } else {
02006       _settings_game.economy.allow_town_roads = true;
02007       _settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
02008     }
02009 
02010     /* Initialize layout of all towns. Older versions were using different
02011      * generator for random town layout, use it if needed. */
02012     Town *t;
02013     FOR_ALL_TOWNS(t) {
02014       if (_settings_game.economy.town_layout != TL_RANDOM) {
02015         t->layout = _settings_game.economy.town_layout;
02016         continue;
02017       }
02018 
02019       /* Use old layout randomizer code */
02020       byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
02021       switch (layout) {
02022         default: break;
02023         case 5: layout = 1; break;
02024         case 0: layout = 2; break;
02025       }
02026       t->layout = layout - 1;
02027     }
02028   }
02029 
02030   if (IsSavegameVersionBefore(114)) {
02031     /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
02032      * The conversion affects oil rigs and buoys too, but it doesn't matter as
02033      * they have st->owner == OWNER_NONE already. */
02034     Station *st;
02035     FOR_ALL_STATIONS(st) {
02036       if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
02037     }
02038   }
02039 
02040   /* Trains could now stop in a specific location. */
02041   if (IsSavegameVersionBefore(117)) {
02042     Order *o;
02043     FOR_ALL_ORDERS(o) {
02044       if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
02045     }
02046   }
02047 
02048   if (IsSavegameVersionBefore(120)) {
02049     extern VehicleDefaultSettings _old_vds;
02050     Company *c;
02051     FOR_ALL_COMPANIES(c) {
02052       c->settings.vehicle = _old_vds;
02053     }
02054   }
02055 
02056   if (IsSavegameVersionBefore(121)) {
02057     /* Delete small ufos heading for non-existing vehicles */
02058     Vehicle *v;
02059     FOR_ALL_DISASTERVEHICLES(v) {
02060       if (v->subtype == 2/*ST_SMALL_UFO*/ && v->current_order.GetDestination() != 0) {
02061         const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
02062         if (u == NULL || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
02063           delete v;
02064         }
02065       }
02066     }
02067 
02068     /* We didn't store cargo payment yet, so make them for vehicles that are
02069      * currently at a station and loading/unloading. If they don't get any
02070      * payment anymore they just removed in the next load/unload cycle.
02071      * However, some 0.7 versions might have cargo payment. For those we just
02072      * add cargopayment for the vehicles that don't have it.
02073      */
02074     Station *st;
02075     FOR_ALL_STATIONS(st) {
02076       std::list<Vehicle *>::iterator iter;
02077       for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
02078         /* There are always as many CargoPayments as Vehicles. We need to make the
02079          * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
02080         assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
02081         assert(CargoPayment::CanAllocateItem());
02082         Vehicle *v = *iter;
02083         if (v->cargo_payment == NULL) v->cargo_payment = new CargoPayment(v);
02084       }
02085     }
02086   }
02087 
02088   if (IsSavegameVersionBefore(122)) {
02089     /* Animated tiles would sometimes not be actually animated or
02090      * in case of old savegames duplicate. */
02091 
02092     extern TileIndex *_animated_tile_list;
02093     extern uint _animated_tile_count;
02094 
02095     for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
02096       /* Remove if tile is not animated */
02097       bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == NULL;
02098 
02099       /* and remove if duplicate */
02100       for (uint j = 0; !remove && j < i; j++) {
02101         remove = _animated_tile_list[i] == _animated_tile_list[j];
02102       }
02103 
02104       if (remove) {
02105         DeleteAnimatedTile(_animated_tile_list[i]);
02106       } else {
02107         i++;
02108       }
02109     }
02110   }
02111 
02112   if (IsSavegameVersionBefore(124) && !IsSavegameVersionBefore(1)) {
02113     /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
02114     Waypoint *wp;
02115     FOR_ALL_WAYPOINTS(wp) {
02116       if (wp->facilities & FACIL_TRAIN) {
02117         wp->train_station.tile = wp->xy;
02118         wp->train_station.w = 1;
02119         wp->train_station.h = 1;
02120       } else {
02121         wp->train_station.tile = INVALID_TILE;
02122         wp->train_station.w = 0;
02123         wp->train_station.h = 0;
02124       }
02125     }
02126   }
02127 
02128   if (IsSavegameVersionBefore(125)) {
02129     /* Convert old subsidies */
02130     Subsidy *s;
02131     FOR_ALL_SUBSIDIES(s) {
02132       if (s->remaining < 12) {
02133         /* Converting nonawarded subsidy */
02134         s->remaining = 12 - s->remaining; // convert "age" to "remaining"
02135         s->awarded = INVALID_COMPANY; // not awarded to anyone
02136         const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
02137         switch (cs->town_effect) {
02138           case TE_PASSENGERS:
02139           case TE_MAIL:
02140             /* Town -> Town */
02141             s->src_type = s->dst_type = ST_TOWN;
02142             if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
02143             break;
02144           case TE_GOODS:
02145           case TE_FOOD:
02146             /* Industry -> Town */
02147             s->src_type = ST_INDUSTRY;
02148             s->dst_type = ST_TOWN;
02149             if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
02150             break;
02151           default:
02152             /* Industry -> Industry */
02153             s->src_type = s->dst_type = ST_INDUSTRY;
02154             if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
02155             break;
02156         }
02157       } else {
02158         /* Do our best for awarded subsidies. The original source or destination industry
02159          * can't be determined anymore for awarded subsidies, so invalidate them.
02160          * Town -> Town subsidies are converted using simple heuristic */
02161         s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
02162         const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
02163         switch (cs->town_effect) {
02164           case TE_PASSENGERS:
02165           case TE_MAIL: {
02166             /* Town -> Town */
02167             const Station *ss = Station::GetIfValid(s->src);
02168             const Station *sd = Station::GetIfValid(s->dst);
02169             if (ss != NULL && sd != NULL && ss->owner == sd->owner &&
02170                 Company::IsValidID(ss->owner)) {
02171               s->src_type = s->dst_type = ST_TOWN;
02172               s->src = ss->town->index;
02173               s->dst = sd->town->index;
02174               s->awarded = ss->owner;
02175               continue;
02176             }
02177             break;
02178           }
02179           default:
02180             break;
02181         }
02182       }
02183       /* Awarded non-town subsidy or invalid source/destination, invalidate */
02184       delete s;
02185     }
02186   }
02187 
02188   if (IsSavegameVersionBefore(126)) {
02189     /* Recompute inflation based on old unround loan limit
02190      * Note: Max loan is 500000. With an inflation of 4% across 170 years
02191      *       that results in a max loan of about 0.7 * 2^31.
02192      *       So taking the 16 bit fractional part into account there are plenty of bits left
02193      *       for unmodified savegames ...
02194      */
02195     uint64 aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
02196 
02197     /* ... well, just clamp it then. */
02198     if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
02199 
02200     /* Simulate the inflation, so we also get the payment inflation */
02201     while (_economy.inflation_prices < aimed_inflation) {
02202       AddInflation(false);
02203     }
02204   }
02205 
02206   if (IsSavegameVersionBefore(127)) {
02207     Station *st;
02208     FOR_ALL_STATIONS(st) UpdateStationAcceptance(st, false);
02209   }
02210 
02211   if (IsSavegameVersionBefore(128)) {
02212     const Depot *d;
02213     FOR_ALL_DEPOTS(d) {
02214       _m[d->xy].m2 = d->index;
02215       if (IsTileType(d->xy, MP_WATER)) _m[GetOtherShipDepotTile(d->xy)].m2 = d->index;
02216     }
02217   }
02218 
02219   /* The behaviour of force_proceed has been changed. Now
02220    * it counts signals instead of some random time out. */
02221   if (IsSavegameVersionBefore(131)) {
02222     Train *t;
02223     FOR_ALL_TRAINS(t) {
02224       if (t->force_proceed != TFP_NONE) {
02225         t->force_proceed = TFP_STUCK;
02226       }
02227     }
02228   }
02229 
02230   /* The bits for the tree ground and tree density have
02231    * been swapped (m2 bits 7..6 and 5..4. */
02232   if (IsSavegameVersionBefore(135)) {
02233     for (TileIndex t = 0; t < map_size; t++) {
02234       if (IsTileType(t, MP_CLEAR)) {
02235         if (GetRawClearGround(t) == CLEAR_SNOW) {
02236           SetClearGroundDensity(t, CLEAR_GRASS, GetClearDensity(t));
02237           SetBit(_m[t].m3, 4);
02238         } else {
02239           ClrBit(_m[t].m3, 4);
02240         }
02241       }
02242       if (IsTileType(t, MP_TREES)) {
02243         uint density = GB(_m[t].m2, 6, 2);
02244         uint ground = GB(_m[t].m2, 4, 2);
02245         uint counter = GB(_m[t].m2, 0, 4);
02246         _m[t].m2 = ground << 6 | density << 4 | counter;
02247       }
02248     }
02249   }
02250 
02251   /* Wait counter and load/unload ticks got split. */
02252   if (IsSavegameVersionBefore(136)) {
02253     Aircraft *a;
02254     FOR_ALL_AIRCRAFT(a) {
02255       a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
02256     }
02257 
02258     Train *t;
02259     FOR_ALL_TRAINS(t) {
02260       t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
02261     }
02262   }
02263 
02264   /* Airport tile animation uses animation frame instead of other graphics id */
02265   if (IsSavegameVersionBefore(137)) {
02266     struct AirportTileConversion {
02267       byte old_start;
02268       byte num_frames;
02269     };
02270     static const AirportTileConversion atc[] = {
02271       {31,  12}, // APT_RADAR_GRASS_FENCE_SW
02272       {50,   4}, // APT_GRASS_FENCE_NE_FLAG
02273       {62,   2}, // 1 unused tile
02274       {66,  12}, // APT_RADAR_FENCE_SW
02275       {78,  12}, // APT_RADAR_FENCE_NE
02276       {101, 10}, // 9 unused tiles
02277       {111,  8}, // 7 unused tiles
02278       {119, 15}, // 14 unused tiles (radar)
02279       {140,  4}, // APT_GRASS_FENCE_NE_FLAG_2
02280     };
02281     for (TileIndex t = 0; t < map_size; t++) {
02282       if (IsAirportTile(t)) {
02283         StationGfx old_gfx = GetStationGfx(t);
02284         byte offset = 0;
02285         for (uint i = 0; i < lengthof(atc); i++) {
02286           if (old_gfx < atc[i].old_start) {
02287             SetStationGfx(t, old_gfx - offset);
02288             break;
02289           }
02290           if (old_gfx < atc[i].old_start + atc[i].num_frames) {
02291             SetAnimationFrame(t, old_gfx - atc[i].old_start);
02292             SetStationGfx(t, atc[i].old_start - offset);
02293             break;
02294           }
02295           offset += atc[i].num_frames - 1;
02296         }
02297       }
02298     }
02299   }
02300 
02301   if (IsSavegameVersionBefore(140)) {
02302     Station *st;
02303     FOR_ALL_STATIONS(st) {
02304       if (st->airport.tile != INVALID_TILE) {
02305         st->airport.w = st->airport.GetSpec()->size_x;
02306         st->airport.h = st->airport.GetSpec()->size_y;
02307       }
02308     }
02309   }
02310 
02311   if (IsSavegameVersionBefore(141)) {
02312     for (TileIndex t = 0; t < map_size; t++) {
02313       /* Reset tropic zone for VOID tiles, they shall not have any. */
02314       if (IsTileType(t, MP_VOID)) SetTropicZone(t, TROPICZONE_NORMAL);
02315     }
02316 
02317     /* We need to properly number/name the depots.
02318      * The first step is making sure none of the depots uses the
02319      * 'default' names, after that we can assign the names. */
02320     Depot *d;
02321     FOR_ALL_DEPOTS(d) d->town_cn = UINT16_MAX;
02322 
02323     FOR_ALL_DEPOTS(d) MakeDefaultName(d);
02324   }
02325 
02326   if (IsSavegameVersionBefore(142)) {
02327     Depot *d;
02328     FOR_ALL_DEPOTS(d) d->build_date = _date;
02329   }
02330 
02331   /* In old versions it was possible to remove an airport while a plane was
02332    * taking off or landing. This gives all kind of problems when building
02333    * another airport in the same station so we don't allow that anymore.
02334    * For old savegames with such aircraft we just throw them in the air and
02335    * treat the aircraft like they were flying already. */
02336   if (IsSavegameVersionBefore(146)) {
02337     Aircraft *v;
02338     FOR_ALL_AIRCRAFT(v) {
02339       if (!v->IsNormalAircraft()) continue;
02340       Station *st = GetTargetAirportIfValid(v);
02341       if (st == NULL && v->state != FLYING) {
02342         v->state = FLYING;
02343         UpdateAircraftCache(v);
02344         AircraftNextAirportPos_and_Order(v);
02345         /* get aircraft back on running altitude */
02346         if ((v->vehstatus & VS_CRASHED) == 0) SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftMaxAltitude(v->x_pos, v->y_pos, 0));
02347       }
02348     }
02349   }
02350 
02351   /* Move the animation frame to the same location (m7) for all objects. */
02352   if (IsSavegameVersionBefore(KEEP_COMPATIBLE_1_SV)) {
02353     for (TileIndex t = 0; t < map_size; t++) {
02354       switch (GetTileType(t)) {
02355         case MP_HOUSE:
02356           if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
02357             uint per_proc = _me[t].m7;
02358             _me[t].m7 = GB(_m[t].m6, 2, 6) | (GB(_m[t].m3, 5, 1) << 6);
02359             SB(_m[t].m3, 5, 1, 0);
02360             SB(_m[t].m6, 2, 6, min(per_proc, 63));
02361           }
02362           break;
02363 
02364         case MP_INDUSTRY: {
02365           uint rand = _me[t].m7;
02366           _me[t].m7 = _m[t].m3;
02367           _m[t].m3 = rand;
02368           break;
02369         }
02370 
02371         case MP_OBJECT:
02372           _me[t].m7 = _m[t].m3;
02373           _m[t].m3 = 0;
02374           break;
02375 
02376         default:
02377           /* For stations/airports it's already at m7 */
02378           break;
02379       }
02380     }
02381   }
02382 
02383   /* Add (random) colour to all objects. */
02384   if (IsSavegameVersionBefore(148) && (!IsSavegameVersionBefore(MORE_HEIGHTLEVEL_SAVEGAME_VERSION))) {
02385     Object *o;
02386     FOR_ALL_OBJECTS(o) {
02387       Owner owner = GetTileOwner(o->location.tile);
02388       o->colour = (owner == OWNER_NONE) ? Random() & 0xF : Company::Get(owner)->livery->colour1;
02389     }
02390   }
02391 
02392   if (IsSavegameVersionBefore(KEEP_COMPATIBLE_3_SV)) {
02393     for (TileIndex t = 0; t < map_size; t++) {
02394       if (!IsTileType(t, MP_STATION)) continue;
02395       if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && GetTileSlope(t, NULL) == SLOPE_FLAT)) {
02396         SetWaterClass(t, WATER_CLASS_INVALID);
02397       }
02398     }
02399 
02400     /* Waypoints with custom name may have a non-unique town_cn,
02401      * renumber those. First set all affected waypoints to the
02402      * highest possible number to get them numbered in the
02403      * order they have in the pool. */
02404     Waypoint *wp;
02405     FOR_ALL_WAYPOINTS(wp) {
02406       if (wp->name != NULL) wp->town_cn = UINT16_MAX;
02407     }
02408 
02409     FOR_ALL_WAYPOINTS(wp) {
02410       if (wp->name != NULL) MakeDefaultName(wp);
02411     }
02412   }
02413 
02414   if (IsSavegameVersionBefore(KEEP_COMPATIBLE_10_SV)) {
02415     _industry_builder.Reset(); // Initialize industry build data.
02416 
02417     /* The moment vehicles go from hidden to visible changed. This means
02418      * that vehicles don't always get visible anymore causing things to
02419      * get messed up just after loading the savegame. This fixes that. */
02420     Vehicle *v;
02421     FOR_ALL_VEHICLES(v) {
02422       /* Not all vehicle types can be inside a tunnel. Furthermore,
02423        * testing IsTunnelTile() for invalid tiles causes a crash. */
02424       if (!v->IsGroundVehicle()) continue;
02425 
02426       /* Is the vehicle in a tunnel? */
02427       if (!IsTunnelTile(v->tile)) continue;
02428 
02429       /* Is the vehicle actually at a tunnel entrance/exit? */
02430       TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
02431       if (!IsTunnelTile(vtile)) continue;
02432 
02433       /* Are we actually in this tunnel? Or maybe a lower tunnel? */
02434       if ((int)GetSlopeZ(v->x_pos, v->y_pos) != v->z_pos) continue;
02435 
02436       /* What way are we going? */
02437       const DiagDirection dir = GetTunnelBridgeDirection(vtile);
02438       const DiagDirection vdir = DirToDiagDir(v->direction);
02439 
02440       /* Have we passed the visibility "switch" state already? */
02441       byte pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
02442       byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
02443       extern const byte _tunnel_visibility_frame[DIAGDIR_END];
02444 
02445       /* Should the vehicle be hidden or not? */
02446       bool hidden;
02447       if (dir == vdir) { // Entering tunnel
02448         hidden = frame >= _tunnel_visibility_frame[dir];
02449         v->tile = vtile;
02450       } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
02451         hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
02452         /* v->tile changes at the moment when the vehicle leaves the tunnel. */
02453         v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
02454       } else {
02455         /* We could get here in two cases:
02456          * - for road vehicles, it is reversing at the end of the tunnel
02457          * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
02458          * Whatever case it is, do not change anything and use the old values.
02459          * Especially changing RV's state would break its reversing in the middle. */
02460         continue;
02461       }
02462 
02463       if (hidden) {
02464         v->vehstatus |= VS_HIDDEN;
02465 
02466         switch (v->type) {
02467           case VEH_TRAIN: Train::From(v)->track       = TRACK_BIT_WORMHOLE; break;
02468           case VEH_ROAD:  RoadVehicle::From(v)->state = RVSB_WORMHOLE;      break;
02469           default: NOT_REACHED();
02470         }
02471       } else {
02472         v->vehstatus &= ~VS_HIDDEN;
02473 
02474         switch (v->type) {
02475           case VEH_TRAIN: Train::From(v)->track       = DiagDirToDiagTrackBits(vdir); break;
02476           case VEH_ROAD:  RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
02477           default: NOT_REACHED();
02478         }
02479       }
02480     }
02481   }
02482 
02483   if (IsSavegameVersionBefore(KEEP_COMPATIBLE_11_SV)) {
02484     RoadVehicle *rv;
02485     FOR_ALL_ROADVEHICLES(rv) {
02486       if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
02487 
02488       bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
02489       if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
02490         extern const byte _road_stop_stop_frame[];
02491         SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > _road_stop_stop_frame[rv->state - RVSB_IN_ROAD_STOP + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)]);
02492       } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
02493         SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
02494       }
02495     }
02496   }
02497 
02498   if (IsSavegameVersionBefore(DAYLENGHT_SL)) {
02499     /* Make sure the cheat to not devide income by daylengh factor is off.
02500      * When cheats were used in an older savegame the code may get confused and enable it.*/
02501     _cheats.daylength_income.value = false;
02502   }
02503 
02504   if (IsSavegameVersionBefore(IS_SL)) {
02505     Company *c;
02506     FOR_ALL_COMPANIES(c) {
02507       /* yearly_expenses has 3*15 entries now, saveload code gave us 3*13.
02508        * Move the old data to the right place in the new array and clear the new data.
02509        * The move has to be done in reverse order (first 2, then 1). */
02510       MemMoveT(&c->yearly_expenses[2][0], &c->yearly_expenses[1][11], 13);
02511       MemMoveT(&c->yearly_expenses[1][0], &c->yearly_expenses[0][13], 13);
02512       /* Clear the old location of just-moved data, so sharing income/expenses is set to 0 */
02513       MemSetT(&c->yearly_expenses[0][13], 0, 2);
02514       MemSetT(&c->yearly_expenses[1][13], 0, 2);
02515     }
02516   }
02517 
02518   if (IsSavegameVersionBefore(KEEP_COMPATIBLE_17_SV)) {
02519     /* The train's pathfinder lost flag got moved. */
02520     Train *t;
02521     FOR_ALL_TRAINS(t) {
02522       if (!HasBit(t->flags, 5)) continue;
02523 
02524       ClrBit(t->flags, 5);
02525       SetBit(t->vehicle_flags, VF_PATHFINDER_LOST);
02526     }
02527 
02528     /* Introduced terraform/clear limits. */
02529     Company *c;
02530     FOR_ALL_COMPANIES(c) {
02531       c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
02532       c->clear_limit     = _settings_game.construction.clear_frame_burst << 16;
02533     }
02534   }
02535 
02536   if (IsSavegameVersionBefore(KEEP_COMPATIBLE_16_SV)) {
02537     Vehicle *v;
02538     FOR_ALL_VEHICLES(v) {
02539       switch (v->type) {
02540         case VEH_TRAIN: {
02541           Train *t = Train::From(v);
02542 
02543           /* Clear old GOINGUP / GOINGDOWN flags.
02544            * It was changed in savegame version 139, but savegame
02545            * version 158 doesn't use these bits, so it doesn't hurt
02546            * to clear them unconditionally. */
02547           ClrBit(t->flags, 1);
02548           ClrBit(t->flags, 2);
02549 
02550           /* Clear both bits first. */
02551           ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
02552           ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
02553 
02554           /* Crashed vehicles can't be going up/down. */
02555           if (t->vehstatus & VS_CRASHED) break;
02556 
02557           /* Only X/Y tracks can be sloped. */
02558           if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
02559 
02560           t->gv_flags |= FixVehicleInclination(t, t->direction);
02561           break;
02562         }
02563         case VEH_ROAD: {
02564           RoadVehicle *rv = RoadVehicle::From(v);
02565           ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
02566           ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
02567 
02568           /* Crashed vehicles can't be going up/down. */
02569           if (rv->vehstatus & VS_CRASHED) break;
02570 
02571           if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
02572 
02573           TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, rv->compatible_roadtypes);
02574           TrackBits trackbits = TrackStatusToTrackBits(ts);
02575 
02576           /* Only X/Y tracks can be sloped. */
02577           if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
02578 
02579           Direction dir = rv->direction;
02580 
02581           /* Test if we are reversing. */
02582           Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
02583           if (AxisToDirection(a) != dir &&
02584               AxisToDirection(a) != ReverseDir(dir)) {
02585             /* When reversing, the road vehicle is on the edge of the tile,
02586              * so it can be safely compared to the middle of the tile. */
02587             dir = INVALID_DIR;
02588           }
02589 
02590           rv->gv_flags |= FixVehicleInclination(rv, dir);
02591           break;
02592         }
02593         case VEH_SHIP:
02594           break;
02595 
02596         default:
02597           continue;
02598       }
02599 
02600       if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
02601         /* In old versions, z_pos was 1 unit lower on bridge heads.
02602          * However, this invalid state could be converted to new savegames
02603          * by loading and saving the game in a new version. */
02604         v->z_pos = GetSlopeZ(v->x_pos, v->y_pos);
02605         DiagDirection dir = GetTunnelBridgeDirection(v->tile);
02606         if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
02607             v->direction != DiagDirToDir(dir)) {
02608           /* If the train has left the bridge, it shouldn't have
02609            * track == TRACK_BIT_WORMHOLE - this could happen
02610            * when the train was reversed while on the last "tick"
02611            * on the ramp before leaving the ramp to the bridge. */
02612           Train::From(v)->track = DiagDirToDiagTrackBits(dir);
02613         }
02614       }
02615 
02616       /* If the vehicle is really above v->tile (not in a wormhole),
02617        * it should have set v->z_pos correctly. */
02618       assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == (int)GetSlopeZ(v->x_pos, v->y_pos));
02619     }
02620 
02621     /* Fill Vehicle::cur_real_order_index */
02622     FOR_ALL_VEHICLES(v) {
02623       if (!v->IsPrimaryVehicle()) continue;
02624 
02625       /* Older versions are less strict with indices being in range and fix them on the fly */
02626       if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
02627 
02628       v->cur_real_order_index = v->cur_implicit_order_index;
02629       v->UpdateRealOrderIndex();
02630     }
02631   }
02632 
02633   if (IsSavegameVersionBefore(KEEP_COMPATIBLE_17_SV)) {
02634     /* If the savegame is old (before version 100), then the value of 255
02635      * for these settings did not mean "disabled". As such everything
02636      * before then did reverse.
02637      * To simplify stuff we disable all turning around or we do not
02638      * disable anything at all. So, if some reversing was disabled we
02639      * will keep reversing disabled, otherwise it'll be turned on. */
02640     _settings_game.pf.reverse_at_signals = IsSavegameVersionBefore(100) || (_settings_game.pf.wait_oneway_signal != 255 && _settings_game.pf.wait_twoway_signal != 255 && _settings_game.pf.wait_for_pbs_path != 255);
02641 
02642     Train *t;
02643     FOR_ALL_TRAINS(t) {
02644       _settings_game.vehicle.max_train_length = max<uint8>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
02645     }
02646   }
02647 
02648   if (IsSavegameVersionBefore(KEEP_COMPATIBLE_18_SV)) {
02649     /* Setting difficulty industry_density other than zero get bumped to +1
02650      * since a new option (minimal at position 1) has been added */
02651     if (_settings_game.difficulty.industry_density > 0) {
02652       _settings_game.difficulty.industry_density++;
02653     }
02654   }
02655 
02656   /* Set some breakdown-related variables to the correct values. */
02657   if (IsSavegameVersionBefore(SL_IB)) {
02658     Vehicle *v;
02659     FOR_ALL_VEHICLES(v) {
02660       switch(v->type) {
02661         case VEH_TRAIN: {
02662           if (Train::From(v)->IsFrontEngine()) {
02663             if (v->breakdown_ctr == 1) SetBit(Train::From(v)->flags, VRF_BREAKDOWN_STOPPED);
02664           } else if (Train::From(v)->IsEngine() || Train::From(v)->IsMultiheaded()) {
02665             /* Non-front engines could have a reliability of 0.
02666              * Set it to the reliability of the front engine or the maximum, whichever is lower. */
02667             const Engine *e = Engine::Get(v->engine_type);
02668             v->reliability_spd_dec = e->reliability_spd_dec;
02669             v->reliability = min(v->First()->reliability, e->reliability);
02670           }
02671         }
02672         case VEH_ROAD:
02673           v->breakdown_chance = 128;
02674           break;
02675         case VEH_SHIP:
02676           v->breakdown_chance = 64;
02677           break;
02678         case VEH_AIRCRAFT:
02679           v->breakdown_chance = Clamp(64 + (AircraftVehInfo(v->engine_type)->max_speed >> 3), 0, 255);
02680           v->breakdown_severity = 40;
02681           break;
02682         default: break;
02683       }
02684     }
02685   }
02686 
02687   if (IsSavegameVersionBefore(TL_SV)) {
02688     /* Savegames before this version can not have trafficlights already.
02689      * Sometimes they are added randomly when loading old savegames.
02690      * Unfortunately also in the wrong places -> not on crossings.
02691      *
02692      * Iterate over the whole map and remove any trafficlights found. */
02693     for (TileIndex tile = 0; tile < MapSize(); tile++) {
02694       if (HasTrafficLights(tile)) ClearTrafficLights(tile);
02695     }
02696   }
02697 
02698   /* Road stops is 'only' updating some caches */
02699   AfterLoadRoadStops();
02700   AfterLoadLabelMaps();
02701   AfterLoadCompanyStats();
02702 
02703   GamelogPrintDebug(1);
02704 
02705   InitializeWindowsAndCaches();
02706   /* Restore the signals */
02707   ResetSignalHandlers();
02708 
02709   AfterLoadLinkGraphs();
02710   return true;
02711 }
02712 
02721 void ReloadNewGRFData()
02722 {
02723   /* reload grf data */
02724   GfxLoadSprites();
02725   LoadStringWidthTable();
02726   RecomputePrices();
02727   /* reload vehicles */
02728   ResetVehiclePosHash();
02729   AfterLoadVehicles(false);
02730   StartupEngines();
02731   SetCachedEngineCounts();
02732   /* update station graphics */
02733   AfterLoadStations();
02734   /* Update company statistics. */
02735   AfterLoadCompanyStats();
02736   /* Check and update house and town values */
02737   UpdateHousesAndTowns();
02738   /* Delete news referring to no longer existing entities */
02739   DeleteInvalidEngineNews();
02740   /* Update livery selection windows */
02741   for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i);
02742   /* Update company infrastructure counts. */
02743   InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
02744   /* redraw the whole screen */
02745   MarkWholeScreenDirty();
02746   CheckTrainsLengths();
02747 }