afterload.cpp

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

Generated on Sun Jan 9 16:02:00 2011 for OpenTTD by  doxygen 1.6.1