# afterload.cpp

Go to the documentation of this file.

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