afterload.cpp

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

Generated on Fri Feb 4 20:53:46 2011 for OpenTTD by  doxygen 1.6.1