afterload.cpp

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

Generated on Thu Jan 20 22:57:39 2011 for OpenTTD by  doxygen 1.6.1