Increase the number of road and tram subtypes to 32.
[openttd-joker.git] / src / saveload / afterload.cpp
blob5739717157b3f57b63e910bdd2c37fcaffd8d2fc
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file afterload.cpp Code updating data after game load */
12 #include "../stdafx.h"
13 #include "../void_map.h"
14 #include "../signs_base.h"
15 #include "../depot_base.h"
16 #include "../tunnel_base.h"
17 #include "../fios.h"
18 #include "../gamelog_internal.h"
19 #include "../network/network.h"
20 #include "../network/network_func.h"
21 #include "../gfxinit.h"
22 #include "../viewport_func.h"
23 #include "../industry.h"
24 #include "../clear_map.h"
25 #include "../vehicle_func.h"
26 #include "../string_func.h"
27 #include "../date_func.h"
28 #include "../roadveh.h"
29 #include "../train.h"
30 #include "../station_base.h"
31 #include "../waypoint_base.h"
32 #include "../roadstop_base.h"
33 #include "../dock_base.h"
34 #include "../tunnelbridge_map.h"
35 #include "../pathfinder/yapf/yapf_cache.h"
36 #include "../elrail_func.h"
37 #include "../signs_func.h"
38 #include "../aircraft.h"
39 #include "../object_map.h"
40 #include "../object_base.h"
41 #include "../tree_map.h"
42 #include "../company_func.h"
43 #include "../road_cmd.h"
44 #include "../ai/ai.hpp"
45 #include "../ai/ai_gui.hpp"
46 #include "../town.h"
47 #include "../economy_base.h"
48 #include "../animated_tile_func.h"
49 #include "../subsidy_base.h"
50 #include "../subsidy_func.h"
51 #include "../newgrf.h"
52 #include "../engine_func.h"
53 #include "../rail_gui.h"
54 #include "../core/backup_type.hpp"
55 #include "../smallmap_gui.h"
56 #include "../news_func.h"
57 #include "../order_backup.h"
58 #include "../error.h"
59 #include "../disaster_vehicle.h"
60 #include "../tunnel_map.h"
63 #include "saveload_internal.h"
65 #include <signal.h>
66 #include <algorithm>
68 #include "../safeguards.h"
70 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
72 /**
73 * Makes a tile canal or water depending on the surroundings.
75 * Must only be used for converting old savegames. Use WaterClass now.
77 * This as for example docks and shipdepots do not store
78 * whether the tile used to be canal or 'normal' water.
79 * @param t the tile to change.
80 * @param include_invalid_water_class Also consider WATER_CLASS_INVALID, i.e. industry tiles on land
82 void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
84 /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
85 * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
86 if (!IsTileFlat(t)) {
87 if (include_invalid_water_class) {
88 SetWaterClass(t, WATER_CLASS_INVALID);
89 return;
90 } else {
91 SlErrorCorrupt("Invalid water class for dry tile");
95 /* Mark tile dirty in all cases */
96 MarkTileDirtyByTile(t);
98 if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
99 /* tiles at map borders are always WATER_CLASS_SEA */
100 SetWaterClass(t, WATER_CLASS_SEA);
101 return;
104 bool has_water = false;
105 bool has_canal = false;
106 bool has_river = false;
108 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
109 TileIndex neighbour = TileAddByDiagDir(t, dir);
110 switch (GetTileType(neighbour)) {
111 case MP_WATER:
112 /* clear water and shipdepots have already a WaterClass associated */
113 if (IsCoast(neighbour)) {
114 has_water = true;
115 } else if (!IsLock(neighbour)) {
116 switch (GetWaterClass(neighbour)) {
117 case WATER_CLASS_SEA: has_water = true; break;
118 case WATER_CLASS_CANAL: has_canal = true; break;
119 case WATER_CLASS_RIVER: has_river = true; break;
120 default: SlErrorCorrupt("Invalid water class for tile");
123 break;
125 case MP_RAILWAY:
126 /* Shore or flooded halftile */
127 has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
128 break;
130 case MP_TREES:
131 /* trees on shore */
132 has_water |= (GB(_m[neighbour].m2, 4, 2) == TREE_GROUND_SHORE);
133 break;
135 default: break;
139 if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
140 SetWaterClass(t, WATER_CLASS_INVALID);
141 return;
144 if (has_river && !has_canal) {
145 SetWaterClass(t, WATER_CLASS_RIVER);
146 } else if (has_canal || !has_water) {
147 SetWaterClass(t, WATER_CLASS_CANAL);
148 } else {
149 SetWaterClass(t, WATER_CLASS_SEA);
153 static void ConvertTownOwner()
155 for (TileIndex tile = 0; tile != MapSize(); tile++) {
156 switch (GetTileType(tile)) {
157 case MP_ROAD:
158 if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
159 _m[tile].m3 = OWNER_TOWN;
161 FALLTHROUGH;
163 case MP_TUNNELBRIDGE:
164 if (_m[tile].m1 & 0x80) SetTileOwner(tile, OWNER_TOWN);
165 break;
167 default: break;
172 /* since savegame version 4.1, exclusive transport rights are stored at towns */
173 static void UpdateExclusiveRights()
175 Town *t;
177 FOR_ALL_TOWNS(t) {
178 t->exclusivity = INVALID_COMPANY;
181 /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
182 * could be implemented this way:
183 * 1.) Go through all stations
184 * Build an array town_blocked[ town_id ][ company_id ]
185 * that stores if at least one station in that town is blocked for a company
186 * 2.) Go through that array, if you find a town that is not blocked for
187 * one company, but for all others, then give him exclusivity.
191 static const byte convert_currency[] = {
192 0, 1, 12, 8, 3,
193 10, 14, 19, 4, 5,
194 9, 11, 13, 6, 17,
195 16, 22, 21, 7, 15,
196 18, 2, 20,
199 /* since savegame version 4.2 the currencies are arranged differently */
200 static void UpdateCurrencies()
202 _settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
205 /* Up to revision 1413 the invisible tiles at the southern border have not been
206 * MP_VOID, even though they should have. This is fixed by this function
208 static void UpdateVoidTiles()
210 uint i;
212 for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
213 for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
216 static inline RailType UpdateRailType(RailType rt, RailType min)
218 return rt >= min ? (RailType)(rt + 1): rt;
222 * Update the viewport coordinates of all signs.
224 void UpdateAllVirtCoords()
226 UpdateAllStationVirtCoords();
227 UpdateAllSignVirtCoords();
228 UpdateAllTownVirtCoords();
232 * Initialization of the windows and several kinds of caches.
233 * This is not done directly in AfterLoadGame because these
234 * functions require that all saveload conversions have been
235 * done. As people tend to add savegame conversion stuff after
236 * the intialization of the windows and caches quite some bugs
237 * had been made.
238 * Moving this out of there is both cleaner and less bug-prone.
240 static void InitializeWindowsAndCaches()
242 /* Initialize windows */
243 ResetWindowSystem();
244 SetupColoursAndInitialWindow();
246 /* Update coordinates of the signs. */
247 UpdateAllVirtCoords();
248 ResetViewportAfterLoadGame();
250 Company *c;
251 FOR_ALL_COMPANIES(c) {
252 /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
253 * accordingly if it is not the case. No need to set it on companies that are not been used already,
254 * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
255 if (_file_to_saveload.abstract_ftype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
256 c->inaugurated_year = _cur_year;
260 /* Count number of objects per type */
261 Object *o;
262 FOR_ALL_OBJECTS(o) {
263 Object::IncTypeCount(o->type);
266 /* Identify owners of persistent storage arrays */
267 Industry *i;
268 FOR_ALL_INDUSTRIES(i) {
269 if (i->psa != nullptr) {
270 i->psa->feature = GSF_INDUSTRIES;
271 i->psa->tile = i->location.tile;
274 Station *s;
275 FOR_ALL_STATIONS(s) {
276 if (s->airport.psa != nullptr) {
277 s->airport.psa->feature = GSF_AIRPORTS;
278 s->airport.psa->tile = s->airport.tile;
281 Town *t;
282 FOR_ALL_TOWNS(t) {
283 for (std::list<PersistentStorage *>::iterator it = t->psa_list.begin(); it != t->psa_list.end(); ++it) {
284 (*it)->feature = GSF_FAKE_TOWNS;
285 (*it)->tile = t->xy;
288 RoadVehicle *rv;
289 FOR_ALL_ROADVEHICLES(rv) {
290 if (rv->IsFrontEngine()) {
291 rv->CargoChanged();
295 RecomputePrices();
297 GroupStatistics::UpdateAfterLoad();
299 Station::RecomputeIndustriesNearForAll();
300 RebuildSubsidisedSourceAndDestinationCache();
302 /* Towns have a noise controlled number of airports system
303 * So each airport's noise value must be added to the town->noise_reached value
304 * Reset each town's noise_reached value to '0' before. */
305 UpdateAirportsNoise();
307 CheckTrainsLengths();
308 ShowNewGRFError();
309 ShowAIDebugWindowIfAIError();
311 /* Rebuild the smallmap list of owners. */
312 BuildOwnerLegend();
315 typedef void (CDECL *SignalHandlerPointer)(int);
316 static SignalHandlerPointer _prev_segfault = nullptr;
317 static SignalHandlerPointer _prev_abort = nullptr;
318 static SignalHandlerPointer _prev_fpe = nullptr;
320 static void CDECL HandleSavegameLoadCrash(int signum);
323 * Replaces signal handlers of SIGSEGV and SIGABRT
324 * and stores pointers to original handlers in memory.
326 static void SetSignalHandlers()
328 _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
329 _prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
330 _prev_fpe = signal(SIGFPE, HandleSavegameLoadCrash);
334 * Resets signal handlers back to original handlers.
336 static void ResetSignalHandlers()
338 signal(SIGSEGV, _prev_segfault);
339 signal(SIGABRT, _prev_abort);
340 signal(SIGFPE, _prev_fpe);
344 * Try to find the overridden GRF identifier of the given GRF.
345 * @param c the GRF to get the 'previous' version of.
346 * @return the GRF identifier or \a c if none could be found.
348 static const GRFIdentifier *GetOverriddenIdentifier(const GRFConfig *c)
350 const LoggedAction *la = &_gamelog_action[_gamelog_actions - 1];
351 if (la->at != GLAT_LOAD) return &c->ident;
353 const LoggedChange *lcend = &la->change[la->changes];
354 for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
355 if (lc->ct == GLCT_GRFCOMPAT && lc->grfcompat.grfid == c->ident.grfid) return &lc->grfcompat;
358 return &c->ident;
361 /** Was the saveload crash because of missing NewGRFs? */
362 static bool _saveload_crash_with_missing_newgrfs = false;
365 * Did loading the savegame cause a crash? If so,
366 * were NewGRFs missing?
367 * @return when the saveload crashed due to missing NewGRFs.
369 bool SaveloadCrashWithMissingNewGRFs()
371 return _saveload_crash_with_missing_newgrfs;
375 * Signal handler used to give a user a more useful report for crashes during
376 * the savegame loading process; especially when there's problems with the
377 * NewGRFs that are required by the savegame.
378 * @param signum received signal
380 static void CDECL HandleSavegameLoadCrash(int signum)
382 ResetSignalHandlers();
384 char buffer[8192];
385 char *p = buffer;
386 p += seprintf(p, lastof(buffer), "Loading your savegame caused OpenTTD to crash.\n");
388 for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != nullptr; c = c->next) {
389 _saveload_crash_with_missing_newgrfs = HasBit(c->flags, GCF_COMPATIBLE) || c->status == GCS_NOT_FOUND;
392 if (_saveload_crash_with_missing_newgrfs) {
393 p += seprintf(p, lastof(buffer),
394 "This is most likely caused by a missing NewGRF or a NewGRF that\n"
395 "has been loaded as replacement for a missing NewGRF. OpenTTD\n"
396 "cannot easily determine whether a replacement NewGRF is of a newer\n"
397 "or older version.\n"
398 "It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
399 "This means that if the author makes incompatible NewGRFs with the\n"
400 "same GRF ID OpenTTD cannot magically do the right thing. In most\n"
401 "cases OpenTTD will load the savegame and not crash, but this is an\n"
402 "exception.\n"
403 "Please load the savegame with the appropriate NewGRFs installed.\n"
404 "The missing/compatible NewGRFs are:\n");
406 for (const GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
407 if (HasBit(c->flags, GCF_COMPATIBLE)) {
408 const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
409 char buf[40];
410 md5sumToString(buf, lastof(buf), replaced->md5sum);
411 p += seprintf(p, lastof(buffer), "NewGRF %08X (checksum %s) not found.\n Loaded NewGRF \"%s\" with same GRF ID instead.\n", BSWAP32(c->ident.grfid), buf, c->filename);
413 if (c->status == GCS_NOT_FOUND) {
414 char buf[40];
415 md5sumToString(buf, lastof(buf), c->ident.md5sum);
416 p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s.\n", BSWAP32(c->ident.grfid), c->filename, buf);
419 } else {
420 p += seprintf(p, lastof(buffer),
421 "This is probably caused by a corruption in the savegame.\n"
422 "Please file a bug report and attach this savegame.\n");
425 ShowInfo(buffer);
427 SignalHandlerPointer call = nullptr;
428 switch (signum) {
429 case SIGSEGV: call = _prev_segfault; break;
430 case SIGABRT: call = _prev_abort; break;
431 case SIGFPE: call = _prev_fpe; break;
432 default: NOT_REACHED();
434 if (call != nullptr) call(signum);
438 * Tries to change owner of this rail tile to a valid owner. In very old versions it could happen that
439 * a rail track had an invalid owner. When conversion isn't possible, track is removed.
440 * @param t tile to update
442 static void FixOwnerOfRailTrack(TileIndex t)
444 assert(!Company::IsValidID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
446 /* remove leftover rail piece from crossing (from very old savegames) */
447 Train *v = nullptr, *w;
448 FOR_ALL_TRAINS(w) {
449 if (w->tile == t) {
450 v = w;
451 break;
455 if (v != nullptr) {
456 /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
457 SetTileOwner(t, v->owner);
458 return;
461 /* try to find any connected rail */
462 for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
463 TileIndex tt = t + TileOffsByDiagDir(dd);
464 if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
465 GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
466 Company::IsValidID(GetTileOwner(tt))) {
467 SetTileOwner(t, GetTileOwner(tt));
468 return;
472 if (IsLevelCrossingTile(t)) {
473 /* else change the crossing to normal road (road vehicles won't care) */
474 Owner road = GetRoadOwner(t, ROADTYPE_ROAD);
475 Owner tram = GetRoadOwner(t, ROADTYPE_TRAM);
476 RoadBits bits = GetCrossingRoadBits(t);
477 RoadTypes rts = (RoadTypes)GB(_me[t].m7, 6, 2);
479 /* MakeRoadNormal */
480 SetTileType(t, MP_ROAD);
481 SetTileOwner(t, road);
482 _m[t].m3 = (HasBit(rts, ROADTYPE_ROAD) ? bits : 0);
483 _m[t].m5 = (HasBit(rts, ROADTYPE_TRAM) ? bits : 0) | ROAD_TILE_NORMAL << 6;
484 SB(_me[t].m6, 2, 4, 0);
485 SetRoadOwner(t, ROADTYPE_TRAM, tram);
486 return;
489 /* if it's not a crossing, make it clean land */
490 MakeClear(t, CLEAR_GRASS, 0);
494 * Fixes inclination of a vehicle. Older OpenTTD versions didn't update the bits correctly.
495 * @param v vehicle
496 * @param dir vehicle's direction, or # INVALID_DIR if it can be ignored
497 * @return inclination bits to set
499 static uint FixVehicleInclination(Vehicle *v, Direction dir)
501 /* Compute place where this vehicle entered the tile */
502 int entry_x = v->x_pos;
503 int entry_y = v->y_pos;
504 switch (dir) {
505 case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
506 case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
507 case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
508 case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
509 case INVALID_DIR: break;
510 default: NOT_REACHED();
512 byte entry_z = GetSlopePixelZ(entry_x, entry_y);
514 /* Compute middle of the tile. */
515 int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
516 int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
517 byte middle_z = GetSlopePixelZ(middle_x, middle_y);
519 /* middle_z == entry_z, no height change. */
520 if (middle_z == entry_z) return 0;
522 /* middle_z < entry_z, we are going downwards. */
523 if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
525 /* middle_z > entry_z, we are going upwards. */
526 return 1U << GVF_GOINGUP_BIT;
530 * Checks for the possibility that a bridge may be on this tile
531 * These are in fact all the tile types on which a bridge can be found
532 * @param t The tile to analyze
533 * @return True if a bridge might have been present prior to savegame 194 or to patch pack savegame SL_PATCH_PACK_1_9.
535 static inline bool MayHaveBridgeAbove(TileIndex t)
537 return IsTileType(t, MP_CLEAR) || IsTileType(t, MP_RAILWAY) || IsTileType(t, MP_ROAD) ||
538 IsTileType(t, MP_WATER) || IsTileType(t, MP_TUNNELBRIDGE) || IsTileType(t, MP_OBJECT);
541 TileIndex GetOtherTunnelBridgeEndOld(TileIndex tile)
543 DiagDirection dir = GetTunnelBridgeDirection(tile);
544 TileIndexDiff delta = TileOffsByDiagDir(dir);
545 int z = GetTileZ(tile);
547 dir = ReverseDiagDir(dir);
548 do {
549 tile += delta;
550 } while (
551 !IsTunnelTile(tile) ||
552 GetTunnelBridgeDirection(tile) != dir ||
553 GetTileZ(tile) != z
556 return tile;
560 * Perform a (large) amount of savegame conversion *magic* in order to
561 * load older savegames and to fill the caches for various purposes.
562 * @return True iff conversion went without a problem.
564 bool AfterLoadGame()
566 SetSignalHandlers();
568 TileIndex map_size = MapSize();
570 extern TileIndex _cur_tileloop_tile; // From landscape.cpp.
571 /* The LFSR used in RunTileLoop iteration cannot have a zeroed state, make it non-zeroed. */
572 if (_cur_tileloop_tile == 0) _cur_tileloop_tile = 1;
574 if (IsSavegameVersionBefore(98)) GamelogOldver();
576 GamelogTestRevision();
577 GamelogTestMode();
579 if (IsSavegameVersionBefore(98)) GamelogGRFAddList(_grfconfig);
581 if (IsSavegameVersionBefore(119)) {
582 _pause_mode = (_pause_mode == 2) ? PM_PAUSED_NORMAL : PM_UNPAUSED;
583 } else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
584 DEBUG(net, 0, "The loading savegame was paused due to an error state.");
585 DEBUG(net, 0, " The savegame cannot be used for multiplayer!");
586 /* Restore the signals */
587 ResetSignalHandlers();
588 return false;
589 } else if (!_networking || _network_server) {
590 /* If we are in single player, i.e. not networking, and loading the
591 * savegame or we are loading the savegame as network server we do
592 * not want to be bothered by being paused because of the automatic
593 * reason of a network server, e.g. joining clients or too few
594 * active clients. Note that resetting these values for a network
595 * client are very bad because then the client is going to execute
596 * the game loop when the server is not, i.e. it desyncs. */
597 _pause_mode &= ~PMB_PAUSED_NETWORK;
600 /* In very old versions, size of train stations was stored differently.
601 * They had swapped width and height if station was built along the Y axis.
602 * TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
603 * Because the data stored by TTDPatch are unusable for rail stations > 7x7,
604 * recompute the width and height. Doing this unconditionally for all old
605 * savegames simplifies the code. */
606 if (IsSavegameVersionBefore(2)) {
607 Station *st;
608 FOR_ALL_STATIONS(st) {
609 st->train_station.w = st->train_station.h = 0;
611 for (TileIndex t = 0; t < map_size; t++) {
612 if (!IsTileType(t, MP_STATION)) continue;
613 if (_m[t].m5 > 7) continue; // is it a rail station tile?
614 st = Station::Get(_m[t].m2);
615 assert(st->train_station.tile != 0);
616 int dx = TileX(t) - TileX(st->train_station.tile);
617 int dy = TileY(t) - TileY(st->train_station.tile);
618 assert(dx >= 0 && dy >= 0);
619 st->train_station.w = max<uint>(st->train_station.w, dx + 1);
620 st->train_station.h = max<uint>(st->train_station.h, dy + 1);
624 if (IsSavegameVersionBefore(194) || IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_9)) {
625 _settings_game.construction.max_heightlevel = 15;
627 /* In old savegame versions, the heightlevel was coded in bits 0..3 of the type field */
628 for (TileIndex t = 0; t < map_size; t++) {
629 _m[t].height = GB(_m[t].type, 0, 4);
630 SB(_m[t].type, 0, 2, GB(_me[t].m6, 0, 2));
631 SB(_me[t].m6, 0, 2, 0);
632 if (MayHaveBridgeAbove(t)) {
633 SB(_m[t].type, 2, 2, GB(_me[t].m6, 6, 2));
634 SB(_me[t].m6, 6, 2, 0);
635 } else {
636 SB(_m[t].type, 2, 2, 0);
641 /* in version 2.1 of the savegame, town owner was unified. */
642 if (IsSavegameVersionBefore(2, 1)) ConvertTownOwner();
644 /* from version 4.1 of the savegame, exclusive rights are stored at towns */
645 if (IsSavegameVersionBefore(4, 1)) UpdateExclusiveRights();
647 /* from version 4.2 of the savegame, currencies are in a different order */
648 if (IsSavegameVersionBefore(4, 2)) UpdateCurrencies();
650 /* In old version there seems to be a problem that water is owned by
651 * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
652 * (4.3) version, so I just check when versions are older, and then
653 * walk through the whole map.. */
654 if (IsSavegameVersionBefore(4, 3)) {
655 for (TileIndex t = 0; t < map_size; t++) {
656 if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
657 SetTileOwner(t, OWNER_WATER);
662 if (IsSavegameVersionBefore(84)) {
663 Company *c;
664 FOR_ALL_COMPANIES(c) {
665 c->name = CopyFromOldName(c->name_1);
666 if (c->name != nullptr) c->name_1 = STR_SV_UNNAMED;
667 c->president_name = CopyFromOldName(c->president_name_1);
668 if (c->president_name != nullptr) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
671 Station *st;
672 FOR_ALL_STATIONS(st) {
673 st->name = CopyFromOldName(st->string_id);
674 /* generating new name would be too much work for little effect, use the station name fallback */
675 if (st->name != nullptr) st->string_id = STR_SV_STNAME_FALLBACK;
678 Town *t;
679 FOR_ALL_TOWNS(t) {
680 t->name = CopyFromOldName(t->townnametype);
681 if (t->name != nullptr) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
685 /* From this point the old names array is cleared. */
686 ResetOldNames();
688 if (IsSavegameVersionBefore(106)) {
689 /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
690 Station *st;
691 FOR_ALL_STATIONS(st) {
692 if (st->airport.tile == 0) st->airport.tile = INVALID_TILE;
693 if (st->dock_station.tile == 0) st->dock_station.tile = INVALID_TILE;
694 if (st->train_station.tile == 0) st->train_station.tile = INVALID_TILE;
697 /* the same applies to Company::location_of_HQ */
698 Company *c;
699 FOR_ALL_COMPANIES(c) {
700 if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(4) && c->location_of_HQ == 0xFFFF)) {
701 c->location_of_HQ = INVALID_TILE;
706 /* convert road side to my format. */
707 if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
709 /* Check if all NewGRFs are present, we are very strict in MP mode */
710 GRFListCompatibility gcf_res = IsGoodGRFConfigList(_grfconfig);
711 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
712 if (c->status == GCS_NOT_FOUND) {
713 GamelogGRFRemove(c->ident.grfid);
714 } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
715 GamelogGRFCompatible(&c->ident);
719 if (_networking && gcf_res != GLC_ALL_GOOD) {
720 SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
721 /* Restore the signals */
722 ResetSignalHandlers();
723 return false;
726 switch (gcf_res) {
727 case GLC_COMPATIBLE: ShowErrorMessage(STR_NEWGRF_COMPATIBLE_LOAD_WARNING, INVALID_STRING_ID, WL_CRITICAL); break;
728 case GLC_NOT_FOUND: ShowErrorMessage(STR_NEWGRF_DISABLED_WARNING, INVALID_STRING_ID, WL_CRITICAL); _pause_mode = PM_PAUSED_ERROR; break;
729 default: break;
732 /* The value of _date_fract got divided, so make sure that old games are converted correctly. */
733 if (IsSavegameVersionBefore(11, 1) || (IsSavegameVersionBefore(147) && _date_fract > DAY_TICKS)) _date_fract /= 885;
735 if (IsSavegameVersionBefore(SL_PATCH_PACK_DAYLENGTH))
737 if (!IsPatchPackSavegameVersionBefore(SL_PATCH_PACK))
738 _settings_game.economy.daylength = 4;
739 else
740 _settings_game.economy.daylength = 1;
743 /* Update current year
744 * must be done before loading sprites as some newgrfs check it */
745 SetDate(_date, _date_fract);
748 * Force the old behaviour for compatibility reasons with old savegames. As new
749 * settings can only be loaded from new savegames loading old savegames with new
750 * versions of OpenTTD will normally initialize settings newer than the savegame
751 * version with "new game" defaults which the player can define to their liking.
752 * For some settings we override that to keep the behaviour the same as when the
753 * game was saved.
755 * Note that there is no non-stop in here. This is because the setting could have
756 * either value in TTDPatch. To convert it properly the user has to make sure the
757 * right value has been chosen in the settings. Otherwise we will be converting
758 * it incorrectly in half of the times without a means to correct that.
760 if (IsSavegameVersionBefore(4, 2)) _settings_game.station.modified_catchment = false;
761 if (IsSavegameVersionBefore(6, 1)) _settings_game.pf.forbid_90_deg = false;
762 if (IsSavegameVersionBefore(21)) _settings_game.vehicle.train_acceleration_model = 0;
763 if (IsSavegameVersionBefore(90)) _settings_game.vehicle.plane_speed = 4;
764 if (IsSavegameVersionBefore(95)) _settings_game.vehicle.dynamic_engines = 0;
765 if (IsSavegameVersionBefore(96)) _settings_game.economy.station_noise_level = false;
766 if (IsSavegameVersionBefore(133)) {
767 _settings_game.vehicle.train_slope_steepness = 3;
769 if (IsSavegameVersionBefore(134)) _settings_game.economy.feeder_payment_share = 75;
770 if (IsSavegameVersionBefore(138)) _settings_game.vehicle.plane_crashes = 2;
771 if (IsSavegameVersionBefore(139)) {
772 _settings_game.vehicle.roadveh_acceleration_model = 0;
773 _settings_game.vehicle.roadveh_slope_steepness = 7;
775 if (IsSavegameVersionBefore(143)) _settings_game.economy.allow_town_level_crossings = true;
776 if (IsSavegameVersionBefore(159)) {
777 _settings_game.vehicle.max_train_length = 50;
778 _settings_game.construction.max_bridge_length = 64;
779 _settings_game.construction.max_tunnel_length = 64;
781 if (IsSavegameVersionBefore(166)) _settings_game.economy.infrastructure_maintenance = false;
782 if (IsSavegameVersionBefore(183)) {
783 _settings_game.linkgraph.distribution_pax = DT_MANUAL;
784 _settings_game.linkgraph.distribution_mail = DT_MANUAL;
785 _settings_game.linkgraph.distribution_armoured = DT_MANUAL;
786 _settings_game.linkgraph.distribution_default = DT_MANUAL;
789 /* Load the sprites */
790 GfxLoadSprites();
791 LoadStringWidthTable();
793 /* Copy temporary data to Engine pool */
794 CopyTempEngineData();
796 /* Connect front and rear engines of multiheaded trains and converts
797 * subtype to the new format */
798 if (IsSavegameVersionBefore(17, 1)) ConvertOldMultiheadToNew();
800 /* Connect front and rear engines of multiheaded trains */
801 ConnectMultiheadedTrains();
803 /* Fix the CargoPackets *and* fix the caches of CargoLists.
804 * If this isn't done before Stations and especially Vehicles are
805 * running their AfterLoad we might get in trouble. In the case of
806 * vehicles we could give the wrong (cached) count of items in a
807 * vehicle which causes different results when getting their caches
808 * filled; and that could eventually lead to desyncs. */
809 CargoPacket::AfterLoad();
811 /* Oilrig was moved from id 15 to 9. We have to do this conversion
812 * here as AfterLoadVehicles can check it indirectly via the newgrf
813 * code. */
814 if (IsSavegameVersionBefore(139)) {
815 Station *st;
816 FOR_ALL_STATIONS(st) {
817 if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
818 st->airport.type = AT_OILRIG;
823 /* Update all vehicles */
824 AfterLoadVehicles(true);
826 /* Update old version of trip history */
827 AfterLoadTripHistory();
829 /* Update template vehicles */
830 AfterLoadTemplateVehicles();
832 /* Make sure there is an AI attached to an AI company */
834 Company *c;
835 FOR_ALL_COMPANIES(c) {
836 if (c->is_ai && c->ai_instance == nullptr) AI::StartNew(c->index);
840 /* make sure there is a town in the game */
841 if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
842 SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
843 /* Restore the signals */
844 ResetSignalHandlers();
845 return false;
848 /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
849 * This problem appears in savegame version 21 too, see r3455. But after loading the
850 * savegame and saving again, the buggy map array could be converted to new savegame
851 * version. It didn't show up before r12070. */
852 if (IsSavegameVersionBefore(87)) UpdateVoidTiles();
854 /* If Load Scenario / New (Scenario) Game is used,
855 * a company does not exist yet. So create one here.
856 * 1 exception: network-games. Those can have 0 companies
857 * But this exception is not true for non-dedicated network servers! */
858 if (!Company::IsValidID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated))) {
859 DoStartupNewCompany(false);
860 Company *c = Company::Get(COMPANY_FIRST);
861 c->settings = _settings_client.company;
864 /* Fix the cache for cargo payments. */
865 CargoPayment *cp;
866 FOR_ALL_CARGO_PAYMENTS(cp) {
867 cp->front->cargo_payment = cp;
868 cp->current_station = cp->front->last_station_visited;
871 if (IsSavegameVersionBefore(72)) {
872 /* Locks in very old savegames had OWNER_WATER as owner */
873 for (TileIndex t = 0; t < MapSize(); t++) {
874 switch (GetTileType(t)) {
875 default: break;
877 case MP_WATER:
878 if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
879 break;
881 case MP_STATION: {
882 if (HasBit(_me[t].m6, 3)) SetBit(_me[t].m6, 2);
883 StationGfx gfx = GetStationGfx(t);
884 StationType st;
885 if ( IsInsideMM(gfx, 0, 8)) { // Rail station
886 st = STATION_RAIL;
887 SetStationGfx(t, gfx - 0);
888 } else if (IsInsideMM(gfx, 8, 67)) { // Airport
889 st = STATION_AIRPORT;
890 SetStationGfx(t, gfx - 8);
891 } else if (IsInsideMM(gfx, 67, 71)) { // Truck
892 st = STATION_TRUCK;
893 SetStationGfx(t, gfx - 67);
894 } else if (IsInsideMM(gfx, 71, 75)) { // Bus
895 st = STATION_BUS;
896 SetStationGfx(t, gfx - 71);
897 } else if (gfx == 75) { // Oil rig
898 st = STATION_OILRIG;
899 SetStationGfx(t, gfx - 75);
900 } else if (IsInsideMM(gfx, 76, 82)) { // Dock
901 st = STATION_DOCK;
902 SetStationGfx(t, gfx - 76);
903 } else if (gfx == 82) { // Buoy
904 st = STATION_BUOY;
905 SetStationGfx(t, gfx - 82);
906 } else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
907 st = STATION_AIRPORT;
908 SetStationGfx(t, gfx - 83 + 67 - 8);
909 } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
910 st = STATION_TRUCK;
911 SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
912 } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
913 st = STATION_BUS;
914 SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
915 } else {
916 /* Restore the signals */
917 ResetSignalHandlers();
918 return false;
920 SB(_me[t].m6, 3, 3, st);
921 break;
927 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_18)) {
928 /* Dock type has changed. */
929 Station *st;
930 FOR_ALL_STATIONS(st) {
931 if (st->dock_station.tile == INVALID_TILE) continue;
932 assert(Dock::CanAllocateItem());
933 if (IsOilRig(st->dock_station.tile)) {
934 /* Set dock station tile to dest tile instead of station. */
935 st->docks = new Dock(st->dock_station.tile, st->dock_station.tile + ToTileIndexDiff({ 1, 0 }));
936 } else if (IsDock(st->dock_station.tile)) {
937 /* A normal two-tiles dock. */
938 st->docks = new Dock(st->dock_station.tile, TileAddByDiagDir(st->dock_station.tile, GetDockDirection(st->dock_station.tile)));
939 } else if (IsBuoy(st->dock_station.tile)) {
940 /* A buoy. */
941 } else {
942 NOT_REACHED();
947 for (TileIndex t = 0; t < map_size; t++) {
948 switch (GetTileType(t)) {
949 case MP_STATION: {
950 BaseStation *bst = BaseStation::GetByTile(t);
952 /* Set up station spread */
953 bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
955 /* Waypoints don't have road stops/oil rigs in the old format */
956 if (!Station::IsExpected(bst)) break;
957 Station *st = Station::From(bst);
959 /* Set up station catchment */
960 st->catchment.BeforeAddTile(t, st->GetCatchmentRadius());
962 switch (GetStationType(t)) {
963 case STATION_TRUCK:
964 case STATION_BUS:
965 if (IsSavegameVersionBefore(6)) {
966 /* Before version 5 you could not have more than 250 stations.
967 * Version 6 adds large maps, so you could only place 253*253
968 * road stops on a map (no freeform edges) = 64009. So, yes
969 * someone could in theory create such a full map to trigger
970 * this assertion, it's safe to assume that's only something
971 * theoretical and does not happen in normal games. */
972 assert(RoadStop::CanAllocateItem());
974 /* From this version on there can be multiple road stops of the
975 * same type per station. Convert the existing stops to the new
976 * internal data structure. */
977 RoadStop *rs = new RoadStop(t);
979 RoadStop **head =
980 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
981 *head = rs;
983 break;
985 case STATION_OILRIG: {
986 /* Very old savegames sometimes have phantom oil rigs, i.e.
987 * an oil rig which got shut down, but not completely removed from
988 * the map
990 TileIndex t1 = TILE_ADDXY(t, 0, 1);
991 if (IsTileType(t1, MP_INDUSTRY) &&
992 GetIndustryGfx(t1) == GFX_OILRIG_1) {
993 /* The internal encoding of oil rigs was changed twice.
994 * It was 3 (till 2.2) and later 5 (till 5.1).
995 * Setting it unconditionally does not hurt.
997 Station::GetByTile(t)->airport.type = AT_OILRIG;
998 } else {
999 DeleteOilRig(t);
1001 break;
1004 default: break;
1006 break;
1009 default: break;
1013 /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
1014 * This has to be called after the oilrig airport_type update above ^^^ ! */
1015 if (IsSavegameVersionBefore(2, 2)) UpdateOldAircraft();
1017 /* In version 6.1 we put the town index in the map-array. To do this, we need
1018 * to use m2 (16bit big), so we need to clean m2, and that is where this is
1019 * all about ;) */
1020 if (IsSavegameVersionBefore(6, 1)) {
1021 for (TileIndex t = 0; t < map_size; t++) {
1022 switch (GetTileType(t)) {
1023 case MP_HOUSE:
1024 _m[t].m4 = _m[t].m2;
1025 SetTownIndex(t, CalcClosestTownFromTile(t)->index);
1026 break;
1028 case MP_ROAD:
1029 _m[t].m4 |= (_m[t].m2 << 4);
1030 if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
1031 SetTownIndex(t, CalcClosestTownFromTile(t)->index);
1032 } else {
1033 SetTownIndex(t, 0);
1035 break;
1037 default: break;
1042 /* Force the freeform edges to false for old savegames. */
1043 if (IsSavegameVersionBefore(111)) {
1044 _settings_game.construction.freeform_edges = false;
1047 /* From version 9.0, we update the max passengers of a town (was sometimes negative
1048 * before that. */
1049 if (IsSavegameVersionBefore(9)) {
1050 Town *t;
1051 FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
1054 /* From version 16.0, we included autorenew on engines, which are now saved, but
1055 * of course, we do need to initialize them for older savegames. */
1056 if (IsSavegameVersionBefore(16)) {
1057 Company *c;
1058 FOR_ALL_COMPANIES(c) {
1059 c->engine_renew_list = nullptr;
1060 c->settings.engine_renew = false;
1061 c->settings.engine_renew_months = 6;
1062 c->settings.engine_renew_money = 100000;
1065 /* When loading a game, _local_company is not yet set to the correct value.
1066 * However, in a dedicated server we are a spectator, so nothing needs to
1067 * happen. In case we are not a dedicated server, the local company always
1068 * becomes company 0, unless we are in the scenario editor where all the
1069 * companies are 'invalid'.
1071 c = Company::GetIfValid(COMPANY_FIRST);
1072 if (!_network_dedicated && c != nullptr) {
1073 c->settings = _settings_client.company;
1077 if (IsSavegameVersionBefore(48)) {
1078 for (TileIndex t = 0; t < map_size; t++) {
1079 switch (GetTileType(t)) {
1080 case MP_RAILWAY:
1081 if (IsPlainRail(t)) {
1082 /* Swap ground type and signal type for plain rail tiles, so the
1083 * ground type uses the same bits as for depots and waypoints. */
1084 uint tmp = GB(_m[t].m4, 0, 4);
1085 SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
1086 SB(_m[t].m2, 0, 4, tmp);
1087 } else if (HasBit(_m[t].m5, 2)) {
1088 /* Split waypoint and depot rail type and remove the subtype. */
1089 ClrBit(_m[t].m5, 2);
1090 ClrBit(_m[t].m5, 6);
1092 break;
1094 case MP_ROAD:
1095 /* Swap m3 and m4, so the track type for rail crossings is the
1096 * same as for normal rail. */
1097 Swap(_m[t].m3, _m[t].m4);
1098 break;
1100 default: break;
1105 if (IsSavegameVersionBefore(61)) {
1106 /* Added the RoadType */
1107 bool old_bridge = IsSavegameVersionBefore(42);
1108 for (TileIndex t = 0; t < map_size; t++) {
1109 switch (GetTileType(t)) {
1110 case MP_ROAD:
1111 SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
1112 switch (GetRoadTileType(t)) {
1113 default: SlErrorCorrupt("Invalid road tile type");
1114 case ROAD_TILE_NORMAL:
1115 SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
1116 SB(_m[t].m4, 4, 4, 0);
1117 SB(_me[t].m6, 2, 4, 0);
1118 break;
1119 case ROAD_TILE_CROSSING:
1120 SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
1121 break;
1122 case ROAD_TILE_DEPOT: break;
1124 SB(_me[t].m7, 6, 2, ROADTYPES_ROAD);
1125 break;
1127 case MP_STATION:
1128 if (IsRoadStop(t)) SB(_me[t].m7, 6, 2, ROADTYPES_ROAD);
1129 break;
1131 case MP_TUNNELBRIDGE:
1132 /* Middle part of "old" bridges */
1133 if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
1134 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1135 SB(_me[t].m7, 6, 2, ROADTYPES_ROAD);
1137 break;
1139 default: break;
1144 if (IsSavegameVersionBefore(114)) {
1145 bool fix_roadtypes = !IsSavegameVersionBefore(61);
1146 bool old_bridge = IsSavegameVersionBefore(42);
1148 for (TileIndex t = 0; t < map_size; t++) {
1149 switch (GetTileType(t)) {
1150 case MP_ROAD:
1151 if (fix_roadtypes) SB(_me[t].m7, 6, 2, (RoadTypes)GB(_me[t].m7, 5, 3));
1152 SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
1153 switch (GetRoadTileType(t)) {
1154 default: SlErrorCorrupt("Invalid road tile type");
1155 case ROAD_TILE_NORMAL:
1156 SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
1157 SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
1158 SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4)); // tram bits
1159 SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
1160 SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4)); // road bits
1161 break;
1163 case ROAD_TILE_CROSSING:
1164 SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
1165 SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
1166 SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
1167 SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1)); // road axis
1168 SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1)); // crossing state
1169 break;
1171 case ROAD_TILE_DEPOT:
1172 break;
1174 if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1175 const Town *town = CalcClosestTownFromTile(t);
1176 if (town != nullptr) SetTownIndex(t, town->index);
1178 _m[t].m4 = 0;
1179 break;
1181 case MP_STATION:
1182 if (!IsRoadStop(t)) break;
1184 if (fix_roadtypes) SB(_me[t].m7, 6, 2, (RoadTypes)GB(_m[t].m3, 0, 3));
1185 SB(_me[t].m7, 0, 5, HasBit(_me[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
1186 SB(_m[t].m3, 4, 4, _m[t].m1);
1187 _m[t].m4 = 0;
1188 break;
1190 case MP_TUNNELBRIDGE:
1191 if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
1192 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1193 if (fix_roadtypes) SB(_me[t].m7, 6, 2, (RoadTypes)GB(_m[t].m3, 0, 3));
1195 Owner o = GetTileOwner(t);
1196 SB(_me[t].m7, 0, 5, o); // road owner
1197 SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
1199 SB(_me[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
1200 SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
1202 _m[t].m2 = 0;
1203 _m[t].m4 = 0;
1204 break;
1206 default: break;
1211 if (IsSavegameVersionBefore(42)) {
1212 Vehicle *v;
1214 for (TileIndex t = 0; t < map_size; t++) {
1215 if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
1216 if (IsBridgeTile(t)) {
1217 if (HasBit(_m[t].m5, 6)) { // middle part
1218 Axis axis = (Axis)GB(_m[t].m5, 0, 1);
1220 if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
1221 if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
1222 MakeRailNormal(
1224 GetTileOwner(t),
1225 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
1226 GetRailType(t)
1228 } else {
1229 TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
1231 /* MakeRoadNormal */
1232 SetTileType(t, MP_ROAD);
1233 _m[t].m2 = town;
1234 _m[t].m3 = 0;
1235 _m[t].m5 = (axis == AXIS_X ? ROAD_Y : ROAD_X) | ROAD_TILE_NORMAL << 6;
1236 SB(_me[t].m6, 2, 4, 0);
1237 _me[t].m7 = ROADTYPES_ROAD << 6;
1238 SetRoadOwner(t, ROADTYPE_TRAM, OWNER_NONE);
1240 } else {
1241 if (GB(_m[t].m5, 3, 2) == 0) {
1242 MakeClear(t, CLEAR_GRASS, 3);
1243 } else {
1244 if (!IsTileFlat(t)) {
1245 MakeShore(t);
1246 } else {
1247 if (GetTileOwner(t) == OWNER_WATER) {
1248 MakeSea(t);
1249 } else {
1250 MakeCanal(t, GetTileOwner(t), Random());
1255 SetBridgeMiddle(t, axis);
1256 } else { // ramp
1257 Axis axis = (Axis)GB(_m[t].m5, 0, 1);
1258 uint north_south = GB(_m[t].m5, 5, 1);
1259 DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
1260 TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
1262 _m[t].m5 = 1 << 7 | type << 2 | dir;
1267 FOR_ALL_VEHICLES(v) {
1268 if (!v->IsGroundVehicle()) continue;
1269 if (IsBridgeTile(v->tile)) {
1270 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
1272 if (dir != DirToDiagDir(v->direction)) continue;
1273 switch (dir) {
1274 default: SlErrorCorrupt("Invalid vehicle direction");
1275 case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
1276 case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
1277 case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
1278 case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
1280 } else if (v->z_pos > GetSlopePixelZ(v->x_pos, v->y_pos)) {
1281 v->tile = GetNorthernBridgeEnd(v->tile);
1282 } else {
1283 continue;
1285 if (v->type == VEH_TRAIN) {
1286 Train::From(v)->track = TRACK_BIT_WORMHOLE;
1287 } else {
1288 RoadVehicle::From(v)->state = RVSB_WORMHOLE;
1293 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_27)) {
1294 // Add road subtypes.
1295 for (TileIndex t = 0; t < map_size; t++) {
1296 bool has_road = false;
1297 switch (GetTileType(t)) {
1298 case MP_ROAD:
1299 has_road = true;
1300 break;
1301 case MP_STATION:
1302 has_road = IsRoadStop(t);
1303 break;
1304 case MP_TUNNELBRIDGE:
1305 has_road = GetTunnelBridgeTransportType(t) == TRANSPORT_ROAD;
1306 break;
1307 default:
1308 break;
1311 if (has_road) {
1312 RoadTypeIdentifiers rtids;
1313 if (HasBit(_me[t].m7, 6)) rtids.road_identifier = RoadTypeIdentifier(ROADTYPE_ROAD, ROADSUBTYPE_NORMAL);
1314 if (HasBit(_me[t].m7, 7)) rtids.tram_identifier = RoadTypeIdentifier(ROADTYPE_TRAM, ROADSUBTYPE_ELECTRIC);
1315 assert(rtids.PresentRoadTypes() != ROADTYPES_NONE);
1316 SB(_me[t].m7, 6, 2, 0); // We'll use these two bits to increase road/tram types to 32
1317 SetRoadTypes(t, rtids);
1322 /* Elrails got added in rev 24 */
1323 if (IsSavegameVersionBefore(24)) {
1324 RailType min_rail = RAILTYPE_ELECTRIC;
1326 Train *v;
1327 FOR_ALL_TRAINS(v) {
1328 RailType rt = RailVehInfo(v->engine_type)->railtype;
1330 v->railtype = rt;
1331 if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
1334 /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
1335 for (TileIndex t = 0; t < map_size; t++) {
1336 switch (GetTileType(t)) {
1337 case MP_RAILWAY:
1338 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1339 break;
1341 case MP_ROAD:
1342 if (IsLevelCrossing(t)) {
1343 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1345 break;
1347 case MP_STATION:
1348 if (HasStationRail(t)) {
1349 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1351 break;
1353 case MP_TUNNELBRIDGE:
1354 if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
1355 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1357 break;
1359 default:
1360 break;
1364 FOR_ALL_TRAINS(v) {
1365 if (v->IsFrontEngine() || v->IsFreeWagon()) v->ConsistChanged(CCF_TRACK);
1370 /* In version 16.1 of the savegame a company can decide if trains, which get
1371 * replaced, shall keep their old length. In all prior versions, just default
1372 * to false */
1373 if (IsSavegameVersionBefore(16, 1)) {
1374 Company *c;
1375 FOR_ALL_COMPANIES(c) c->settings.renew_keep_length = false;
1378 if (IsSavegameVersionBefore(123)) {
1379 /* Waypoints became subclasses of stations ... */
1380 MoveWaypointsToBaseStations();
1381 /* ... and buoys were moved to waypoints. */
1382 MoveBuoysToWaypoints();
1385 /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
1386 * room for PBS. Now in version 21 move it back :P. */
1387 if (IsSavegameVersionBefore(21) && !IsSavegameVersionBefore(15)) {
1388 for (TileIndex t = 0; t < map_size; t++) {
1389 switch (GetTileType(t)) {
1390 case MP_RAILWAY:
1391 if (HasSignals(t)) {
1392 /* Original signal type/variant was stored in m4 but since saveload
1393 * version 48 they are in m2. The bits has been already moved to m2
1394 * (see the code somewhere above) so don't use m4, use m2 instead. */
1396 /* convert PBS signals to combo-signals */
1397 if (HasBit(_m[t].m2, 2)) SB(_m[t].m2, 0, 2, SIGTYPE_COMBO);
1399 /* move the signal variant back */
1400 SB(_m[t].m2, 2, 1, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1401 ClrBit(_m[t].m2, 3);
1404 /* Clear PBS reservation on track */
1405 if (!IsRailDepotTile(t)) {
1406 SB(_m[t].m4, 4, 4, 0);
1407 } else {
1408 ClrBit(_m[t].m3, 6);
1410 break;
1412 case MP_STATION: // Clear PBS reservation on station
1413 ClrBit(_m[t].m3, 6);
1414 break;
1416 default: break;
1421 if (IsSavegameVersionBefore(25)) {
1422 RoadVehicle *rv;
1423 FOR_ALL_ROADVEHICLES(rv) {
1424 rv->vehstatus &= ~0x40;
1428 if (IsSavegameVersionBefore(26)) {
1429 Station *st;
1430 FOR_ALL_STATIONS(st) {
1431 st->last_vehicle_type = VEH_INVALID;
1435 YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
1437 if (IsSavegameVersionBefore(34)) {
1438 Company *c;
1439 FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
1442 Company *c;
1443 FOR_ALL_COMPANIES(c) {
1444 c->avail_railtypes = GetCompanyRailtypes(c->index);
1445 c->avail_roadtypes[ROADTYPE_ROAD] = GetCompanyRoadtypes(c->index, ROADTYPE_ROAD);
1446 c->avail_roadtypes[ROADTYPE_TRAM] = GetCompanyRoadtypes(c->index, ROADTYPE_TRAM);
1449 if (!IsSavegameVersionBefore(27)) AfterLoadStations();
1451 /* Time starts at 0 instead of 1920.
1452 * Account for this in older games by adding an offset */
1453 if (IsSavegameVersionBefore(31)) {
1454 Station *st;
1455 Waypoint *wp;
1456 Engine *e;
1457 Industry *i;
1458 Vehicle *v;
1460 _date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1461 _cur_year += ORIGINAL_BASE_YEAR;
1463 FOR_ALL_STATIONS(st) st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1464 FOR_ALL_WAYPOINTS(wp) wp->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1465 FOR_ALL_ENGINES(e) e->intro_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1466 FOR_ALL_COMPANIES(c) c->inaugurated_year += ORIGINAL_BASE_YEAR;
1467 FOR_ALL_INDUSTRIES(i) i->last_prod_year += ORIGINAL_BASE_YEAR;
1469 FOR_ALL_VEHICLES(v) {
1470 v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
1471 v->build_year += ORIGINAL_BASE_YEAR;
1475 /* From 32 on we save the industry who made the farmland.
1476 * To give this prettiness to old savegames, we remove all farmfields and
1477 * plant new ones. */
1478 if (IsSavegameVersionBefore(32)) {
1479 Industry *i;
1481 for (TileIndex t = 0; t < map_size; t++) {
1482 if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
1483 /* remove fields */
1484 MakeClear(t, CLEAR_GRASS, 3);
1488 FOR_ALL_INDUSTRIES(i) {
1489 uint j;
1491 if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
1492 for (j = 0; j != 50; j++) PlantRandomFarmField(i);
1497 /* Setting no refit flags to all orders in savegames from before refit in orders were added */
1498 if (IsSavegameVersionBefore(36)) {
1499 Order *order;
1500 Vehicle *v;
1502 FOR_ALL_ORDERS(order) {
1503 order->SetRefit(CT_NO_REFIT);
1506 FOR_ALL_VEHICLES(v) {
1507 v->current_order.SetRefit(CT_NO_REFIT);
1511 /* from version 38 we have optional elrails, since we cannot know the
1512 * preference of a user, let elrails enabled; it can be disabled manually */
1513 if (IsSavegameVersionBefore(38)) _settings_game.vehicle.disable_elrails = false;
1514 /* do the same as when elrails were enabled/disabled manually just now */
1515 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
1516 InitializeRailGUI();
1518 /* From version 53, the map array was changed for house tiles to allow
1519 * space for newhouses grf features. A new byte, m7, was also added. */
1520 if (IsSavegameVersionBefore(53)) {
1521 for (TileIndex t = 0; t < map_size; t++) {
1522 if (IsTileType(t, MP_HOUSE)) {
1523 if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
1524 /* Move the construction stage from m3[7..6] to m5[5..4].
1525 * The construction counter does not have to move. */
1526 SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
1527 SB(_m[t].m3, 6, 2, 0);
1529 /* The "house is completed" bit is now in m6[2]. */
1530 SetHouseCompleted(t, false);
1531 } else {
1532 /* The "lift has destination" bit has been moved from
1533 * m5[7] to m7[0]. */
1534 SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
1535 ClrBit(_m[t].m5, 7);
1537 /* The "lift is moving" bit has been removed, as it does
1538 * the same job as the "lift has destination" bit. */
1539 ClrBit(_m[t].m1, 7);
1541 /* The position of the lift goes from m1[7..0] to m6[7..2],
1542 * making m1 totally free, now. The lift position does not
1543 * have to be a full byte since the maximum value is 36. */
1544 SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
1546 _m[t].m1 = 0;
1547 _m[t].m3 = 0;
1548 SetHouseCompleted(t, true);
1554 /* Check and update house and town values */
1555 UpdateHousesAndTowns();
1557 if (IsSavegameVersionBefore(43)) {
1558 for (TileIndex t = 0; t < map_size; t++) {
1559 if (IsTileType(t, MP_INDUSTRY)) {
1560 switch (GetIndustryGfx(t)) {
1561 case GFX_POWERPLANT_SPARKS:
1562 _m[t].m3 = GB(_m[t].m1, 2, 5);
1563 break;
1565 case GFX_OILWELL_ANIMATED_1:
1566 case GFX_OILWELL_ANIMATED_2:
1567 case GFX_OILWELL_ANIMATED_3:
1568 _m[t].m3 = GB(_m[t].m1, 0, 2);
1569 break;
1571 case GFX_COAL_MINE_TOWER_ANIMATED:
1572 case GFX_COPPER_MINE_TOWER_ANIMATED:
1573 case GFX_GOLD_MINE_TOWER_ANIMATED:
1574 _m[t].m3 = _m[t].m1;
1575 break;
1577 default: // No animation states to change
1578 break;
1584 if (IsSavegameVersionBefore(45)) {
1585 Vehicle *v;
1586 /* Originally just the fact that some cargo had been paid for was
1587 * stored to stop people cheating and cashing in several times. This
1588 * wasn't enough though as it was cleared when the vehicle started
1589 * loading again, even if it didn't actually load anything, so now the
1590 * amount that has been paid is stored. */
1591 FOR_ALL_VEHICLES(v) {
1592 ClrBit(v->vehicle_flags, 2);
1596 /* Buoys do now store the owner of the previous water tile, which can never
1597 * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
1598 if (IsSavegameVersionBefore(46)) {
1599 Waypoint *wp;
1600 FOR_ALL_WAYPOINTS(wp) {
1601 if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
1605 if (IsSavegameVersionBefore(50)) {
1606 Aircraft *v;
1607 /* Aircraft units changed from 8 mph to 1 km-ish/h */
1608 FOR_ALL_AIRCRAFT(v) {
1609 if (v->subtype <= AIR_AIRCRAFT) {
1610 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
1611 v->cur_speed *= 128;
1612 v->cur_speed /= 10;
1613 v->acceleration = avi->acceleration;
1618 if (IsSavegameVersionBefore(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
1620 if (IsSavegameVersionBefore(52)) {
1621 for (TileIndex t = 0; t < map_size; t++) {
1622 if (IsTileType(t, MP_OBJECT) && _m[t].m5 == OBJECT_STATUE) {
1623 _m[t].m2 = CalcClosestTownFromTile(t)->index;
1628 /* A setting containing the proportion of towns that grow twice as
1629 * fast was added in version 54. From version 56 this is now saved in the
1630 * town as cities can be built specifically in the scenario editor. */
1631 if (IsSavegameVersionBefore(56)) {
1632 Town *t;
1634 FOR_ALL_TOWNS(t) {
1635 if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
1636 t->larger_town = true;
1641 if (IsSavegameVersionBefore(57)) {
1642 Vehicle *v;
1643 /* Added a FIFO queue of vehicles loading at stations */
1644 FOR_ALL_VEHICLES(v) {
1645 if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) && // for all locs
1646 !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
1647 v->current_order.IsType(OT_LOADING)) { // loading
1648 Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
1650 /* The loading finished flag is *only* set when actually completely
1651 * finished. Because the vehicle is loading, it is not finished. */
1652 ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
1655 } else if (IsSavegameVersionBefore(59)) {
1656 /* For some reason non-loading vehicles could be in the station's loading vehicle list */
1658 Station *st;
1659 FOR_ALL_STATIONS(st) {
1660 st->loading_vehicles.erase(std::remove_if(st->loading_vehicles.begin(), st->loading_vehicles.end(),
1661 [](Vehicle *v) {
1662 return !v->current_order.IsType(OT_LOADING);
1663 }), st->loading_vehicles.end());
1667 if (IsSavegameVersionBefore(58)) {
1668 /* Setting difficulty industry_density other than zero get bumped to +1
1669 * since a new option (very low at position 1) has been added */
1670 if (_settings_game.difficulty.industry_density > 0) {
1671 _settings_game.difficulty.industry_density++;
1674 /* Same goes for number of towns, although no test is needed, just an increment */
1675 _settings_game.difficulty.number_towns++;
1678 if (IsSavegameVersionBefore(64)) {
1679 /* Since now we allow different signal types and variants on a single tile.
1680 * Move signal states to m4 to make room and clone the signal type/variant. */
1681 for (TileIndex t = 0; t < map_size; t++) {
1682 if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
1683 /* move signal states */
1684 SetSignalStates(t, GB(_m[t].m2, 4, 4));
1685 SB(_m[t].m2, 4, 4, 0);
1686 /* clone signal type and variant */
1687 SB(_m[t].m2, 4, 3, GB(_m[t].m2, 0, 3));
1692 if (IsSavegameVersionBefore(69)) {
1693 /* In some old savegames a bit was cleared when it should not be cleared */
1694 RoadVehicle *rv;
1695 FOR_ALL_ROADVEHICLES(rv) {
1696 if (rv->state == 250 || rv->state == 251) {
1697 SetBit(rv->state, 2);
1702 if (IsSavegameVersionBefore(70)) {
1703 /* Added variables to support newindustries */
1704 Industry *i;
1705 FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
1708 /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
1709 Replace the owner for those by OWNER_NONE. */
1710 if (IsSavegameVersionBefore(82)) {
1711 for (TileIndex t = 0; t < map_size; t++) {
1712 if (IsTileType(t, MP_WATER) &&
1713 GetWaterTileType(t) == WATER_TILE_CLEAR &&
1714 GetTileOwner(t) == OWNER_WATER &&
1715 TileHeight(t) != 0) {
1716 SetTileOwner(t, OWNER_NONE);
1722 * Add the 'previous' owner to the ship depots so we can reset it with
1723 * the correct values when it gets destroyed. This prevents that
1724 * someone can remove canals owned by somebody else and it prevents
1725 * making floods using the removal of ship depots.
1727 if (IsSavegameVersionBefore(83)) {
1728 for (TileIndex t = 0; t < map_size; t++) {
1729 if (IsShipDepotTile(t)) {
1730 _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
1735 if (IsSavegameVersionBefore(74)) {
1736 Station *st;
1737 FOR_ALL_STATIONS(st) {
1738 for (CargoID c = 0; c < NUM_CARGO; c++) {
1739 st->goods[c].last_speed = 0;
1740 if (st->goods[c].cargo.AvailableCount() != 0) SetBit(st->goods[c].status, GoodsEntry::GES_RATING);
1745 if (IsSavegameVersionBefore(78)) {
1746 Industry *i;
1747 uint j;
1748 FOR_ALL_INDUSTRIES(i) {
1749 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1750 for (j = 0; j < lengthof(i->produced_cargo); j++) {
1751 i->produced_cargo[j] = indsp->produced_cargo[j];
1753 for (j = 0; j < lengthof(i->accepts_cargo); j++) {
1754 i->accepts_cargo[j] = indsp->accepts_cargo[j];
1759 /* Before version 81, the density of grass was always stored as zero, and
1760 * grassy trees were always drawn fully grassy. Furthermore, trees on rough
1761 * land used to have zero density, now they have full density. Therefore,
1762 * make all grassy/rough land trees have a density of 3. */
1763 if (IsSavegameVersionBefore(81)) {
1764 for (TileIndex t = 0; t < map_size; t++) {
1765 if (GetTileType(t) == MP_TREES) {
1766 TreeGround groundType = (TreeGround)GB(_m[t].m2, 4, 2);
1767 if (groundType != TREE_GROUND_SNOW_DESERT) SB(_m[t].m2, 6, 2, 3);
1773 if (IsSavegameVersionBefore(93)) {
1774 /* Rework of orders. */
1775 Order *order;
1776 FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
1778 Vehicle *v;
1779 FOR_ALL_VEHICLES(v) {
1780 if (v->HasOrdersList() && v->GetFirstOrder() != nullptr && v->GetFirstOrder()->IsType(OT_NOTHING)) {
1781 v->FreeOrderChain();
1784 v->current_order.ConvertFromOldSavegame();
1785 if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
1786 FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
1789 } else if (IsSavegameVersionBefore(94)) {
1790 /* Unload and transfer are now mutual exclusive. */
1791 Order *order;
1792 FOR_ALL_ORDERS(order) {
1793 if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1794 order->SetUnloadType(OUFB_TRANSFER);
1795 order->SetLoadType(OLFB_NO_LOAD);
1799 Vehicle *v;
1800 FOR_ALL_VEHICLES(v) {
1801 if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1802 v->current_order.SetUnloadType(OUFB_TRANSFER);
1803 v->current_order.SetLoadType(OLFB_NO_LOAD);
1806 } else if (IsSavegameVersionBefore(SL_PATCH_PACK_1_24)) {
1807 Order* order;
1808 FOR_ALL_ORDERS(order) {
1809 if (order->IsType(OT_CONDITIONAL) && order->GetConditionVariable() == OCV_SLOT_OCCUPANCY) {
1810 order->GetXDataRef() = order->GetConditionValue();
1815 if (IsSavegameVersionBefore(84)) {
1816 /* Set all share owners to INVALID_COMPANY for
1817 * 1) all inactive companies
1818 * (when inactive companies were stored in the savegame - TTD, TTDP and some
1819 * *really* old revisions of OTTD; else it is already set in InitializeCompanies())
1820 * 2) shares that are owned by inactive companies or self
1821 * (caused by cheating clients in earlier revisions) */
1822 FOR_ALL_COMPANIES(c) {
1823 for (uint i = 0; i < 4; i++) {
1824 CompanyID company = c->share_owners[i];
1825 if (company == INVALID_COMPANY) continue;
1826 if (!Company::IsValidID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
1831 /* The water class was moved/unified. */
1832 if (IsSavegameVersionBefore(146)) {
1833 for (TileIndex t = 0; t < map_size; t++) {
1834 switch (GetTileType(t)) {
1835 case MP_STATION:
1836 switch (GetStationType(t)) {
1837 case STATION_OILRIG:
1838 case STATION_DOCK:
1839 case STATION_BUOY:
1840 SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
1841 SB(_m[t].m3, 0, 2, 0);
1842 break;
1844 default:
1845 SetWaterClass(t, WATER_CLASS_INVALID);
1846 break;
1848 break;
1850 case MP_WATER:
1851 SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
1852 SB(_m[t].m3, 0, 2, 0);
1853 break;
1855 case MP_OBJECT:
1856 SetWaterClass(t, WATER_CLASS_INVALID);
1857 break;
1859 default:
1860 /* No water class. */
1861 break;
1866 if (IsSavegameVersionBefore(86)) {
1867 for (TileIndex t = 0; t < map_size; t++) {
1868 /* Move river flag and update canals to use water class */
1869 if (IsTileType(t, MP_WATER)) {
1870 if (GetWaterClass(t) != WATER_CLASS_RIVER) {
1871 if (IsWater(t)) {
1872 Owner o = GetTileOwner(t);
1873 if (o == OWNER_WATER) {
1874 MakeSea(t);
1875 } else {
1876 MakeCanal(t, o, Random());
1878 } else if (IsShipDepot(t)) {
1879 Owner o = (Owner)_m[t].m4; // Original water owner
1880 SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
1886 /* Update locks, depots, docks and buoys to have a water class based
1887 * on its neighbouring tiles. Done after river and canal updates to
1888 * ensure neighbours are correct. */
1889 for (TileIndex t = 0; t < map_size; t++) {
1890 if (!IsTileFlat(t)) continue;
1892 if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
1893 if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
1897 if (IsSavegameVersionBefore(87)) {
1898 for (TileIndex t = 0; t < map_size; t++) {
1899 /* skip oil rigs at borders! */
1900 if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
1901 (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
1902 /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
1903 * This conversion has to be done before buoys with invalid owner are removed. */
1904 SetWaterClass(t, WATER_CLASS_SEA);
1907 if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
1908 Owner o = GetTileOwner(t);
1909 if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
1910 Backup<CompanyByte> cur_company(_current_company, o, FILE_LINE);
1911 ChangeTileOwner(t, o, INVALID_OWNER);
1912 cur_company.Restore();
1914 if (IsBuoyTile(t)) {
1915 /* reset buoy owner to OWNER_NONE in the station struct
1916 * (even if it is owned by active company) */
1917 Waypoint::GetByTile(t)->owner = OWNER_NONE;
1919 } else if (IsTileType(t, MP_ROAD)) {
1920 /* works for all RoadTileType */
1921 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
1922 /* update even non-existing road types to update tile owner too */
1923 Owner o = GetRoadOwner(t, rt);
1924 if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rt, OWNER_NONE);
1926 if (IsLevelCrossing(t)) {
1927 if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
1929 } else if (IsPlainRailTile(t)) {
1930 if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
1934 /* Convert old PF settings to new */
1935 if (_settings_game.pf.yapf.rail_use_yapf || IsSavegameVersionBefore(28)) {
1936 _settings_game.pf.pathfinder_for_trains = VPF_YAPF;
1937 } else {
1938 _settings_game.pf.pathfinder_for_trains = VPF_NPF;
1941 if (_settings_game.pf.yapf.road_use_yapf || IsSavegameVersionBefore(28)) {
1942 _settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
1943 } else {
1944 _settings_game.pf.pathfinder_for_roadvehs = VPF_NPF;
1947 if (_settings_game.pf.yapf.ship_use_yapf) {
1948 _settings_game.pf.pathfinder_for_ships = VPF_YAPF;
1949 } else {
1950 _settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
1954 if (IsSavegameVersionBefore(88)) {
1955 /* Profits are now with 8 bit fract */
1956 Vehicle *v;
1957 FOR_ALL_VEHICLES(v) {
1958 v->profit_this_year <<= 8;
1959 v->profit_last_year <<= 8;
1960 v->running_ticks = 0;
1964 if (IsSavegameVersionBefore(91)) {
1965 /* Increase HouseAnimationFrame from 5 to 7 bits */
1966 for (TileIndex t = 0; t < map_size; t++) {
1967 if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
1968 SB(_me[t].m6, 2, 6, GB(_me[t].m6, 3, 5));
1969 SB(_m[t].m3, 5, 1, 0);
1974 if (IsSavegameVersionBefore(62)) {
1975 /* Remove all trams from savegames without tram support.
1976 * There would be trams without tram track under causing crashes sooner or later. */
1977 RoadVehicle *v;
1978 FOR_ALL_ROADVEHICLES(v) {
1979 if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
1980 ShowErrorMessage(STR_WARNING_LOADGAME_REMOVED_TRAMS, INVALID_STRING_ID, WL_CRITICAL);
1981 delete v;
1986 if (IsSavegameVersionBefore(99)) {
1987 for (TileIndex t = 0; t < map_size; t++) {
1988 /* Set newly introduced WaterClass of industry tiles */
1989 if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
1990 SetWaterClassDependingOnSurroundings(t, true);
1992 if (IsTileType(t, MP_INDUSTRY)) {
1993 if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
1994 SetWaterClassDependingOnSurroundings(t, true);
1995 } else {
1996 SetWaterClass(t, WATER_CLASS_INVALID);
2000 /* Replace "house construction year" with "house age" */
2001 if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
2002 _m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
2007 /* Tunnel pool has to be initiated before reservations. */
2008 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_19)) {
2009 for (TileIndex t = 0; t < map_size; t++) {
2010 if (IsTunnelTile(t)) {
2011 DiagDirection dir = GetTunnelBridgeDirection(t);
2012 if (dir == DIAGDIR_SE || dir == DIAGDIR_SW) {
2013 TileIndex start_tile = t;
2014 TileIndex end_tile = GetOtherTunnelBridgeEndOld(start_tile);
2016 if (!Tunnel::CanAllocateItem()) {
2017 SetSaveLoadError(STR_ERROR_TUNNEL_TOO_MANY);
2018 /* Restore the signals */
2019 ResetSignalHandlers();
2020 return false;
2023 const Tunnel *t = new Tunnel(start_tile, end_tile, TileHeight(start_tile), false);
2025 SetTunnelIndex(start_tile, t->index);
2026 SetTunnelIndex(end_tile, t->index);
2032 /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
2033 * format here, as an old layout wouldn't work properly anyway. To be safe, we
2034 * clear any possible PBS reservations as well. */
2035 if (IsSavegameVersionBefore(100)) {
2036 for (TileIndex t = 0; t < map_size; t++) {
2037 switch (GetTileType(t)) {
2038 case MP_RAILWAY:
2039 if (HasSignals(t)) {
2040 /* move the signal variant */
2041 SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
2042 SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
2043 ClrBit(_m[t].m2, 2);
2044 ClrBit(_m[t].m2, 6);
2047 /* Clear PBS reservation on track */
2048 if (IsRailDepot(t)) {
2049 SetDepotReservation(t, false);
2050 } else {
2051 SetTrackReservation(t, TRACK_BIT_NONE);
2053 break;
2055 case MP_ROAD: // Clear PBS reservation on crossing
2056 if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
2057 break;
2059 case MP_STATION: // Clear PBS reservation on station
2060 if (HasStationRail(t)) SetRailStationReservation(t, false);
2061 break;
2063 case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/bridges
2064 if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
2065 break;
2067 default: break;
2072 /* Reserve all tracks trains are currently on. */
2073 if (IsSavegameVersionBefore(101)) {
2074 const Train *t;
2075 FOR_ALL_TRAINS(t) {
2076 if (t->First() == t) t->ReserveTrackUnderConsist();
2080 if (IsSavegameVersionBefore(102)) {
2081 for (TileIndex t = 0; t < map_size; t++) {
2082 /* Now all crossings should be in correct state */
2083 if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
2087 if (IsSavegameVersionBefore(103)) {
2088 /* Non-town-owned roads now store the closest town */
2089 UpdateNearestTownForRoadTiles(false);
2091 /* signs with invalid owner left from older savegames */
2092 Sign *si;
2093 FOR_ALL_SIGNS(si) {
2094 if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
2097 /* Station can get named based on an industry type, but the current ones
2098 * are not, so mark them as if they are not named by an industry. */
2099 Station *st;
2100 FOR_ALL_STATIONS(st) {
2101 st->indtype = IT_INVALID;
2105 if (IsSavegameVersionBefore(104)) {
2106 Aircraft *a;
2107 FOR_ALL_AIRCRAFT(a) {
2108 /* Set engine_type of shadow and rotor */
2109 if (!a->IsNormalAircraft()) {
2110 a->engine_type = a->First()->engine_type;
2114 /* More companies ... */
2115 Company *c;
2116 FOR_ALL_COMPANIES(c) {
2117 if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
2120 Engine *e;
2121 FOR_ALL_ENGINES(e) {
2122 if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
2125 Town *t;
2126 FOR_ALL_TOWNS(t) {
2127 if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
2128 for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
2132 if (IsSavegameVersionBefore(112)) {
2133 for (TileIndex t = 0; t < map_size; t++) {
2134 /* Check for HQ bit being set, instead of using map accessor,
2135 * since we've already changed it code-wise */
2136 if (IsTileType(t, MP_OBJECT) && HasBit(_m[t].m5, 7)) {
2137 /* Move size and part identification of HQ out of the m5 attribute,
2138 * on new locations */
2139 _m[t].m3 = GB(_m[t].m5, 0, 5);
2140 _m[t].m5 = OBJECT_HQ;
2144 if (IsSavegameVersionBefore(144)) {
2145 for (TileIndex t = 0; t < map_size; t++) {
2146 if (!IsTileType(t, MP_OBJECT)) continue;
2148 /* Reordering/generalisation of the object bits. */
2149 ObjectType type = _m[t].m5;
2150 SB(_me[t].m6, 2, 4, type == OBJECT_HQ ? GB(_m[t].m3, 2, 3) : 0);
2151 _m[t].m3 = type == OBJECT_HQ ? GB(_m[t].m3, 1, 1) | GB(_m[t].m3, 0, 1) << 4 : 0;
2153 /* Make sure those bits are clear as well! */
2154 _m[t].m4 = 0;
2155 _me[t].m7 = 0;
2159 if (IsSavegameVersionBefore(147) && Object::GetNumItems() == 0) {
2160 /* Make real objects for object tiles. */
2161 for (TileIndex t = 0; t < map_size; t++) {
2162 if (!IsTileType(t, MP_OBJECT)) continue;
2164 if (Town::GetNumItems() == 0) {
2165 /* No towns, so remove all objects! */
2166 DoClearSquare(t);
2167 } else {
2168 uint offset = _m[t].m3;
2170 /* Also move the animation state. */
2171 _m[t].m3 = GB(_me[t].m6, 2, 4);
2172 SB(_me[t].m6, 2, 4, 0);
2174 if (offset == 0) {
2175 /* No offset, so make the object. */
2176 ObjectType type = _m[t].m5;
2177 int size = type == OBJECT_HQ ? 2 : 1;
2179 if (!Object::CanAllocateItem()) {
2180 /* Nice... you managed to place 64k lighthouses and
2181 * antennae on the map... boohoo. */
2182 SlError(STR_ERROR_TOO_MANY_OBJECTS);
2185 Object *o = new Object();
2186 o->location.tile = t;
2187 o->location.w = size;
2188 o->location.h = size;
2189 o->build_date = _date;
2190 o->town = type == OBJECT_STATUE ? Town::Get(_m[t].m2) : CalcClosestTownFromTile(t, UINT_MAX);
2191 _m[t].m2 = o->index;
2192 Object::IncTypeCount(type);
2193 } else {
2194 /* We're at an offset, so get the ID from our "root". */
2195 TileIndex northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
2196 assert(IsTileType(northern_tile, MP_OBJECT));
2197 _m[t].m2 = _m[northern_tile].m2;
2203 if (IsSavegameVersionBefore(113)) {
2204 /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
2205 if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
2206 _settings_game.economy.allow_town_roads = false;
2207 _settings_game.economy.town_layout = TL_BETTER_ROADS;
2208 } else {
2209 _settings_game.economy.allow_town_roads = true;
2210 _settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
2213 /* Initialize layout of all towns. Older versions were using different
2214 * generator for random town layout, use it if needed. */
2215 Town *t;
2216 FOR_ALL_TOWNS(t) {
2217 if (_settings_game.economy.town_layout != TL_RANDOM) {
2218 t->layout = _settings_game.economy.town_layout;
2219 continue;
2222 /* Use old layout randomizer code */
2223 byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
2224 switch (layout) {
2225 default: break;
2226 case 5: layout = 1; break;
2227 case 0: layout = 2; break;
2229 t->layout = layout - 1;
2233 if (IsSavegameVersionBefore(114)) {
2234 /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
2235 * The conversion affects oil rigs and buoys too, but it doesn't matter as
2236 * they have st->owner == OWNER_NONE already. */
2237 Station *st;
2238 FOR_ALL_STATIONS(st) {
2239 if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
2243 /* Trains could now stop in a specific location. */
2244 if (IsSavegameVersionBefore(117)) {
2245 Order *o;
2246 FOR_ALL_ORDERS(o) {
2247 if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
2251 if (IsSavegameVersionBefore(120)) {
2252 extern VehicleDefaultSettings _old_vds;
2253 Company *c;
2254 FOR_ALL_COMPANIES(c) {
2255 c->settings.vehicle = _old_vds;
2259 if (IsSavegameVersionBefore(121)) {
2260 /* Delete small ufos heading for non-existing vehicles */
2261 Vehicle *v;
2262 FOR_ALL_DISASTERVEHICLES(v) {
2263 if (v->subtype == 2 /* ST_SMALL_UFO */ && v->current_order.GetDestination() != 0) {
2264 const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
2265 if (u == nullptr || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
2266 delete v;
2271 /* We didn't store cargo payment yet, so make them for vehicles that are
2272 * currently at a station and loading/unloading. If they don't get any
2273 * payment anymore they just removed in the next load/unload cycle.
2274 * However, some 0.7 versions might have cargo payment. For those we just
2275 * add cargopayment for the vehicles that don't have it.
2277 Station *st;
2278 FOR_ALL_STATIONS(st) {
2279 for (Vehicle *v : st->loading_vehicles) {
2280 /* There are always as many CargoPayments as Vehicles. We need to make the
2281 * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
2282 assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
2283 assert(CargoPayment::CanAllocateItem());
2284 if (v->cargo_payment == nullptr) v->cargo_payment = new CargoPayment(v);
2289 if (IsSavegameVersionBefore(122)) {
2290 /* Animated tiles would sometimes not be actually animated or
2291 * in case of old savegames duplicate. */
2293 extern TileIndex *_animated_tile_list;
2294 extern uint _animated_tile_count;
2296 for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
2297 /* Remove if tile is not animated */
2298 bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == nullptr;
2300 /* and remove if duplicate */
2301 for (uint j = 0; !remove && j < i; j++) {
2302 remove = _animated_tile_list[i] == _animated_tile_list[j];
2305 if (remove) {
2306 DeleteAnimatedTile(_animated_tile_list[i]);
2307 } else {
2308 i++;
2313 if (IsSavegameVersionBefore(124) && !IsSavegameVersionBefore(1)) {
2314 /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
2315 Waypoint *wp;
2316 FOR_ALL_WAYPOINTS(wp) {
2317 if (wp->facilities & FACIL_TRAIN) {
2318 wp->train_station.tile = wp->xy;
2319 wp->train_station.w = 1;
2320 wp->train_station.h = 1;
2321 } else {
2322 wp->train_station.tile = INVALID_TILE;
2323 wp->train_station.w = 0;
2324 wp->train_station.h = 0;
2329 if (IsSavegameVersionBefore(125)) {
2330 /* Convert old subsidies */
2331 Subsidy *s;
2332 FOR_ALL_SUBSIDIES(s) {
2333 if (s->remaining < 12) {
2334 /* Converting nonawarded subsidy */
2335 s->remaining = 12 - s->remaining; // convert "age" to "remaining"
2336 s->awarded = INVALID_COMPANY; // not awarded to anyone
2337 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2338 switch (cs->town_effect) {
2339 case TE_PASSENGERS:
2340 case TE_MAIL:
2341 /* Town -> Town */
2342 s->src_type = s->dst_type = ST_TOWN;
2343 if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2344 break;
2345 case TE_GOODS:
2346 case TE_FOOD:
2347 /* Industry -> Town */
2348 s->src_type = ST_INDUSTRY;
2349 s->dst_type = ST_TOWN;
2350 if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2351 break;
2352 default:
2353 /* Industry -> Industry */
2354 s->src_type = s->dst_type = ST_INDUSTRY;
2355 if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
2356 break;
2358 } else {
2359 /* Do our best for awarded subsidies. The original source or destination industry
2360 * can't be determined anymore for awarded subsidies, so invalidate them.
2361 * Town -> Town subsidies are converted using simple heuristic */
2362 s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
2363 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2364 switch (cs->town_effect) {
2365 case TE_PASSENGERS:
2366 case TE_MAIL: {
2367 /* Town -> Town */
2368 const Station *ss = Station::GetIfValid(s->src);
2369 const Station *sd = Station::GetIfValid(s->dst);
2370 if (ss != nullptr && sd != nullptr && ss->owner == sd->owner &&
2371 Company::IsValidID(ss->owner)) {
2372 s->src_type = s->dst_type = ST_TOWN;
2373 s->src = ss->town->index;
2374 s->dst = sd->town->index;
2375 s->awarded = ss->owner;
2376 continue;
2378 break;
2380 default:
2381 break;
2384 /* Awarded non-town subsidy or invalid source/destination, invalidate */
2385 delete s;
2389 if (IsSavegameVersionBefore(126)) {
2390 /* Recompute inflation based on old unround loan limit
2391 * Note: Max loan is 500000. With an inflation of 4% across 170 years
2392 * that results in a max loan of about 0.7 * 2^31.
2393 * So taking the 16 bit fractional part into account there are plenty of bits left
2394 * for unmodified savegames ...
2396 uint64 aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
2398 /* ... well, just clamp it then. */
2399 if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
2401 /* Simulate the inflation, so we also get the payment inflation */
2402 while (_economy.inflation_prices < aimed_inflation) {
2403 if (AddInflation(false)) break;
2407 if (IsSavegameVersionBefore(128)) {
2408 const Depot *d;
2409 FOR_ALL_DEPOTS(d) {
2410 _m[d->xy].m2 = d->index;
2411 if (IsTileType(d->xy, MP_WATER)) _m[GetOtherShipDepotTile(d->xy)].m2 = d->index;
2415 /* The behaviour of force_proceed has been changed. Now
2416 * it counts signals instead of some random time out. */
2417 if (IsSavegameVersionBefore(131)) {
2418 Train *t;
2419 FOR_ALL_TRAINS(t) {
2420 if (t->force_proceed != TFP_NONE) {
2421 t->force_proceed = TFP_STUCK;
2426 /* The bits for the tree ground and tree density have
2427 * been swapped (m2 bits 7..6 and 5..4. */
2428 if (IsSavegameVersionBefore(135)) {
2429 for (TileIndex t = 0; t < map_size; t++) {
2430 if (IsTileType(t, MP_CLEAR)) {
2431 if (GetRawClearGround(t) == CLEAR_SNOW) {
2432 SetClearGroundDensity(t, CLEAR_GRASS, GetClearDensity(t));
2433 SetBit(_m[t].m3, 4);
2434 } else {
2435 ClrBit(_m[t].m3, 4);
2438 if (IsTileType(t, MP_TREES)) {
2439 uint density = GB(_m[t].m2, 6, 2);
2440 uint ground = GB(_m[t].m2, 4, 2);
2441 uint counter = GB(_m[t].m2, 0, 4);
2442 _m[t].m2 = ground << 6 | density << 4 | counter;
2447 /* Wait counter and load/unload ticks got split. */
2448 if (IsSavegameVersionBefore(136)) {
2449 Aircraft *a;
2450 FOR_ALL_AIRCRAFT(a) {
2451 a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
2454 Train *t;
2455 FOR_ALL_TRAINS(t) {
2456 t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
2460 /* Airport tile animation uses animation frame instead of other graphics id */
2461 if (IsSavegameVersionBefore(137)) {
2462 struct AirportTileConversion {
2463 byte old_start;
2464 byte num_frames;
2466 static const AirportTileConversion atc[] = {
2467 {31, 12}, // APT_RADAR_GRASS_FENCE_SW
2468 {50, 4}, // APT_GRASS_FENCE_NE_FLAG
2469 {62, 2}, // 1 unused tile
2470 {66, 12}, // APT_RADAR_FENCE_SW
2471 {78, 12}, // APT_RADAR_FENCE_NE
2472 {101, 10}, // 9 unused tiles
2473 {111, 8}, // 7 unused tiles
2474 {119, 15}, // 14 unused tiles (radar)
2475 {140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
2477 for (TileIndex t = 0; t < map_size; t++) {
2478 if (IsAirportTile(t)) {
2479 StationGfx old_gfx = GetStationGfx(t);
2480 byte offset = 0;
2481 for (uint i = 0; i < lengthof(atc); i++) {
2482 if (old_gfx < atc[i].old_start) {
2483 SetStationGfx(t, old_gfx - offset);
2484 break;
2486 if (old_gfx < atc[i].old_start + atc[i].num_frames) {
2487 SetAnimationFrame(t, old_gfx - atc[i].old_start);
2488 SetStationGfx(t, atc[i].old_start - offset);
2489 break;
2491 offset += atc[i].num_frames - 1;
2497 if (IsSavegameVersionBefore(140)) {
2498 Station *st;
2499 FOR_ALL_STATIONS(st) {
2500 if (st->airport.tile != INVALID_TILE) {
2501 st->airport.w = st->airport.GetSpec()->size_x;
2502 st->airport.h = st->airport.GetSpec()->size_y;
2507 if (IsSavegameVersionBefore(141)) {
2508 for (TileIndex t = 0; t < map_size; t++) {
2509 /* Reset tropic zone for VOID tiles, they shall not have any. */
2510 if (IsTileType(t, MP_VOID)) SetTropicZone(t, TROPICZONE_NORMAL);
2513 /* We need to properly number/name the depots.
2514 * The first step is making sure none of the depots uses the
2515 * 'default' names, after that we can assign the names. */
2516 Depot *d;
2517 FOR_ALL_DEPOTS(d) d->town_cn = UINT16_MAX;
2519 FOR_ALL_DEPOTS(d) MakeDefaultName(d);
2522 if (IsSavegameVersionBefore(142)) {
2523 Depot *d;
2524 FOR_ALL_DEPOTS(d) d->build_date = _date;
2527 /* In old versions it was possible to remove an airport while a plane was
2528 * taking off or landing. This gives all kind of problems when building
2529 * another airport in the same station so we don't allow that anymore.
2530 * For old savegames with such aircraft we just throw them in the air and
2531 * treat the aircraft like they were flying already. */
2532 if (IsSavegameVersionBefore(146)) {
2533 Aircraft *v;
2534 FOR_ALL_AIRCRAFT(v) {
2535 if (!v->IsNormalAircraft()) continue;
2536 Station *st = GetTargetAirportIfValid(v);
2537 if (st == nullptr && v->state != FLYING) {
2538 v->state = FLYING;
2539 UpdateAircraftCache(v);
2540 AircraftNextAirportPos_and_Order(v);
2541 /* get aircraft back on running altitude */
2542 if ((v->vehstatus & VS_CRASHED) == 0) {
2543 GetAircraftFlightLevelBounds(v, &v->z_pos, nullptr);
2544 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
2550 /* Move the animation frame to the same location (m7) for all objects. */
2551 if (IsSavegameVersionBefore(147)) {
2552 for (TileIndex t = 0; t < map_size; t++) {
2553 switch (GetTileType(t)) {
2554 case MP_HOUSE:
2555 if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
2556 uint per_proc = _me[t].m7;
2557 _me[t].m7 = GB(_me[t].m6, 2, 6) | (GB(_m[t].m3, 5, 1) << 6);
2558 SB(_m[t].m3, 5, 1, 0);
2559 SB(_me[t].m6, 2, 6, min(per_proc, 63));
2561 break;
2563 case MP_INDUSTRY: {
2564 uint rand = _me[t].m7;
2565 _me[t].m7 = _m[t].m3;
2566 _m[t].m3 = rand;
2567 break;
2570 case MP_OBJECT:
2571 _me[t].m7 = _m[t].m3;
2572 _m[t].m3 = 0;
2573 break;
2575 default:
2576 /* For stations/airports it's already at m7 */
2577 break;
2582 /* Add (random) colour to all objects. */
2583 if (IsSavegameVersionBefore(148)) {
2584 Object *o;
2585 FOR_ALL_OBJECTS(o) {
2586 Owner owner = GetTileOwner(o->location.tile);
2587 o->colour = (owner == OWNER_NONE) ? Random() & 0xF : Company::Get(owner)->livery->colour1;
2591 if (IsSavegameVersionBefore(149)) {
2592 for (TileIndex t = 0; t < map_size; t++) {
2593 if (!IsTileType(t, MP_STATION)) continue;
2594 if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && IsTileFlat(t))) {
2595 SetWaterClass(t, WATER_CLASS_INVALID);
2599 /* Waypoints with custom name may have a non-unique town_cn,
2600 * renumber those. First set all affected waypoints to the
2601 * highest possible number to get them numbered in the
2602 * order they have in the pool. */
2603 Waypoint *wp;
2604 FOR_ALL_WAYPOINTS(wp) {
2605 if (wp->name != nullptr) wp->town_cn = UINT16_MAX;
2608 FOR_ALL_WAYPOINTS(wp) {
2609 if (wp->name != nullptr) MakeDefaultName(wp);
2613 if (IsSavegameVersionBefore(152)) {
2614 _industry_builder.Reset(); // Initialize industry build data.
2616 /* The moment vehicles go from hidden to visible changed. This means
2617 * that vehicles don't always get visible anymore causing things to
2618 * get messed up just after loading the savegame. This fixes that. */
2619 Vehicle *v;
2620 FOR_ALL_VEHICLES(v) {
2621 /* Not all vehicle types can be inside a tunnel. Furthermore,
2622 * testing IsTunnelTile() for invalid tiles causes a crash. */
2623 if (!v->IsGroundVehicle()) continue;
2625 /* Is the vehicle in a tunnel? */
2626 if (!IsTunnelTile(v->tile)) continue;
2628 /* Is the vehicle actually at a tunnel entrance/exit? */
2629 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
2630 if (!IsTunnelTile(vtile)) continue;
2632 /* Are we actually in this tunnel? Or maybe a lower tunnel? */
2633 if (GetSlopePixelZ(v->x_pos, v->y_pos) != v->z_pos) continue;
2635 /* What way are we going? */
2636 const DiagDirection dir = GetTunnelBridgeDirection(vtile);
2637 const DiagDirection vdir = DirToDiagDir(v->direction);
2639 /* Have we passed the visibility "switch" state already? */
2640 byte pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
2641 byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2642 extern const byte _tunnel_visibility_frame[DIAGDIR_END];
2644 /* Should the vehicle be hidden or not? */
2645 bool hidden;
2646 if (dir == vdir) { // Entering tunnel
2647 hidden = frame >= _tunnel_visibility_frame[dir];
2648 v->tile = vtile;
2649 } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
2650 hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
2651 /* v->tile changes at the moment when the vehicle leaves the tunnel. */
2652 v->tile = hidden ? GetOtherTunnelBridgeEndOld(vtile) : vtile;
2653 } else {
2654 /* We could get here in two cases:
2655 * - for road vehicles, it is reversing at the end of the tunnel
2656 * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
2657 * Whatever case it is, do not change anything and use the old values.
2658 * Especially changing RV's state would break its reversing in the middle. */
2659 continue;
2662 if (hidden) {
2663 v->vehstatus |= VS_HIDDEN;
2665 switch (v->type) {
2666 case VEH_TRAIN: Train::From(v)->track = TRACK_BIT_WORMHOLE; break;
2667 case VEH_ROAD: RoadVehicle::From(v)->state = RVSB_WORMHOLE; break;
2668 default: NOT_REACHED();
2670 } else {
2671 v->vehstatus &= ~VS_HIDDEN;
2673 switch (v->type) {
2674 case VEH_TRAIN: Train::From(v)->track = DiagDirToDiagTrackBits(vdir); break;
2675 case VEH_ROAD: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
2676 default: NOT_REACHED();
2682 if (IsSavegameVersionBefore(153)) {
2683 RoadVehicle *rv;
2684 FOR_ALL_ROADVEHICLES(rv) {
2685 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
2687 bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
2688 if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
2689 extern const byte _road_stop_stop_frame[];
2690 SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > _road_stop_stop_frame[rv->state - RVSB_IN_ROAD_STOP + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)]);
2691 } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
2692 SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
2697 if (IsSavegameVersionBefore(156)) {
2698 /* The train's pathfinder lost flag got moved. */
2699 Train *t;
2700 FOR_ALL_TRAINS(t) {
2701 if (!HasBit(t->flags, 5)) continue;
2703 ClrBit(t->flags, 5);
2704 SetBit(t->vehicle_flags, VF_PATHFINDER_LOST);
2707 /* Introduced terraform/clear limits. */
2708 Company *c;
2709 FOR_ALL_COMPANIES(c) {
2710 c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
2711 c->clear_limit = _settings_game.construction.clear_frame_burst << 16;
2715 if (IsSavegameVersionBefore(158)) {
2716 Vehicle *v;
2717 FOR_ALL_VEHICLES(v) {
2718 switch (v->type) {
2719 case VEH_TRAIN: {
2720 Train *t = Train::From(v);
2722 /* Clear old GOINGUP / GOINGDOWN flags.
2723 * It was changed in savegame version 139, but savegame
2724 * version 158 doesn't use these bits, so it doesn't hurt
2725 * to clear them unconditionally. */
2726 ClrBit(t->flags, 1);
2727 ClrBit(t->flags, 2);
2729 /* Clear both bits first. */
2730 ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
2731 ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
2733 /* Crashed vehicles can't be going up/down. */
2734 if (t->vehstatus & VS_CRASHED) break;
2736 /* Only X/Y tracks can be sloped. */
2737 if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
2739 t->gv_flags |= FixVehicleInclination(t, t->direction);
2740 break;
2742 case VEH_ROAD: {
2743 RoadVehicle *rv = RoadVehicle::From(v);
2744 ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
2745 ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
2747 /* Crashed vehicles can't be going up/down. */
2748 if (rv->vehstatus & VS_CRASHED) break;
2750 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
2752 TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, rv->rtid.basetype);
2753 TrackBits trackbits = TrackStatusToTrackBits(ts);
2755 /* Only X/Y tracks can be sloped. */
2756 if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
2758 Direction dir = rv->direction;
2760 /* Test if we are reversing. */
2761 Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
2762 if (AxisToDirection(a) != dir &&
2763 AxisToDirection(a) != ReverseDir(dir)) {
2764 /* When reversing, the road vehicle is on the edge of the tile,
2765 * so it can be safely compared to the middle of the tile. */
2766 dir = INVALID_DIR;
2769 rv->gv_flags |= FixVehicleInclination(rv, dir);
2770 break;
2772 case VEH_SHIP:
2773 break;
2775 default:
2776 continue;
2779 if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2780 /* In old versions, z_pos was 1 unit lower on bridge heads.
2781 * However, this invalid state could be converted to new savegames
2782 * by loading and saving the game in a new version. */
2783 v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos);
2784 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
2785 if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
2786 v->direction != DiagDirToDir(dir)) {
2787 /* If the train has left the bridge, it shouldn't have
2788 * track == TRACK_BIT_WORMHOLE - this could happen
2789 * when the train was reversed while on the last "tick"
2790 * on the ramp before leaving the ramp to the bridge. */
2791 Train::From(v)->track = DiagDirToDiagTrackBits(dir);
2795 /* If the vehicle is really above v->tile (not in a wormhole),
2796 * it should have set v->z_pos correctly. */
2797 assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos));
2800 /* Fill Vehicle::cur_real_order_index */
2801 FOR_ALL_VEHICLES(v) {
2802 if (!v->IsPrimaryVehicle()) continue;
2804 /* Older versions are less strict with indices being in range and fix them on the fly */
2805 if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
2807 v->cur_real_order_index = v->cur_implicit_order_index;
2808 v->UpdateRealOrderIndex();
2812 if (IsSavegameVersionBefore(159)) {
2813 /* If the savegame is old (before version 100), then the value of 255
2814 * for these settings did not mean "disabled". As such everything
2815 * before then did reverse.
2816 * To simplify stuff we disable all turning around or we do not
2817 * disable anything at all. So, if some reversing was disabled we
2818 * will keep reversing disabled, otherwise it'll be turned on. */
2819 _settings_game.pf.reverse_at_signals = IsSavegameVersionBefore(100) || (_settings_game.pf.wait_oneway_signal != 255 && _settings_game.pf.wait_twoway_signal != 255 && _settings_game.pf.wait_for_pbs_path != 255);
2821 Train *t;
2822 FOR_ALL_TRAINS(t) {
2823 _settings_game.vehicle.max_train_length = max<uint8>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
2827 if (IsSavegameVersionBefore(160)) {
2828 /* Setting difficulty industry_density other than zero get bumped to +1
2829 * since a new option (minimal at position 1) has been added */
2830 if (_settings_game.difficulty.industry_density > 0) {
2831 _settings_game.difficulty.industry_density++;
2835 if (IsSavegameVersionBefore(161)) {
2836 /* Before savegame version 161, persistent storages were not stored in a pool. */
2838 if (!IsSavegameVersionBefore(76)) {
2839 Industry *ind;
2840 FOR_ALL_INDUSTRIES(ind) {
2841 assert(ind->psa != nullptr);
2843 /* Check if the old storage was empty. */
2844 bool is_empty = true;
2845 for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
2846 if (ind->psa->GetValue(i) != 0) {
2847 is_empty = false;
2848 break;
2852 if (!is_empty) {
2853 ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
2854 } else {
2855 delete ind->psa;
2856 ind->psa = nullptr;
2861 if (!IsSavegameVersionBefore(145)) {
2862 Station *st;
2863 FOR_ALL_STATIONS(st) {
2864 if (!(st->facilities & FACIL_AIRPORT)) continue;
2865 assert(st->airport.psa != nullptr);
2867 /* Check if the old storage was empty. */
2868 bool is_empty = true;
2869 for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
2870 if (st->airport.psa->GetValue(i) != 0) {
2871 is_empty = false;
2872 break;
2876 if (!is_empty) {
2877 st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
2878 } else {
2879 delete st->airport.psa;
2880 st->airport.psa = nullptr;
2887 /* This triggers only when old snow_lines were copied into the snow_line_height. */
2888 if (IsSavegameVersionBefore(164) && _settings_game.game_creation.snow_line_height >= MIN_SNOWLINE_HEIGHT * TILE_HEIGHT) {
2889 _settings_game.game_creation.snow_line_height /= TILE_HEIGHT;
2892 if (IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_18_6)) {
2893 _settings_game.game_creation.tree_line_height = _settings_game.game_creation.snow_line_height;
2896 if (IsSavegameVersionBefore(164) && !IsSavegameVersionBefore(32)) {
2897 /* We store 4 fences in the field tiles instead of only SE and SW. */
2898 for (TileIndex t = 0; t < map_size; t++) {
2899 if (!IsTileType(t, MP_CLEAR) && !IsTileType(t, MP_TREES)) continue;
2900 if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) continue;
2901 uint fence = GB(_m[t].m4, 5, 3);
2902 if (fence != 0 && IsTileType(TILE_ADDXY(t, 1, 0), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 1, 0), CLEAR_FIELDS)) {
2903 SetFence(TILE_ADDXY(t, 1, 0), DIAGDIR_NE, fence);
2905 fence = GB(_m[t].m4, 2, 3);
2906 if (fence != 0 && IsTileType(TILE_ADDXY(t, 0, 1), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 0, 1), CLEAR_FIELDS)) {
2907 SetFence(TILE_ADDXY(t, 0, 1), DIAGDIR_NW, fence);
2909 SB(_m[t].m4, 2, 3, 0);
2910 SB(_m[t].m4, 5, 3, 0);
2914 /* The center of train vehicles was changed, fix up spacing. */
2915 if (IsSavegameVersionBefore(164)) FixupTrainLengths();
2917 if (IsSavegameVersionBefore(165)) {
2918 Town *t;
2920 FOR_ALL_TOWNS(t) {
2921 /* Set the default cargo requirement for town growth */
2922 switch (_settings_game.game_creation.landscape) {
2923 case LT_ARCTIC:
2924 if (FindFirstCargoWithTownEffect(TE_FOOD) != nullptr) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
2925 break;
2927 case LT_TROPIC:
2928 if (FindFirstCargoWithTownEffect(TE_FOOD) != nullptr) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
2929 if (FindFirstCargoWithTownEffect(TE_WATER) != nullptr) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
2930 break;
2935 if (IsSavegameVersionBefore(165)) {
2936 /* Adjust zoom level to account for new levels */
2937 _saved_scrollpos_zoom = _saved_scrollpos_zoom + ZOOM_LVL_SHIFT;
2938 _saved_scrollpos_x *= ZOOM_LVL_BASE;
2939 _saved_scrollpos_y *= ZOOM_LVL_BASE;
2942 /* When any NewGRF has been changed the availability of some vehicles might
2943 * have been changed too. e->company_avail must be set to 0 in that case
2944 * which is done by StartupEngines(). */
2945 if (gcf_res != GLC_ALL_GOOD) StartupEngines();
2947 if (IsSavegameVersionBefore(166)) {
2948 /* Update cargo acceptance map of towns. */
2949 for (TileIndex t = 0; t < map_size; t++) {
2950 if (!IsTileType(t, MP_HOUSE)) continue;
2951 Town::Get(GetTownIndex(t))->cargo_accepted.Add(t);
2954 Town *town;
2955 FOR_ALL_TOWNS(town) {
2956 UpdateTownCargoes(town);
2960 /* The road owner of standard road stops was not properly accounted for. */
2961 if (IsSavegameVersionBefore(172)) {
2962 for (TileIndex t = 0; t < map_size; t++) {
2963 if (!IsStandardRoadStopTile(t)) continue;
2964 Owner o = GetTileOwner(t);
2965 SetRoadOwner(t, ROADTYPE_ROAD, o);
2966 SetRoadOwner(t, ROADTYPE_TRAM, o);
2970 if (IsSavegameVersionBefore(175)) {
2971 /* Introduced tree planting limit. */
2972 Company *c;
2973 FOR_ALL_COMPANIES(c) c->tree_limit = _settings_game.construction.tree_frame_burst << 16;
2976 if (IsSavegameVersionBefore(177)) {
2977 /* Fix too high inflation rates */
2978 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
2979 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
2981 /* We have to convert the quarters of bankruptcy into months of bankruptcy */
2982 FOR_ALL_COMPANIES(c) {
2983 c->months_of_bankruptcy = 3 * c->months_of_bankruptcy;
2987 if (IsSavegameVersionBefore(178)) {
2988 extern uint8 _old_diff_level;
2989 /* Initialise script settings profile */
2990 _settings_game.script.settings_profile = IsInsideMM(_old_diff_level, SP_BEGIN, SP_END) ? _old_diff_level : (uint)SP_MEDIUM;
2993 if (IsSavegameVersionBefore(182)) {
2994 Aircraft *v;
2995 /* Aircraft acceleration variable was bonkers */
2996 FOR_ALL_AIRCRAFT(v) {
2997 if (v->subtype <= AIR_AIRCRAFT) {
2998 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
2999 v->acceleration = avi->acceleration;
3003 /* Blocked tiles could be reserved due to a bug, which causes
3004 * other places to assert upon e.g. station reconstruction. */
3005 for (TileIndex t = 0; t < map_size; t++) {
3006 if (HasStationTileRail(t) && IsStationTileBlocked(t)) {
3007 SetRailStationReservation(t, false);
3012 if (IsSavegameVersionBefore(184)) {
3013 /* The global units configuration is split up in multiple configurations. */
3014 extern uint8 _old_units;
3015 _settings_game.locale.units_velocity = Clamp(_old_units, 0, 2);
3016 _settings_game.locale.units_power = Clamp(_old_units, 0, 2);
3017 _settings_game.locale.units_weight = Clamp(_old_units, 1, 2);
3018 _settings_game.locale.units_volume = Clamp(_old_units, 1, 2);
3019 _settings_game.locale.units_force = 2;
3020 _settings_game.locale.units_height = Clamp(_old_units, 0, 2);
3023 if (IsSavegameVersionBefore(186)) {
3024 /* Move ObjectType from map to pool */
3025 for (TileIndex t = 0; t < map_size; t++) {
3026 if (IsTileType(t, MP_OBJECT)) {
3027 Object *o = Object::Get(_m[t].m2);
3028 o->type = _m[t].m5;
3029 _m[t].m5 = 0; // zero upper bits of (now bigger) ObjectID
3034 if (IsSavegameVersionBefore(188)) {
3035 /* Fix articulated road vehicles.
3036 * Some curves were shorter than other curves.
3037 * Now they have the same length, but that means that trailing articulated parts will
3038 * take longer to go through the curve than the parts in front which already left the courve.
3039 * So, make articulated parts catch up. */
3040 RoadVehicle *v;
3041 bool roadside = _settings_game.vehicle.road_side == 1;
3042 SmallVector<uint, 16> skip_frames;
3043 FOR_ALL_ROADVEHICLES(v) {
3044 if (!v->IsFrontEngine()) continue;
3045 skip_frames.Clear();
3046 TileIndex prev_tile = v->tile;
3047 uint prev_tile_skip = 0;
3048 uint cur_skip = 0;
3049 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
3050 if (u->tile != prev_tile) {
3051 prev_tile_skip = cur_skip;
3052 prev_tile = u->tile;
3053 } else {
3054 cur_skip = prev_tile_skip;
3057 uint *this_skip = skip_frames.Append();
3058 *this_skip = prev_tile_skip;
3060 /* The following 3 curves now take longer than before */
3061 switch (u->state) {
3062 case 2:
3063 cur_skip++;
3064 if (u->frame <= (roadside ? 9 : 5)) *this_skip = cur_skip;
3065 break;
3067 case 4:
3068 cur_skip++;
3069 if (u->frame <= (roadside ? 5 : 9)) *this_skip = cur_skip;
3070 break;
3072 case 5:
3073 cur_skip++;
3074 if (u->frame <= (roadside ? 4 : 2)) *this_skip = cur_skip;
3075 break;
3077 default:
3078 break;
3081 while (cur_skip > skip_frames[0]) {
3082 RoadVehicle *u = v;
3083 RoadVehicle *prev = nullptr;
3084 for (uint *it = skip_frames.Begin(); it != skip_frames.End(); ++it, prev = u, u = u->Next()) {
3085 extern bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev);
3086 if (*it >= cur_skip) IndividualRoadVehicleController(u, prev);
3088 cur_skip--;
3093 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_12)) {
3094 Train *t;
3095 FOR_ALL_TRAINS(t) {
3096 t->reverse_distance = 0;
3101 * Only keep order-backups for network clients (and when replaying).
3102 * If we are a network server or not networking, then we just loaded a previously
3103 * saved-by-server savegame. There are no clients with a backup, so clear it.
3104 * Furthermore before savegame version 192 / SL_PATCH_PACK_1_8 the actual content was always corrupt.
3106 if (!_networking || _network_server || IsSavegameVersionBefore(192) || IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_8)) {
3107 #ifndef DEBUG_DUMP_COMMANDS
3108 /* Note: We cannot use CleanPool since that skips part of the destructor
3109 * and then leaks un-reachable Orders in the order pool. */
3110 OrderBackup *ob;
3111 FOR_ALL_ORDER_BACKUPS(ob) {
3112 delete ob;
3114 #endif
3117 if (IsSavegameVersionBefore(198) || IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_26)) {
3118 // Convert towns growth_rate and grow_counter to ticks.
3119 Town *t;
3120 FOR_ALL_TOWNS(t) {
3121 // 0x8000 = TOWN_GROWTH_RATE_CUSTOM previously.
3122 // 0xFFFF = TOWN_GROWTH_RATE_NONE previously.
3123 if (t->growth_rate & 0x8000) SetBit(t->flags, TOWN_CUSTOM_GROWTH);
3124 if (t->growth_rate == 0xFFFF) {
3125 t->growth_rate = TOWN_GROWTH_RATE_NONE;
3126 } else {
3127 t->growth_rate = TownTicksToGameTicks(t->growth_rate & ~0x8000);
3129 // Add t->index % TOWN_GROWTH_TICKS to spread growth across ticks.
3130 t->grow_counter = TownTicksToGameTicks(t->grow_counter) + t->index % TOWN_GROWTH_TICKS;
3134 if (IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_16)) {
3135 /* red/green signal state bit for tunnel entrances moved
3136 * to no longer re-use signalled tunnel exit bit
3138 for (TileIndex t = 0; t < map_size; t++) {
3139 if (IsTileType(t, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL && IsTunnelBridgeWithSignalSimulation(t)) {
3140 if (HasBit(_m[t].m5, 5)) {
3141 /* signalled tunnel entrance */
3142 SignalState state = HasBit(_m[t].m5, 6) ? SIGNAL_STATE_RED : SIGNAL_STATE_GREEN;
3143 ClrBit(_m[t].m5, 6);
3144 SetTunnelBridgeSignalState(t, state);
3150 if (IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_19)) {
3151 /* load_unload_ticks --> tunnel_bridge_signal_num */
3152 Train *t;
3153 FOR_ALL_TRAINS(t) {
3154 TileIndex tile = t->tile;
3155 if (IsTileType(tile, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL && IsTunnelBridgeWithSignalSimulation(tile)) {
3156 t->tunnel_bridge_signal_num = t->load_unload_ticks;
3157 t->load_unload_ticks = 0;
3162 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_19)) {
3163 /* ensure that previously unused custom bridge-head bits are cleared */
3164 for (TileIndex t = 0; t < map_size; t++) {
3165 if (IsBridgeTile(t) && GetTunnelBridgeTransportType(t) == TRANSPORT_ROAD) {
3166 SB(_m[t].m2, 0, 8, 0);
3171 /* Station acceptance is some kind of cache */
3172 if (IsSavegameVersionBefore(127)) {
3173 Station *st;
3174 FOR_ALL_STATIONS(st) UpdateStationAcceptance(st, false);
3177 // Before this version we didn't store the 5th bit of the tracktype here.
3178 // So set it to 0 just in case there was garbage in there.
3179 if (IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_14)) {
3180 for (TileIndex t = 0; t < map_size; t++) {
3181 if (GetTileType(t) == MP_RAILWAY ||
3182 IsLevelCrossingTile(t) ||
3183 IsRailStationTile(t) ||
3184 IsRailWaypointTile(t) ||
3185 IsRailTunnelBridgeTile(t)) {
3186 ClrBit(_m[t].m1, 7);
3191 /* Set lifetime vehicle profit to 0 if save game before 195 */
3192 if (IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_14)) {
3193 Vehicle *v;
3194 FOR_ALL_VEHICLES(v) {
3195 v->profit_lifetime = v->profit_last_year;
3199 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_24)) {
3200 Vehicle *v;
3201 FOR_ALL_VEHICLES(v) {
3202 v->cur_timetable_order_index = v->GetNumManualOrders() > 0 ? v->cur_real_order_index : INVALID_VEH_ORDER_ID;
3204 OrderBackup *bckup;
3205 FOR_ALL_ORDER_BACKUPS(bckup) {
3206 bckup->cur_timetable_order_index = INVALID_VEH_ORDER_ID;
3208 Order *order;
3209 FOR_ALL_ORDERS(order) {
3210 if (order->IsType(OT_CONDITIONAL)) {
3211 if (order->GetTravelTime() != 0) {
3212 DEBUG(sl, 1, "Fixing: order->GetTravelTime() != 0, %u", order->GetTravelTime());
3213 order->SetTravelTime(0);
3217 OrderList *order_list;
3218 FOR_ALL_ORDER_LISTS(order_list) {
3219 order_list->DebugCheckSanity();
3223 /* Road stops is 'only' updating some caches */
3224 AfterLoadRoadStops();
3225 AfterLoadLabelMaps();
3226 AfterLoadCompanyStats();
3227 AfterLoadStoryBook();
3229 GamelogPrintDebug(1);
3231 InitializeWindowsAndCaches();
3232 /* Restore the signals */
3233 ResetSignalHandlers();
3235 AfterLoadLinkGraphs();
3237 AfterLoadTraceRestrict();
3239 AfterLoadTemplateVehiclesUpdateImage();
3241 return true;
3245 * Reload all NewGRF files during a running game. This is a cut-down
3246 * version of AfterLoadGame().
3247 * XXX - We need to reset the vehicle position hash because with a non-empty
3248 * hash AfterLoadVehicles() will loop infinitely. We need AfterLoadVehicles()
3249 * to recalculate vehicle data as some NewGRF vehicle sets could have been
3250 * removed or added and changed statistics
3252 void ReloadNewGRFData()
3254 RailTypeLabel rail_type_label_map[RAILTYPE_END];
3255 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
3256 rail_type_label_map[rt] = GetRailTypeInfo(rt)->label;
3259 /* reload grf data */
3260 GfxLoadSprites();
3261 LoadStringWidthTable();
3262 RecomputePrices();
3263 /* reload vehicles */
3264 ResetVehicleHash();
3265 AfterLoadVehicles(false);
3266 StartupEngines();
3267 GroupStatistics::UpdateAfterLoad();
3268 /* update station graphics */
3269 AfterLoadStations();
3270 /* Update company statistics. */
3271 AfterLoadCompanyStats();
3272 /* Check and update house and town values */
3273 UpdateHousesAndTowns();
3274 /* Delete news referring to no longer existing entities */
3275 DeleteInvalidEngineNews();
3276 /* Update livery selection windows */
3277 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i);
3278 /* Update company infrastructure counts. */
3279 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
3280 /* redraw the whole screen */
3281 MarkWholeScreenDirty();
3282 CheckTrainsLengths();
3283 AfterLoadTemplateVehiclesUpdateImage();
3285 RailType rail_type_translate_map[RAILTYPE_END];
3286 for (RailType old_type = RAILTYPE_BEGIN; old_type != RAILTYPE_END; old_type++) {
3287 RailType new_type = GetRailTypeByLabel(rail_type_label_map[old_type]);
3288 rail_type_translate_map[old_type] = (new_type == INVALID_RAILTYPE) ? RAILTYPE_RAIL : new_type;
3291 /* Restore correct railtype for all rail tiles.*/
3292 const TileIndex map_size = MapSize();
3293 for (TileIndex t = 0; t < map_size; t++) {
3294 if (GetTileType(t) == MP_RAILWAY ||
3295 IsLevelCrossingTile(t) ||
3296 IsRailStationTile(t) ||
3297 IsRailWaypointTile(t) ||
3298 IsRailTunnelBridgeTile(t)) {
3299 SetRailType(t, rail_type_translate_map[GetRailType(t)]);