afterload.cpp

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

Generated on Sat Nov 20 20:59:08 2010 for OpenTTD by  doxygen 1.6.1