afterload.cpp

Go to the documentation of this file.
00001 /* $Id: afterload.cpp 15903 2009-03-30 23:15:05Z rubidium $ */
00002 
00005 #include "../stdafx.h"
00006 #include "../void_map.h"
00007 #include "../signs_base.h"
00008 #include "../window_func.h"
00009 #include "../fios.h"
00010 #include "../train.h"
00011 #include "../string_func.h"
00012 #include "../gamelog.h"
00013 #include "../network/network.h"
00014 #include "../gfxinit.h"
00015 #include "../functions.h"
00016 #include "../industry_map.h"
00017 #include "../town_map.h"
00018 #include "../clear_map.h"
00019 #include "../vehicle_func.h"
00020 #include "../newgrf_station.h"
00021 #include "../yapf/yapf.hpp"
00022 #include "../elrail_func.h"
00023 #include "../signs_func.h"
00024 #include "../aircraft.h"
00025 #include "../unmovable_map.h"
00026 #include "../tree_map.h"
00027 #include "../company_func.h"
00028 #include "../road_cmd.h"
00029 #include "../ai/ai.hpp"
00030 
00031 #include "table/strings.h"
00032 
00033 #include "saveload_internal.h"
00034 
00035 #include <signal.h>
00036 
00037 extern StringID _switch_mode_errorstr;
00038 extern Company *DoStartupNewCompany(bool is_ai);
00039 extern void InitializeRailGUI();
00040 
00052 void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
00053 {
00054   /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
00055    * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
00056   if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
00057     if (include_invalid_water_class) {
00058       SetWaterClass(t, WATER_CLASS_INVALID);
00059       return;
00060     } else {
00061       NOT_REACHED();
00062     }
00063   }
00064 
00065   /* Mark tile dirty in all cases */
00066   MarkTileDirtyByTile(t);
00067 
00068   if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
00069     /* tiles at map borders are always WATER_CLASS_SEA */
00070     SetWaterClass(t, WATER_CLASS_SEA);
00071     return;
00072   }
00073 
00074   bool has_water = false;
00075   bool has_canal = false;
00076   bool has_river = false;
00077 
00078   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00079     TileIndex neighbour = TileAddByDiagDir(t, dir);
00080     switch (GetTileType(neighbour)) {
00081       case MP_WATER:
00082         /* clear water and shipdepots have already a WaterClass associated */
00083         if (IsCoast(neighbour)) {
00084           has_water = true;
00085         } else if (!IsLock(neighbour)) {
00086           switch (GetWaterClass(neighbour)) {
00087             case WATER_CLASS_SEA:   has_water = true; break;
00088             case WATER_CLASS_CANAL: has_canal = true; break;
00089             case WATER_CLASS_RIVER: has_river = true; break;
00090             default: NOT_REACHED();
00091           }
00092         }
00093         break;
00094 
00095       case MP_RAILWAY:
00096         /* Shore or flooded halftile */
00097         has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
00098         break;
00099 
00100       case MP_TREES:
00101         /* trees on shore */
00102         has_water |= (GetTreeGround(neighbour) == TREE_GROUND_SHORE);
00103         break;
00104 
00105       default: break;
00106     }
00107   }
00108 
00109   if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
00110     SetWaterClass(t, WATER_CLASS_INVALID);
00111     return;
00112   }
00113 
00114   if (has_river && !has_canal) {
00115     SetWaterClass(t, WATER_CLASS_RIVER);
00116   } else if (has_canal || !has_water) {
00117     SetWaterClass(t, WATER_CLASS_CANAL);
00118   } else {
00119     SetWaterClass(t, WATER_CLASS_SEA);
00120   }
00121 }
00122 
00123 static void ConvertTownOwner()
00124 {
00125   for (TileIndex tile = 0; tile != MapSize(); tile++) {
00126     switch (GetTileType(tile)) {
00127       case MP_ROAD:
00128         if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
00129           _m[tile].m3 = OWNER_TOWN;
00130         }
00131         /* FALLTHROUGH */
00132 
00133       case MP_TUNNELBRIDGE:
00134         if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN);
00135         break;
00136 
00137       default: break;
00138     }
00139   }
00140 }
00141 
00142 /* since savegame version 4.1, exclusive transport rights are stored at towns */
00143 static void UpdateExclusiveRights()
00144 {
00145   Town *t;
00146 
00147   FOR_ALL_TOWNS(t) {
00148     t->exclusivity = INVALID_COMPANY;
00149   }
00150 
00151   /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
00152    *   could be implemented this way:
00153    * 1.) Go through all stations
00154    *     Build an array town_blocked[ town_id ][ company_id ]
00155    *     that stores if at least one station in that town is blocked for a company
00156    * 2.) Go through that array, if you find a town that is not blocked for
00157    *     one company, but for all others, then give him exclusivity.
00158    */
00159 }
00160 
00161 static const byte convert_currency[] = {
00162    0,  1, 12,  8,  3,
00163   10, 14, 19,  4,  5,
00164    9, 11, 13,  6, 17,
00165   16, 22, 21,  7, 15,
00166   18,  2, 20,
00167 };
00168 
00169 /* since savegame version 4.2 the currencies are arranged differently */
00170 static void UpdateCurrencies()
00171 {
00172   _settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
00173 }
00174 
00175 /* Up to revision 1413 the invisible tiles at the southern border have not been
00176  * MP_VOID, even though they should have. This is fixed by this function
00177  */
00178 static void UpdateVoidTiles()
00179 {
00180   uint i;
00181 
00182   for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
00183   for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
00184 }
00185 
00186 static inline RailType UpdateRailType(RailType rt, RailType min)
00187 {
00188   return rt >= min ? (RailType)(rt + 1): rt;
00189 }
00190 
00202 static bool InitializeWindowsAndCaches()
00203 {
00204   /* Initialize windows */
00205   ResetWindowSystem();
00206   SetupColoursAndInitialWindow();
00207 
00208   ResetViewportAfterLoadGame();
00209 
00210   /* Update coordinates of the signs. */
00211   UpdateAllStationVirtCoord();
00212   UpdateAllSignVirtCoords();
00213   UpdateAllTownVirtCoords();
00214   UpdateAllWaypointSigns();
00215 
00216   Company *c;
00217   FOR_ALL_COMPANIES(c) {
00218     /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
00219      * accordingly if it is not the case.  No need to set it on companies that are not been used already,
00220      * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
00221     if (_file_to_saveload.filetype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
00222       c->inaugurated_year = _cur_year;
00223     }
00224   }
00225 
00226   SetCachedEngineCounts();
00227 
00228   /* Towns have a noise controlled number of airports system
00229    * So each airport's noise value must be added to the town->noise_reached value
00230    * Reset each town's noise_reached value to '0' before. */
00231   UpdateAirportsNoise();
00232 
00233   CheckTrainsLengths();
00234 
00235   return true;
00236 }
00237 
00244 void CDECL HandleSavegameLoadCrash(int unused)
00245 {
00246   char buffer[8192];
00247   char *p = buffer;
00248   p += seprintf(p, lastof(buffer),
00249       "Loading your savegame caused OpenTTD to crash.\n"
00250       "This is most likely caused by a missing NewGRF or a NewGRF that has been\n"
00251       "loaded as replacement for a missing NewGRF. OpenTTD cannot easily\n"
00252       "determine whether a replacement NewGRF is of a newer or older version.\n"
00253       "It will load a NewGRF with the same GRF ID as the missing NewGRF. This\n"
00254       "means that if the author makes incompatible NewGRFs with the same GRF ID\n"
00255       "OpenTTD cannot magically do the right thing. In most cases OpenTTD will\n"
00256       "load the savegame and not crash, but this is an exception.\n"
00257       "Please load the savegame with the appropriate NewGRFs. When loading a\n"
00258       "savegame still crashes when all NewGRFs are found you should file a\n"
00259       "bug report. The missing NewGRFs are:\n");
00260 
00261   for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
00262     if (HasBit(c->flags, GCF_COMPATIBLE)) {
00263       char buf[40];
00264       md5sumToString(buf, lastof(buf), c->md5sum);
00265       p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s. Tried another NewGRF with same GRF ID\n", BSWAP32(c->grfid), c->filename, buf);
00266     }
00267     if (c->status == GCS_NOT_FOUND) {
00268       char buf[40];
00269       md5sumToString(buf, lastof(buf), c->md5sum);
00270       p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s\n", BSWAP32(c->grfid), c->filename, buf);
00271     }
00272   }
00273 
00274   ShowInfo(buffer);
00275 }
00276 
00282 static void FixOwnerOfRailTrack(TileIndex t)
00283 {
00284   assert(!IsValidCompanyID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
00285 
00286   /* remove leftover rail piece from crossing (from very old savegames) */
00287   Vehicle *v = NULL, *w;
00288   FOR_ALL_VEHICLES(w) {
00289     if (w->type == VEH_TRAIN && w->tile == t) {
00290       v = w;
00291       break;
00292     }
00293   }
00294 
00295   if (v != NULL) {
00296     /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
00297     SetTileOwner(t, v->owner);
00298     return;
00299   }
00300 
00301   /* try to find any connected rail */
00302   for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
00303     TileIndex tt = t + TileOffsByDiagDir(dd);
00304     if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
00305         GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
00306         IsValidCompanyID(GetTileOwner(tt))) {
00307       SetTileOwner(t, GetTileOwner(tt));
00308       return;
00309     }
00310   }
00311 
00312   if (IsLevelCrossingTile(t)) {
00313     /* else change the crossing to normal road (road vehicles won't care) */
00314     MakeRoadNormal(t, GetCrossingRoadBits(t), GetRoadTypes(t), GetTownIndex(t),
00315       GetRoadOwner(t, ROADTYPE_ROAD), GetRoadOwner(t, ROADTYPE_TRAM));
00316     return;
00317   }
00318 
00319   /* if it's not a crossing, make it clean land */
00320   MakeClear(t, CLEAR_GRASS, 0);
00321 }
00322 
00323 bool AfterLoadGame()
00324 {
00325   typedef void (CDECL *SignalHandlerPointer)(int);
00326   SignalHandlerPointer prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
00327   SignalHandlerPointer prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
00328 
00329   TileIndex map_size = MapSize();
00330   Company *c;
00331 
00332   if (CheckSavegameVersion(98)) GamelogOldver();
00333 
00334   GamelogTestRevision();
00335   GamelogTestMode();
00336 
00337   if (CheckSavegameVersion(98)) GamelogGRFAddList(_grfconfig);
00338 
00339   /* in very old versions, size of train stations was stored differently */
00340   if (CheckSavegameVersion(2)) {
00341     Station *st;
00342     FOR_ALL_STATIONS(st) {
00343       if (st->train_tile != 0 && st->trainst_h == 0) {
00344         uint n = _savegame_type == SGT_OTTD ? 4 : 3; // OTTD uses 4 bits per dimensions, TTD 3 bits
00345         uint w = GB(st->trainst_w, n, n);
00346         uint h = GB(st->trainst_w, 0, n);
00347 
00348         if (GetRailStationAxis(st->train_tile) != AXIS_X) Swap(w, h);
00349 
00350         st->trainst_w = w;
00351         st->trainst_h = h;
00352 
00353         assert(GetStationIndex(st->train_tile + TileDiffXY(w - 1, h - 1)) == st->index);
00354       }
00355     }
00356   }
00357 
00358   /* in version 2.1 of the savegame, town owner was unified. */
00359   if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
00360 
00361   /* from version 4.1 of the savegame, exclusive rights are stored at towns */
00362   if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
00363 
00364   /* from version 4.2 of the savegame, currencies are in a different order */
00365   if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
00366 
00367   /* In old version there seems to be a problem that water is owned by
00368    * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
00369    * (4.3) version, so I just check when versions are older, and then
00370    * walk through the whole map.. */
00371   if (CheckSavegameVersionOldStyle(4, 3)) {
00372     for (TileIndex t = 0; t < map_size; t++) {
00373       if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
00374         SetTileOwner(t, OWNER_WATER);
00375       }
00376     }
00377   }
00378 
00379   if (CheckSavegameVersion(84)) {
00380     FOR_ALL_COMPANIES(c) {
00381       c->name = CopyFromOldName(c->name_1);
00382       if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
00383       c->president_name = CopyFromOldName(c->president_name_1);
00384       if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
00385     }
00386 
00387     Station *st;
00388     FOR_ALL_STATIONS(st) {
00389       st->name = CopyFromOldName(st->string_id);
00390       /* generating new name would be too much work for little effect, use the station name fallback */
00391       if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
00392     }
00393 
00394     Town *t;
00395     FOR_ALL_TOWNS(t) {
00396       t->name = CopyFromOldName(t->townnametype);
00397       if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
00398     }
00399 
00400     Waypoint *wp;
00401     FOR_ALL_WAYPOINTS(wp) {
00402       wp->name = CopyFromOldName(wp->string);
00403       wp->string = STR_EMPTY;
00404     }
00405   }
00406 
00407   /* From this point the old names array is cleared. */
00408   ResetOldNames();
00409 
00410   if (CheckSavegameVersion(106)) {
00411     /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
00412     Station *st;
00413     FOR_ALL_STATIONS(st) {
00414       if (st->airport_tile == 0) st->airport_tile = INVALID_TILE;
00415       if (st->dock_tile    == 0) st->dock_tile    = INVALID_TILE;
00416       if (st->train_tile   == 0) st->train_tile   = INVALID_TILE;
00417     }
00418 
00419     /* the same applies to Company::location_of_HQ */
00420     Company *c;
00421     FOR_ALL_COMPANIES(c) {
00422       if (c->location_of_HQ == 0 || (CheckSavegameVersion(4) && c->location_of_HQ == 0xFFFF)) {
00423         c->location_of_HQ = INVALID_TILE;
00424       }
00425     }
00426   }
00427 
00428   /* convert road side to my format. */
00429   if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
00430 
00431   /* Check if all NewGRFs are present, we are very strict in MP mode */
00432   GRFListCompatibility gcf_res = IsGoodGRFConfigList();
00433   if (_networking && gcf_res != GLC_ALL_GOOD) {
00434     SetSaveLoadError(STR_NETWORK_ERR_CLIENT_NEWGRF_MISMATCH);
00435     /* Restore the signals */
00436     signal(SIGSEGV, prev_segfault);
00437     signal(SIGABRT, prev_abort);
00438     return false;
00439   }
00440 
00441   switch (gcf_res) {
00442     case GLC_COMPATIBLE: _switch_mode_errorstr = STR_NEWGRF_COMPATIBLE_LOAD_WARNING; break;
00443     case GLC_NOT_FOUND: _switch_mode_errorstr = STR_NEWGRF_DISABLED_WARNING; _pause_game = -1; break;
00444     default: break;
00445   }
00446 
00447   /* Update current year
00448    * must be done before loading sprites as some newgrfs check it */
00449   SetDate(_date);
00450 
00451   /* Force dynamic engines off when loading older savegames */
00452   if (CheckSavegameVersion(95)) _settings_game.vehicle.dynamic_engines = 0;
00453 
00454   /* Load the sprites */
00455   GfxLoadSprites();
00456   LoadStringWidthTable();
00457 
00458   /* Copy temporary data to Engine pool */
00459   CopyTempEngineData();
00460 
00461   /* Connect front and rear engines of multiheaded trains and converts
00462    * subtype to the new format */
00463   if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
00464 
00465   /* Connect front and rear engines of multiheaded trains */
00466   ConnectMultiheadedTrains();
00467 
00468   /* reinit the landscape variables (landscape might have changed) */
00469   InitializeLandscapeVariables(true);
00470 
00471   /* Update all vehicles */
00472   AfterLoadVehicles(true);
00473 
00474   /* Make sure there is an AI attached to an AI company */
00475   {
00476     Company *c;
00477     FOR_ALL_COMPANIES(c) {
00478       if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
00479     }
00480   }
00481 
00482   /* Update all waypoints */
00483   if (CheckSavegameVersion(12)) FixOldWaypoints();
00484 
00485   /* make sure there is a town in the game */
00486   if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, UINT_MAX)) {
00487     SetSaveLoadError(STR_NO_TOWN_IN_SCENARIO);
00488     /* Restore the signals */
00489     signal(SIGSEGV, prev_segfault);
00490     signal(SIGABRT, prev_abort);
00491     return false;
00492   }
00493 
00494   /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
00495    * This problem appears in savegame version 21 too, see r3455. But after loading the
00496    * savegame and saving again, the buggy map array could be converted to new savegame
00497    * version. It didn't show up before r12070. */
00498   if (CheckSavegameVersion(87)) UpdateVoidTiles();
00499 
00500   /* If Load Scenario / New (Scenario) Game is used,
00501    *  a company does not exist yet. So create one here.
00502    * 1 exeption: network-games. Those can have 0 companies
00503    *   But this exeption is not true for non dedicated network_servers! */
00504   if (!IsValidCompanyID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated)))
00505     DoStartupNewCompany(false);
00506 
00507   if (CheckSavegameVersion(72)) {
00508     /* Locks/shiplifts in very old savegames had OWNER_WATER as owner */
00509     for (TileIndex t = 0; t < MapSize(); t++) {
00510       switch (GetTileType(t)) {
00511         default: break;
00512 
00513         case MP_WATER:
00514           if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
00515           break;
00516 
00517         case MP_STATION: {
00518           if (HasBit(_m[t].m6, 3)) SetBit(_m[t].m6, 2);
00519           StationGfx gfx = GetStationGfx(t);
00520           StationType st;
00521           if (       IsInsideMM(gfx,   0,   8)) { // Railway station
00522             st = STATION_RAIL;
00523             SetStationGfx(t, gfx - 0);
00524           } else if (IsInsideMM(gfx,   8,  67)) { // Airport
00525             st = STATION_AIRPORT;
00526             SetStationGfx(t, gfx - 8);
00527           } else if (IsInsideMM(gfx,  67,  71)) { // Truck
00528             st = STATION_TRUCK;
00529             SetStationGfx(t, gfx - 67);
00530           } else if (IsInsideMM(gfx,  71,  75)) { // Bus
00531             st = STATION_BUS;
00532             SetStationGfx(t, gfx - 71);
00533           } else if (gfx == 75) {                    // Oil rig
00534             st = STATION_OILRIG;
00535             SetStationGfx(t, gfx - 75);
00536           } else if (IsInsideMM(gfx,  76,  82)) { // Dock
00537             st = STATION_DOCK;
00538             SetStationGfx(t, gfx - 76);
00539           } else if (gfx == 82) {                    // Buoy
00540             st = STATION_BUOY;
00541             SetStationGfx(t, gfx - 82);
00542           } else if (IsInsideMM(gfx,  83, 168)) { // Extended airport
00543             st = STATION_AIRPORT;
00544             SetStationGfx(t, gfx - 83 + 67 - 8);
00545           } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
00546             st = STATION_TRUCK;
00547             SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
00548           } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
00549             st = STATION_BUS;
00550             SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
00551           } else {
00552             /* Restore the signals */
00553             signal(SIGSEGV, prev_segfault);
00554             signal(SIGABRT, prev_abort);
00555             return false;
00556           }
00557           SB(_m[t].m6, 3, 3, st);
00558         } break;
00559       }
00560     }
00561   }
00562 
00563   for (TileIndex t = 0; t < map_size; t++) {
00564     switch (GetTileType(t)) {
00565       case MP_STATION: {
00566         Station *st = GetStationByTile(t);
00567 
00568         /* Set up station spread; buoys do not have one */
00569         if (!IsBuoy(t)) st->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
00570 
00571         switch (GetStationType(t)) {
00572           case STATION_TRUCK:
00573           case STATION_BUS:
00574             if (CheckSavegameVersion(6)) {
00575               /* From this version on there can be multiple road stops of the
00576                * same type per station. Convert the existing stops to the new
00577                * internal data structure. */
00578               RoadStop *rs = new RoadStop(t);
00579               if (rs == NULL) error("Too many road stops in savegame");
00580 
00581               RoadStop **head =
00582                 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
00583               *head = rs;
00584             }
00585             break;
00586 
00587           case STATION_OILRIG: {
00588             /* Very old savegames sometimes have phantom oil rigs, i.e.
00589              * an oil rig which got shut down, but not completly removed from
00590              * the map
00591              */
00592             TileIndex t1 = TILE_ADDXY(t, 0, 1);
00593             if (IsTileType(t1, MP_INDUSTRY) &&
00594                 GetIndustryGfx(t1) == GFX_OILRIG_1) {
00595               /* The internal encoding of oil rigs was changed twice.
00596                * It was 3 (till 2.2) and later 5 (till 5.1).
00597                * Setting it unconditionally does not hurt.
00598                */
00599               GetStationByTile(t)->airport_type = AT_OILRIG;
00600             } else {
00601               DeleteOilRig(t);
00602             }
00603             break;
00604           }
00605 
00606           default: break;
00607         }
00608         break;
00609       }
00610 
00611       default: break;
00612     }
00613   }
00614 
00615   /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
00616    * This has to be called after the oilrig airport_type update above ^^^ ! */
00617   if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
00618 
00619   /* In version 6.1 we put the town index in the map-array. To do this, we need
00620    *  to use m2 (16bit big), so we need to clean m2, and that is where this is
00621    *  all about ;) */
00622   if (CheckSavegameVersionOldStyle(6, 1)) {
00623     for (TileIndex t = 0; t < map_size; t++) {
00624       switch (GetTileType(t)) {
00625         case MP_HOUSE:
00626           _m[t].m4 = _m[t].m2;
00627           SetTownIndex(t, CalcClosestTownFromTile(t)->index);
00628           break;
00629 
00630         case MP_ROAD:
00631           _m[t].m4 |= (_m[t].m2 << 4);
00632           if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
00633             SetTownIndex(t, CalcClosestTownFromTile(t)->index);
00634           } else {
00635             SetTownIndex(t, 0);
00636           }
00637           break;
00638 
00639         default: break;
00640       }
00641     }
00642   }
00643 
00644   /* Force the freeform edges to false for old savegames. */
00645   if (CheckSavegameVersion(111)) {
00646     _settings_game.construction.freeform_edges = false;
00647   }
00648 
00649   /* From version 9.0, we update the max passengers of a town (was sometimes negative
00650    *  before that. */
00651   if (CheckSavegameVersion(9)) {
00652     Town *t;
00653     FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
00654   }
00655 
00656   /* From version 16.0, we included autorenew on engines, which are now saved, but
00657    *  of course, we do need to initialize them for older savegames. */
00658   if (CheckSavegameVersion(16)) {
00659     FOR_ALL_COMPANIES(c) {
00660       c->engine_renew_list   = NULL;
00661       c->engine_renew        = false;
00662       c->engine_renew_months = -6;
00663       c->engine_renew_money  = 100000;
00664     }
00665 
00666     /* When loading a game, _local_company is not yet set to the correct value.
00667      * However, in a dedicated server we are a spectator, so nothing needs to
00668      * happen. In case we are not a dedicated server, the local company always
00669      * becomes company 0, unless we are in the scenario editor where all the
00670      * companies are 'invalid'.
00671      */
00672     if (!_network_dedicated && IsValidCompanyID(COMPANY_FIRST)) {
00673       c = GetCompany(COMPANY_FIRST);
00674       c->engine_renew        = _settings_client.gui.autorenew;
00675       c->engine_renew_months = _settings_client.gui.autorenew_months;
00676       c->engine_renew_money  = _settings_client.gui.autorenew_money;
00677     }
00678   }
00679 
00680   if (CheckSavegameVersion(48)) {
00681     for (TileIndex t = 0; t < map_size; t++) {
00682       switch (GetTileType(t)) {
00683         case MP_RAILWAY:
00684           if (IsPlainRailTile(t)) {
00685             /* Swap ground type and signal type for plain rail tiles, so the
00686              * ground type uses the same bits as for depots and waypoints. */
00687             uint tmp = GB(_m[t].m4, 0, 4);
00688             SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
00689             SB(_m[t].m2, 0, 4, tmp);
00690           } else if (HasBit(_m[t].m5, 2)) {
00691             /* Split waypoint and depot rail type and remove the subtype. */
00692             ClrBit(_m[t].m5, 2);
00693             ClrBit(_m[t].m5, 6);
00694           }
00695           break;
00696 
00697         case MP_ROAD:
00698           /* Swap m3 and m4, so the track type for rail crossings is the
00699            * same as for normal rail. */
00700           Swap(_m[t].m3, _m[t].m4);
00701           break;
00702 
00703         default: break;
00704       }
00705     }
00706   }
00707 
00708   if (CheckSavegameVersion(61)) {
00709     /* Added the RoadType */
00710     bool old_bridge = CheckSavegameVersion(42);
00711     for (TileIndex t = 0; t < map_size; t++) {
00712       switch (GetTileType(t)) {
00713         case MP_ROAD:
00714           SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
00715           switch (GetRoadTileType(t)) {
00716             default: NOT_REACHED();
00717             case ROAD_TILE_NORMAL:
00718               SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
00719               SB(_m[t].m4, 4, 4, 0);
00720               SB(_m[t].m6, 2, 4, 0);
00721               break;
00722             case ROAD_TILE_CROSSING:
00723               SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
00724               break;
00725             case ROAD_TILE_DEPOT:    break;
00726           }
00727           SetRoadTypes(t, ROADTYPES_ROAD);
00728           break;
00729 
00730         case MP_STATION:
00731           if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
00732           break;
00733 
00734         case MP_TUNNELBRIDGE:
00735           /* Middle part of "old" bridges */
00736           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
00737           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
00738             SetRoadTypes(t, ROADTYPES_ROAD);
00739           }
00740           break;
00741 
00742         default: break;
00743       }
00744     }
00745   }
00746 
00747   if (CheckSavegameVersion(114)) {
00748     bool fix_roadtypes = !CheckSavegameVersion(61);
00749     bool old_bridge = CheckSavegameVersion(42);
00750 
00751     for (TileIndex t = 0; t < map_size; t++) {
00752       switch (GetTileType(t)) {
00753         case MP_ROAD:
00754           if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
00755           SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
00756           switch (GetRoadTileType(t)) {
00757             default: NOT_REACHED();
00758             case ROAD_TILE_NORMAL:
00759               SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
00760               SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3));  // ground
00761               SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4));  // tram bits
00762               SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4));  // tram owner
00763               SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4));  // road bits
00764               break;
00765 
00766             case ROAD_TILE_CROSSING:
00767               SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
00768               SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3));  // ground
00769               SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4));  // tram owner
00770               SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1));  // road axis
00771               SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1));  // crossing state
00772               break;
00773 
00774             case ROAD_TILE_DEPOT:
00775               break;
00776           }
00777           if (!HasTownOwnedRoad(t)) {
00778             const Town *town = CalcClosestTownFromTile(t);
00779             if (town != NULL) SetTownIndex(t, town->index);
00780           }
00781           _m[t].m4 = 0;
00782           break;
00783 
00784         case MP_STATION:
00785           if (!IsRoadStop(t)) break;
00786 
00787           if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
00788           SB(_me[t].m7, 0, 5, HasBit(_m[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
00789           SB(_m[t].m3, 4, 4, _m[t].m1);
00790           _m[t].m4 = 0;
00791           break;
00792 
00793         case MP_TUNNELBRIDGE:
00794           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
00795           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
00796             if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
00797 
00798             Owner o = GetTileOwner(t);
00799             SB(_me[t].m7, 0, 5, o); // road owner
00800             SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
00801           }
00802           SB(_m[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
00803           SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
00804 
00805           _m[t].m2 = 0;
00806           _m[t].m4 = 0;
00807           break;
00808 
00809         default: break;
00810       }
00811     }
00812   }
00813 
00814   if (CheckSavegameVersion(42)) {
00815     Vehicle *v;
00816 
00817     for (TileIndex t = 0; t < map_size; t++) {
00818       if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
00819       if (IsBridgeTile(t)) {
00820         if (HasBit(_m[t].m5, 6)) { // middle part
00821           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
00822 
00823           if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
00824             if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
00825               MakeRailNormal(
00826                 t,
00827                 GetTileOwner(t),
00828                 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
00829                 GetRailType(t)
00830               );
00831             } else {
00832               TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
00833 
00834               MakeRoadNormal(
00835                 t,
00836                 axis == AXIS_X ? ROAD_Y : ROAD_X,
00837                 ROADTYPES_ROAD,
00838                 town,
00839                 GetTileOwner(t), OWNER_NONE
00840               );
00841             }
00842           } else {
00843             if (GB(_m[t].m5, 3, 2) == 0) {
00844               MakeClear(t, CLEAR_GRASS, 3);
00845             } else {
00846               if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
00847                 MakeShore(t);
00848               } else {
00849                 if (GetTileOwner(t) == OWNER_WATER) {
00850                   MakeWater(t);
00851                 } else {
00852                   MakeCanal(t, GetTileOwner(t), Random());
00853                 }
00854               }
00855             }
00856           }
00857           SetBridgeMiddle(t, axis);
00858         } else { // ramp
00859           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
00860           uint north_south = GB(_m[t].m5, 5, 1);
00861           DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
00862           TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
00863 
00864           _m[t].m5 = 1 << 7 | type << 2 | dir;
00865         }
00866       }
00867     }
00868 
00869     FOR_ALL_VEHICLES(v) {
00870       if (v->type != VEH_TRAIN && v->type != VEH_ROAD) continue;
00871       if (IsBridgeTile(v->tile)) {
00872         DiagDirection dir = GetTunnelBridgeDirection(v->tile);
00873 
00874         if (dir != DirToDiagDir(v->direction)) continue;
00875         switch (dir) {
00876           default: NOT_REACHED();
00877           case DIAGDIR_NE: if ((v->x_pos & 0xF) !=  0)            continue; break;
00878           case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
00879           case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
00880           case DIAGDIR_NW: if ((v->y_pos & 0xF) !=  0)            continue; break;
00881         }
00882       } else if (v->z_pos > GetSlopeZ(v->x_pos, v->y_pos)) {
00883         v->tile = GetNorthernBridgeEnd(v->tile);
00884       } else {
00885         continue;
00886       }
00887       if (v->type == VEH_TRAIN) {
00888         v->u.rail.track = TRACK_BIT_WORMHOLE;
00889       } else {
00890         v->u.road.state = RVSB_WORMHOLE;
00891       }
00892     }
00893   }
00894 
00895   /* Elrails got added in rev 24 */
00896   if (CheckSavegameVersion(24)) {
00897     Vehicle *v;
00898     RailType min_rail = RAILTYPE_ELECTRIC;
00899 
00900     FOR_ALL_VEHICLES(v) {
00901       if (v->type == VEH_TRAIN) {
00902         RailType rt = RailVehInfo(v->engine_type)->railtype;
00903 
00904         v->u.rail.railtype = rt;
00905         if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
00906       }
00907     }
00908 
00909     /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
00910     for (TileIndex t = 0; t < map_size; t++) {
00911       switch (GetTileType(t)) {
00912         case MP_RAILWAY:
00913           SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
00914           break;
00915 
00916         case MP_ROAD:
00917           if (IsLevelCrossing(t)) {
00918             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
00919           }
00920           break;
00921 
00922         case MP_STATION:
00923           if (IsRailwayStation(t)) {
00924             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
00925           }
00926           break;
00927 
00928         case MP_TUNNELBRIDGE:
00929           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
00930             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
00931           }
00932           break;
00933 
00934         default:
00935           break;
00936       }
00937     }
00938 
00939     FOR_ALL_VEHICLES(v) {
00940       if (v->type == VEH_TRAIN && (IsFrontEngine(v) || IsFreeWagon(v))) TrainConsistChanged(v, true);
00941     }
00942 
00943   }
00944 
00945   /* In version 16.1 of the savegame a company can decide if trains, which get
00946    * replaced, shall keep their old length. In all prior versions, just default
00947    * to false */
00948   if (CheckSavegameVersionOldStyle(16, 1)) {
00949     FOR_ALL_COMPANIES(c) c->renew_keep_length = false;
00950   }
00951 
00952   /* In version 17, ground type is moved from m2 to m4 for depots and
00953    * waypoints to make way for storing the index in m2. The custom graphics
00954    * id which was stored in m4 is now saved as a grf/id reference in the
00955    * waypoint struct. */
00956   if (CheckSavegameVersion(17)) {
00957     Waypoint *wp;
00958 
00959     FOR_ALL_WAYPOINTS(wp) {
00960       if (wp->deleted == 0) {
00961         const StationSpec *statspec = NULL;
00962 
00963         if (HasBit(_m[wp->xy].m3, 4))
00964           statspec = GetCustomStationSpec(STAT_CLASS_WAYP, _m[wp->xy].m4 + 1);
00965 
00966         if (statspec != NULL) {
00967           wp->stat_id = _m[wp->xy].m4 + 1;
00968           wp->grfid = statspec->grffile->grfid;
00969           wp->localidx = statspec->localidx;
00970         } else {
00971           /* No custom graphics set, so set to default. */
00972           wp->stat_id = 0;
00973           wp->grfid = 0;
00974           wp->localidx = 0;
00975         }
00976 
00977         /* Move ground type bits from m2 to m4. */
00978         _m[wp->xy].m4 = GB(_m[wp->xy].m2, 0, 4);
00979         /* Store waypoint index in the tile. */
00980         _m[wp->xy].m2 = wp->index;
00981       }
00982     }
00983   } else {
00984     /* As of version 17, we recalculate the custom graphic ID of waypoints
00985      * from the GRF ID / station index. */
00986     AfterLoadWaypoints();
00987   }
00988 
00989   /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
00990    *  room for PBS. Now in version 21 move it back :P. */
00991   if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
00992     for (TileIndex t = 0; t < map_size; t++) {
00993       switch (GetTileType(t)) {
00994         case MP_RAILWAY:
00995           if (HasSignals(t)) {
00996             /* convert PBS signals to combo-signals */
00997             if (HasBit(_m[t].m2, 2)) SetSignalType(t, TRACK_X, SIGTYPE_COMBO);
00998 
00999             /* move the signal variant back */
01000             SetSignalVariant(t, TRACK_X, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
01001             ClrBit(_m[t].m2, 3);
01002           }
01003 
01004           /* Clear PBS reservation on track */
01005           if (!IsRailDepotTile(t)) {
01006             SB(_m[t].m4, 4, 4, 0);
01007           } else {
01008             ClrBit(_m[t].m3, 6);
01009           }
01010           break;
01011 
01012         case MP_STATION: // Clear PBS reservation on station
01013           ClrBit(_m[t].m3, 6);
01014           break;
01015 
01016         default: break;
01017       }
01018     }
01019   }
01020 
01021   if (CheckSavegameVersion(25)) {
01022     Vehicle *v;
01023     FOR_ALL_VEHICLES(v) {
01024       if (v->type == VEH_ROAD) {
01025         v->vehstatus &= ~0x40;
01026         v->u.road.slot = NULL;
01027         v->u.road.slot_age = 0;
01028       }
01029     }
01030   } else {
01031     Vehicle *v;
01032     FOR_ALL_VEHICLES(v) {
01033       if (v->type == VEH_ROAD && v->u.road.slot != NULL) v->u.road.slot->num_vehicles++;
01034     }
01035   }
01036 
01037   if (CheckSavegameVersion(26)) {
01038     Station *st;
01039     FOR_ALL_STATIONS(st) {
01040       st->last_vehicle_type = VEH_INVALID;
01041     }
01042   }
01043 
01044   YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
01045 
01046   if (CheckSavegameVersion(34)) FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
01047 
01048   FOR_ALL_COMPANIES(c) {
01049     c->avail_railtypes = GetCompanyRailtypes(c->index);
01050     c->avail_roadtypes = GetCompanyRoadtypes(c->index);
01051   }
01052 
01053   if (!CheckSavegameVersion(27)) AfterLoadStations();
01054 
01055   /* Time starts at 0 instead of 1920.
01056    * Account for this in older games by adding an offset */
01057   if (CheckSavegameVersion(31)) {
01058     Station *st;
01059     Waypoint *wp;
01060     Engine *e;
01061     Industry *i;
01062     Vehicle *v;
01063 
01064     _date += DAYS_TILL_ORIGINAL_BASE_YEAR;
01065     _cur_year += ORIGINAL_BASE_YEAR;
01066 
01067     FOR_ALL_STATIONS(st)  st->build_date      += DAYS_TILL_ORIGINAL_BASE_YEAR;
01068     FOR_ALL_WAYPOINTS(wp) wp->build_date      += DAYS_TILL_ORIGINAL_BASE_YEAR;
01069     FOR_ALL_ENGINES(e)    e->intro_date       += DAYS_TILL_ORIGINAL_BASE_YEAR;
01070     FOR_ALL_COMPANIES(c)  c->inaugurated_year += ORIGINAL_BASE_YEAR;
01071     FOR_ALL_INDUSTRIES(i) i->last_prod_year   += ORIGINAL_BASE_YEAR;
01072 
01073     FOR_ALL_VEHICLES(v) {
01074       v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
01075       v->build_year += ORIGINAL_BASE_YEAR;
01076     }
01077   }
01078 
01079   /* From 32 on we save the industry who made the farmland.
01080    *  To give this prettyness to old savegames, we remove all farmfields and
01081    *  plant new ones. */
01082   if (CheckSavegameVersion(32)) {
01083     Industry *i;
01084 
01085     for (TileIndex t = 0; t < map_size; t++) {
01086       if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
01087         /* remove fields */
01088         MakeClear(t, CLEAR_GRASS, 3);
01089       } else if (IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES)) {
01090         /* remove fences around fields */
01091         SetFenceSE(t, 0);
01092         SetFenceSW(t, 0);
01093       }
01094     }
01095 
01096     FOR_ALL_INDUSTRIES(i) {
01097       uint j;
01098 
01099       if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
01100         for (j = 0; j != 50; j++) PlantRandomFarmField(i);
01101       }
01102     }
01103   }
01104 
01105   /* Setting no refit flags to all orders in savegames from before refit in orders were added */
01106   if (CheckSavegameVersion(36)) {
01107     Order *order;
01108     Vehicle *v;
01109 
01110     FOR_ALL_ORDERS(order) {
01111       order->SetRefit(CT_NO_REFIT);
01112     }
01113 
01114     FOR_ALL_VEHICLES(v) {
01115       v->current_order.SetRefit(CT_NO_REFIT);
01116     }
01117   }
01118 
01119   /* from version 38 we have optional elrails, since we cannot know the
01120    * preference of a user, let elrails enabled; it can be disabled manually */
01121   if (CheckSavegameVersion(38)) _settings_game.vehicle.disable_elrails = false;
01122   /* do the same as when elrails were enabled/disabled manually just now */
01123   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
01124   InitializeRailGUI();
01125 
01126   /* From version 53, the map array was changed for house tiles to allow
01127    * space for newhouses grf features. A new byte, m7, was also added. */
01128   if (CheckSavegameVersion(53)) {
01129     for (TileIndex t = 0; t < map_size; t++) {
01130       if (IsTileType(t, MP_HOUSE)) {
01131         if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
01132           /* Move the construction stage from m3[7..6] to m5[5..4].
01133            * The construction counter does not have to move. */
01134           SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
01135           SB(_m[t].m3, 6, 2, 0);
01136 
01137           /* The "house is completed" bit is now in m6[2]. */
01138           SetHouseCompleted(t, false);
01139         } else {
01140           /* The "lift has destination" bit has been moved from
01141            * m5[7] to m7[0]. */
01142           SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
01143           ClrBit(_m[t].m5, 7);
01144 
01145           /* The "lift is moving" bit has been removed, as it does
01146            * the same job as the "lift has destination" bit. */
01147           ClrBit(_m[t].m1, 7);
01148 
01149           /* The position of the lift goes from m1[7..0] to m6[7..2],
01150            * making m1 totally free, now. The lift position does not
01151            * have to be a full byte since the maximum value is 36. */
01152           SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
01153 
01154           _m[t].m1 = 0;
01155           _m[t].m3 = 0;
01156           SetHouseCompleted(t, true);
01157         }
01158       }
01159     }
01160   }
01161 
01162   /* Check and update house and town values */
01163   UpdateHousesAndTowns();
01164 
01165   if (CheckSavegameVersion(43)) {
01166     for (TileIndex t = 0; t < map_size; t++) {
01167       if (IsTileType(t, MP_INDUSTRY)) {
01168         switch (GetIndustryGfx(t)) {
01169           case GFX_POWERPLANT_SPARKS:
01170             SetIndustryAnimationState(t, GB(_m[t].m1, 2, 5));
01171             break;
01172 
01173           case GFX_OILWELL_ANIMATED_1:
01174           case GFX_OILWELL_ANIMATED_2:
01175           case GFX_OILWELL_ANIMATED_3:
01176             SetIndustryAnimationState(t, GB(_m[t].m1, 0, 2));
01177             break;
01178 
01179           case GFX_COAL_MINE_TOWER_ANIMATED:
01180           case GFX_COPPER_MINE_TOWER_ANIMATED:
01181           case GFX_GOLD_MINE_TOWER_ANIMATED:
01182              SetIndustryAnimationState(t, _m[t].m1);
01183              break;
01184 
01185           default: // No animation states to change
01186             break;
01187         }
01188       }
01189     }
01190   }
01191 
01192   if (CheckSavegameVersion(44)) {
01193     Vehicle *v;
01194     /* If we remove a station while cargo from it is still enroute, payment calculation will assume
01195      * 0, 0 to be the source of the cargo, resulting in very high payments usually. v->source_xy
01196      * stores the coordinates, preserving them even if the station is removed. However, if a game is loaded
01197      * where this situation exists, the cargo-source information is lost. in this case, we set the source
01198      * to the current tile of the vehicle to prevent excessive profits
01199      */
01200     FOR_ALL_VEHICLES(v) {
01201       const CargoList::List *packets = v->cargo.Packets();
01202       for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
01203         CargoPacket *cp = *it;
01204         cp->source_xy = IsValidStationID(cp->source) ? GetStation(cp->source)->xy : v->tile;
01205         cp->loaded_at_xy = cp->source_xy;
01206       }
01207       v->cargo.InvalidateCache();
01208     }
01209 
01210     /* Store position of the station where the goods come from, so there
01211      * are no very high payments when stations get removed. However, if the
01212      * station where the goods came from is already removed, the source
01213      * information is lost. In that case we set it to the position of this
01214      * station */
01215     Station *st;
01216     FOR_ALL_STATIONS(st) {
01217       for (CargoID c = 0; c < NUM_CARGO; c++) {
01218         GoodsEntry *ge = &st->goods[c];
01219 
01220         const CargoList::List *packets = ge->cargo.Packets();
01221         for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
01222           CargoPacket *cp = *it;
01223           cp->source_xy = IsValidStationID(cp->source) ? GetStation(cp->source)->xy : st->xy;
01224           cp->loaded_at_xy = cp->source_xy;
01225         }
01226       }
01227     }
01228   }
01229 
01230   if (CheckSavegameVersion(45)) {
01231     Vehicle *v;
01232     /* Originally just the fact that some cargo had been paid for was
01233      * stored to stop people cheating and cashing in several times. This
01234      * wasn't enough though as it was cleared when the vehicle started
01235      * loading again, even if it didn't actually load anything, so now the
01236      * amount of cargo that has been paid for is stored. */
01237     FOR_ALL_VEHICLES(v) {
01238       const CargoList::List *packets = v->cargo.Packets();
01239       for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
01240         CargoPacket *cp = *it;
01241         cp->paid_for = HasBit(v->vehicle_flags, 2);
01242       }
01243       ClrBit(v->vehicle_flags, 2);
01244       v->cargo.InvalidateCache();
01245     }
01246   }
01247 
01248   /* Buoys do now store the owner of the previous water tile, which can never
01249    * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
01250   if (CheckSavegameVersion(46)) {
01251     Station *st;
01252     FOR_ALL_STATIONS(st) {
01253       if (st->IsBuoy() && IsTileOwner(st->xy, OWNER_NONE) && TileHeight(st->xy) == 0) SetTileOwner(st->xy, OWNER_WATER);
01254     }
01255   }
01256 
01257   if (CheckSavegameVersion(50)) {
01258     Vehicle *v;
01259     /* Aircraft units changed from 8 mph to 1 km/h */
01260     FOR_ALL_VEHICLES(v) {
01261       if (v->type == VEH_AIRCRAFT && v->subtype <= AIR_AIRCRAFT) {
01262         const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
01263         v->cur_speed *= 129;
01264         v->cur_speed /= 10;
01265         v->max_speed = avi->max_speed;
01266         v->acceleration = avi->acceleration;
01267       }
01268     }
01269   }
01270 
01271   if (CheckSavegameVersion(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
01272 
01273   if (CheckSavegameVersion(52)) {
01274     for (TileIndex t = 0; t < map_size; t++) {
01275       if (IsStatueTile(t)) {
01276         _m[t].m2 = CalcClosestTownFromTile(t)->index;
01277       }
01278     }
01279   }
01280 
01281   /* A setting containing the proportion of towns that grow twice as
01282    * fast was added in version 54. From version 56 this is now saved in the
01283    * town as cities can be built specifically in the scenario editor. */
01284   if (CheckSavegameVersion(56)) {
01285     Town *t;
01286 
01287     FOR_ALL_TOWNS(t) {
01288       if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
01289         t->larger_town = true;
01290       }
01291     }
01292   }
01293 
01294   if (CheckSavegameVersion(57)) {
01295     Vehicle *v;
01296     /* Added a FIFO queue of vehicles loading at stations */
01297     FOR_ALL_VEHICLES(v) {
01298       if ((v->type != VEH_TRAIN || IsFrontEngine(v)) &&  // for all locs
01299           !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
01300           v->current_order.IsType(OT_LOADING)) {         // loading
01301         GetStation(v->last_station_visited)->loading_vehicles.push_back(v);
01302 
01303         /* The loading finished flag is *only* set when actually completely
01304          * finished. Because the vehicle is loading, it is not finished. */
01305         ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
01306       }
01307     }
01308   } else if (CheckSavegameVersion(59)) {
01309     /* For some reason non-loading vehicles could be in the station's loading vehicle list */
01310 
01311     Station *st;
01312     FOR_ALL_STATIONS(st) {
01313       std::list<Vehicle *>::iterator iter;
01314       for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
01315         Vehicle *v = *iter;
01316         iter++;
01317         if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
01318       }
01319     }
01320   }
01321 
01322   if (CheckSavegameVersion(58)) {
01323     /* Setting difficulty number_industries other than zero get bumped to +1
01324      * since a new option (very low at position1) has been added */
01325     if (_settings_game.difficulty.number_industries > 0) {
01326       _settings_game.difficulty.number_industries++;
01327     }
01328 
01329     /* Same goes for number of towns, although no test is needed, just an increment */
01330     _settings_game.difficulty.number_towns++;
01331   }
01332 
01333   if (CheckSavegameVersion(64)) {
01334     /* copy the signal type/variant and move signal states bits */
01335     for (TileIndex t = 0; t < map_size; t++) {
01336       if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
01337         SetSignalStates(t, GB(_m[t].m2, 4, 4));
01338         SetSignalVariant(t, INVALID_TRACK, GetSignalVariant(t, TRACK_X));
01339         SetSignalType(t, INVALID_TRACK, GetSignalType(t, TRACK_X));
01340         ClrBit(_m[t].m2, 7);
01341       }
01342     }
01343   }
01344 
01345   if (CheckSavegameVersion(69)) {
01346     /* In some old savegames a bit was cleared when it should not be cleared */
01347     Vehicle *v;
01348     FOR_ALL_VEHICLES(v) {
01349       if (v->type == VEH_ROAD && (v->u.road.state == 250 || v->u.road.state == 251)) {
01350         SetBit(v->u.road.state, RVS_IS_STOPPING);
01351       }
01352     }
01353   }
01354 
01355   if (CheckSavegameVersion(70)) {
01356     /* Added variables to support newindustries */
01357     Industry *i;
01358     FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
01359   }
01360 
01361   /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
01362       Replace the owner for those by OWNER_NONE. */
01363   if (CheckSavegameVersion(82)) {
01364     for (TileIndex t = 0; t < map_size; t++) {
01365       if (IsTileType(t, MP_WATER) &&
01366           GetWaterTileType(t) == WATER_TILE_CLEAR &&
01367           GetTileOwner(t) == OWNER_WATER &&
01368           TileHeight(t) != 0) {
01369         SetTileOwner(t, OWNER_NONE);
01370       }
01371     }
01372   }
01373 
01374   /*
01375    * Add the 'previous' owner to the ship depots so we can reset it with
01376    * the correct values when it gets destroyed. This prevents that
01377    * someone can remove canals owned by somebody else and it prevents
01378    * making floods using the removal of ship depots.
01379    */
01380   if (CheckSavegameVersion(83)) {
01381     for (TileIndex t = 0; t < map_size; t++) {
01382       if (IsTileType(t, MP_WATER) && IsShipDepot(t)) {
01383         _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
01384       }
01385     }
01386   }
01387 
01388   if (CheckSavegameVersion(74)) {
01389     Station *st;
01390     FOR_ALL_STATIONS(st) {
01391       for (CargoID c = 0; c < NUM_CARGO; c++) {
01392         st->goods[c].last_speed = 0;
01393         if (st->goods[c].cargo.Count() != 0) SetBit(st->goods[c].acceptance_pickup, GoodsEntry::PICKUP);
01394       }
01395     }
01396   }
01397 
01398   if (CheckSavegameVersion(78)) {
01399     Industry *i;
01400     uint j;
01401     FOR_ALL_INDUSTRIES(i) {
01402       const IndustrySpec *indsp = GetIndustrySpec(i->type);
01403       for (j = 0; j < lengthof(i->produced_cargo); j++) {
01404         i->produced_cargo[j] = indsp->produced_cargo[j];
01405       }
01406       for (j = 0; j < lengthof(i->accepts_cargo); j++) {
01407         i->accepts_cargo[j] = indsp->accepts_cargo[j];
01408       }
01409     }
01410   }
01411 
01412   /* Before version 81, the density of grass was always stored as zero, and
01413    * grassy trees were always drawn fully grassy. Furthermore, trees on rough
01414    * land used to have zero density, now they have full density. Therefore,
01415    * make all grassy/rough land trees have a density of 3. */
01416   if (CheckSavegameVersion(81)) {
01417     for (TileIndex t = 0; t < map_size; t++) {
01418       if (GetTileType(t) == MP_TREES) {
01419         TreeGround groundType = GetTreeGround(t);
01420         if (groundType != TREE_GROUND_SNOW_DESERT) SetTreeGroundDensity(t, groundType, 3);
01421       }
01422     }
01423   }
01424 
01425 
01426   if (CheckSavegameVersion(93)) {
01427     /* Rework of orders. */
01428     Order *order;
01429     FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
01430 
01431     Vehicle *v;
01432     FOR_ALL_VEHICLES(v) {
01433       if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && !v->orders.list->GetFirstOrder()->IsValid()) {
01434         v->orders.list->FreeChain();
01435         v->orders.list = NULL;
01436       }
01437 
01438       v->current_order.ConvertFromOldSavegame();
01439       if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
01440         FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
01441       }
01442     }
01443   } else if (CheckSavegameVersion(94)) {
01444     /* Unload and transfer are now mutual exclusive. */
01445     Order *order;
01446     FOR_ALL_ORDERS(order) {
01447       if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
01448         order->SetUnloadType(OUFB_TRANSFER);
01449         order->SetLoadType(OLFB_NO_LOAD);
01450       }
01451     }
01452 
01453     Vehicle *v;
01454     FOR_ALL_VEHICLES(v) {
01455       if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
01456         v->current_order.SetUnloadType(OUFB_TRANSFER);
01457         v->current_order.SetLoadType(OLFB_NO_LOAD);
01458       }
01459     }
01460   }
01461 
01462   if (CheckSavegameVersion(84)) {
01463     /* Update go to buoy orders because they are just waypoints */
01464     Order *order;
01465     FOR_ALL_ORDERS(order) {
01466       if (order->IsType(OT_GOTO_STATION) && GetStation(order->GetDestination())->IsBuoy()) {
01467         order->SetLoadType(OLF_LOAD_IF_POSSIBLE);
01468         order->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE);
01469       }
01470     }
01471 
01472     /* Set all share owners to INVALID_COMPANY for
01473      * 1) all inactive companies
01474      *     (when inactive companies were stored in the savegame - TTD, TTDP and some
01475      *      *really* old revisions of OTTD; else it is already set in InitializeCompanies())
01476      * 2) shares that are owned by inactive companies or self
01477      *     (caused by cheating clients in earlier revisions) */
01478     FOR_ALL_COMPANIES(c) {
01479       for (uint i = 0; i < 4; i++) {
01480         CompanyID company = c->share_owners[i];
01481         if (company == INVALID_COMPANY) continue;
01482         if (!IsValidCompanyID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
01483       }
01484     }
01485   }
01486 
01487   if (CheckSavegameVersion(86)) {
01488     for (TileIndex t = 0; t < map_size; t++) {
01489       /* Move river flag and update canals to use water class */
01490       if (IsTileType(t, MP_WATER)) {
01491         if (GetWaterClass(t) != WATER_CLASS_RIVER) {
01492           if (IsWater(t)) {
01493             Owner o = GetTileOwner(t);
01494             if (o == OWNER_WATER) {
01495               MakeWater(t);
01496             } else {
01497               MakeCanal(t, o, Random());
01498             }
01499           } else if (IsShipDepot(t)) {
01500             Owner o = (Owner)_m[t].m4; // Original water owner
01501             SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
01502           }
01503         }
01504       }
01505     }
01506 
01507     /* Update locks, depots, docks and buoys to have a water class based
01508      * on its neighbouring tiles. Done after river and canal updates to
01509      * ensure neighbours are correct. */
01510     for (TileIndex t = 0; t < map_size; t++) {
01511       if (GetTileSlope(t, NULL) != SLOPE_FLAT) continue;
01512 
01513       if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
01514       if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
01515     }
01516   }
01517 
01518   if (CheckSavegameVersion(87)) {
01519     for (TileIndex t = 0; t < map_size; t++) {
01520       /* skip oil rigs at borders! */
01521       if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
01522           (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
01523         /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
01524          * This conversion has to be done before buoys with invalid owner are removed. */
01525         SetWaterClass(t, WATER_CLASS_SEA);
01526       }
01527 
01528       if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
01529         Owner o = GetTileOwner(t);
01530         if (o < MAX_COMPANIES && !IsValidCompanyID(o)) {
01531           _current_company = o;
01532           ChangeTileOwner(t, o, INVALID_OWNER);
01533         }
01534         if (IsBuoyTile(t)) {
01535           /* reset buoy owner to OWNER_NONE in the station struct
01536            * (even if it is owned by active company) */
01537           GetStationByTile(t)->owner = OWNER_NONE;
01538         }
01539       } else if (IsTileType(t, MP_ROAD)) {
01540         /* works for all RoadTileType */
01541         for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01542           /* update even non-existing road types to update tile owner too */
01543           Owner o = GetRoadOwner(t, rt);
01544           if (o < MAX_COMPANIES && !IsValidCompanyID(o)) SetRoadOwner(t, rt, OWNER_NONE);
01545         }
01546         if (IsLevelCrossing(t)) {
01547           if (!IsValidCompanyID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
01548         }
01549       } else if (IsTileType(t, MP_RAILWAY) && IsPlainRailTile(t)) {
01550         if (!IsValidCompanyID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
01551       }
01552     }
01553 
01554     /* Convert old PF settings to new */
01555     if (_settings_game.pf.yapf.rail_use_yapf || CheckSavegameVersion(28)) {
01556       _settings_game.pf.pathfinder_for_trains = VPF_YAPF;
01557     } else {
01558       _settings_game.pf.pathfinder_for_trains = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_NTP);
01559     }
01560 
01561     if (_settings_game.pf.yapf.road_use_yapf || CheckSavegameVersion(28)) {
01562       _settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
01563     } else {
01564       _settings_game.pf.pathfinder_for_roadvehs = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
01565     }
01566 
01567     if (_settings_game.pf.yapf.ship_use_yapf) {
01568       _settings_game.pf.pathfinder_for_ships = VPF_YAPF;
01569     } else {
01570       _settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
01571     }
01572   }
01573 
01574   if (CheckSavegameVersion(88)) {
01575     /* Profits are now with 8 bit fract */
01576     Vehicle *v;
01577     FOR_ALL_VEHICLES(v) {
01578       v->profit_this_year <<= 8;
01579       v->profit_last_year <<= 8;
01580       v->running_ticks = 0;
01581     }
01582   }
01583 
01584   if (CheckSavegameVersion(91)) {
01585     /* Increase HouseAnimationFrame from 5 to 7 bits */
01586     for (TileIndex t = 0; t < map_size; t++) {
01587       if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
01588         SetHouseAnimationFrame(t, GB(_m[t].m6, 3, 5));
01589       }
01590     }
01591   }
01592 
01593   if (CheckSavegameVersion(62)) {
01594     /* Remove all trams from savegames without tram support.
01595      * There would be trams without tram track under causing crashes sooner or later. */
01596     Vehicle *v;
01597     FOR_ALL_VEHICLES(v) {
01598       if (v->type == VEH_ROAD && v->First() == v &&
01599           HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
01600         if (_switch_mode_errorstr == INVALID_STRING_ID || _switch_mode_errorstr == STR_NEWGRF_COMPATIBLE_LOAD_WARNING) {
01601           _switch_mode_errorstr = STR_LOADGAME_REMOVED_TRAMS;
01602         }
01603         delete v;
01604       }
01605     }
01606   }
01607 
01608   if (CheckSavegameVersion(99)) {
01609     for (TileIndex t = 0; t < map_size; t++) {
01610       /* Set newly introduced WaterClass of industry tiles */
01611       if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
01612         SetWaterClassDependingOnSurroundings(t, true);
01613       }
01614       if (IsTileType(t, MP_INDUSTRY)) {
01615         if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
01616           SetWaterClassDependingOnSurroundings(t, true);
01617         } else {
01618           SetWaterClass(t, WATER_CLASS_INVALID);
01619         }
01620       }
01621 
01622       /* Replace "house construction year" with "house age" */
01623       if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
01624         _m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
01625       }
01626     }
01627   }
01628 
01629   /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
01630    * format here, as an old layout wouldn't work properly anyway. To be safe, we
01631    * clear any possible PBS reservations as well. */
01632   if (CheckSavegameVersion(100)) {
01633     for (TileIndex t = 0; t < map_size; t++) {
01634       switch (GetTileType(t)) {
01635         case MP_RAILWAY:
01636           if (HasSignals(t)) {
01637             /* move the signal variant */
01638             SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
01639             SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
01640             ClrBit(_m[t].m2, 2);
01641             ClrBit(_m[t].m2, 6);
01642           }
01643 
01644           /* Clear PBS reservation on track */
01645           if (IsRailDepot(t) ||IsRailWaypoint(t)) {
01646             SetDepotWaypointReservation(t, false);
01647           } else {
01648             SetTrackReservation(t, TRACK_BIT_NONE);
01649           }
01650           break;
01651 
01652         case MP_ROAD: // Clear PBS reservation on crossing
01653           if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
01654           break;
01655 
01656         case MP_STATION: // Clear PBS reservation on station
01657           if (IsRailwayStation(t)) SetRailwayStationReservation(t, false);
01658           break;
01659 
01660         case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/birdges
01661           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
01662           break;
01663 
01664         default: break;
01665       }
01666     }
01667   }
01668 
01669   /* Reserve all tracks trains are currently on. */
01670   if (CheckSavegameVersion(101)) {
01671     Vehicle *v;
01672     FOR_ALL_VEHICLES(v) {
01673       if (v->type == VEH_TRAIN) {
01674         if ((v->u.rail.track & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
01675           TryReserveRailTrack(v->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(v->tile)));
01676         } else if ((v->u.rail.track & TRACK_BIT_MASK) != TRACK_BIT_NONE) {
01677           TryReserveRailTrack(v->tile, TrackBitsToTrack(v->u.rail.track));
01678         }
01679       }
01680     }
01681   }
01682 
01683   if (CheckSavegameVersion(102)) {
01684     for (TileIndex t = 0; t < map_size; t++) {
01685       /* Now all crossings should be in correct state */
01686       if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
01687     }
01688   }
01689 
01690   if (CheckSavegameVersion(103)) {
01691     /* Non-town-owned roads now store the closest town */
01692     UpdateNearestTownForRoadTiles(false);
01693 
01694     /* signs with invalid owner left from older savegames */
01695     Sign *si;
01696     FOR_ALL_SIGNS(si) {
01697       if (si->owner != OWNER_NONE && !IsValidCompanyID(si->owner)) si->owner = OWNER_NONE;
01698     }
01699 
01700     /* Station can get named based on an industry type, but the current ones
01701      * are not, so mark them as if they are not named by an industry. */
01702     Station *st;
01703     FOR_ALL_STATIONS(st) {
01704       st->indtype = IT_INVALID;
01705     }
01706   }
01707 
01708   if (CheckSavegameVersion(104)) {
01709     Vehicle *v;
01710     FOR_ALL_VEHICLES(v) {
01711       /* Set engine_type of shadow and rotor */
01712       if (v->type == VEH_AIRCRAFT && !IsNormalAircraft(v)) {
01713         v->engine_type = v->First()->engine_type;
01714       }
01715     }
01716 
01717     /* More companies ... */
01718     Company *c;
01719     FOR_ALL_COMPANIES(c) {
01720       if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
01721     }
01722 
01723     Engine *e;
01724     FOR_ALL_ENGINES(e) {
01725       if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
01726     }
01727 
01728     Town *t;
01729     FOR_ALL_TOWNS(t) {
01730       if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
01731       for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01732     }
01733   }
01734 
01735   if (CheckSavegameVersion(112)) {
01736     for (TileIndex t = 0; t < map_size; t++) {
01737       /* Check for HQ bit being set, instead of using map accessor,
01738        * since we've already changed it code-wise */
01739       if (IsTileType(t, MP_UNMOVABLE) && HasBit(_m[t].m5, 7)) {
01740         /* Move size and part identification of HQ out of the m5 attribute,
01741          * on new locations */
01742         uint8 old_m5 = _m[t].m5;
01743         _m[t].m5 = UNMOVABLE_HQ;
01744         SetCompanyHQSize(t, GB(old_m5, 2, 3));
01745         SetCompanyHQSection(t, GB(old_m5, 0, 2));
01746       }
01747     }
01748   }
01749 
01750   if (CheckSavegameVersion(113)) {
01751     /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
01752     if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
01753       _settings_game.economy.allow_town_roads = false;
01754       _settings_game.economy.town_layout = TL_BETTER_ROADS;
01755     } else {
01756       _settings_game.economy.allow_town_roads = true;
01757       _settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
01758     }
01759 
01760     /* Initialize layout of all towns. Older versions were using different
01761      * generator for random town layout, use it if needed. */
01762     Town *t;
01763     FOR_ALL_TOWNS(t) {
01764       if (_settings_game.economy.town_layout != TL_RANDOM) {
01765         t->layout = _settings_game.economy.town_layout;
01766         continue;
01767       }
01768 
01769       /* Use old layout randomizer code */
01770       byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
01771       switch (layout) {
01772         default: break;
01773         case 5: layout = 1; break;
01774         case 0: layout = 2; break;
01775       }
01776       t->layout = layout - 1;
01777     }
01778   }
01779 
01780   if (CheckSavegameVersion(114)) {
01781     /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
01782      * The conversion affects oil rigs and buoys too, but it doesn't matter as
01783      * they have st->owner == OWNER_NONE already. */
01784     Station *st;
01785     FOR_ALL_STATIONS(st) {
01786       if (!IsValidCompanyID(st->owner)) st->owner = OWNER_NONE;
01787     }
01788 
01789     /* Give owners to waypoints, based on rail tracks it is sitting on.
01790      * If none is available, specify OWNER_NONE.
01791      * This code was in CheckSavegameVersion(101) in the past, but in some cases,
01792      * the owner of waypoints could be incorrect. */
01793     Waypoint *wp;
01794     FOR_ALL_WAYPOINTS(wp) {
01795       Owner owner = IsTileType(wp->xy, MP_RAILWAY) ? GetTileOwner(wp->xy) : OWNER_NONE;
01796       wp->owner = IsValidCompanyID(owner) ? owner : OWNER_NONE;
01797     }
01798   }
01799 
01800   GamelogPrintDebug(1);
01801 
01802   bool ret = InitializeWindowsAndCaches();
01803   /* Restore the signals */
01804   signal(SIGSEGV, prev_segfault);
01805   signal(SIGABRT, prev_abort);
01806   return ret;
01807 }
01808 
01815 void ReloadNewGRFData()
01816 {
01817   /* reload grf data */
01818   GfxLoadSprites();
01819   LoadStringWidthTable();
01820   ResetEconomy();
01821   /* reload vehicles */
01822   ResetVehiclePosHash();
01823   AfterLoadVehicles(false);
01824   StartupEngines();
01825   SetCachedEngineCounts();
01826   /* update station and waypoint graphics */
01827   AfterLoadWaypoints();
01828   AfterLoadStations();
01829   /* Check and update house and town values */
01830   UpdateHousesAndTowns();
01831   /* Update livery selection windows */
01832   for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i, _loaded_newgrf_features.has_2CC);
01833   /* redraw the whole screen */
01834   MarkWholeScreenDirty();
01835   CheckTrainsLengths();
01836 }

Generated on Mon May 11 15:48:06 2009 for OpenTTD by  doxygen 1.5.6