afterload.cpp

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

Generated on Fri Jul 31 22:33:17 2009 for OpenTTD by  doxygen 1.5.6