afterload.cpp

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