Update: Translations from eints
[openttd-github.git] / src / saveload / afterload.cpp
blobc0603da2c00684a5c0b80a42a2cd0c5cf64e9bbf
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file afterload.cpp Code updating data after game load */
10 #include "../stdafx.h"
11 #include "../void_map.h"
12 #include "../signs_base.h"
13 #include "../depot_base.h"
14 #include "../fios.h"
15 #include "../gamelog_internal.h"
16 #include "../network/network.h"
17 #include "../network/network_func.h"
18 #include "../gfxinit.h"
19 #include "../viewport_func.h"
20 #include "../viewport_kdtree.h"
21 #include "../industry.h"
22 #include "../clear_map.h"
23 #include "../vehicle_func.h"
24 #include "../string_func.h"
25 #include "../roadveh.h"
26 #include "../roadveh_cmd.h"
27 #include "../train.h"
28 #include "../station_base.h"
29 #include "../waypoint_base.h"
30 #include "../roadstop_base.h"
31 #include "../tunnelbridge_map.h"
32 #include "../pathfinder/yapf/yapf_cache.h"
33 #include "../elrail_func.h"
34 #include "../signs_func.h"
35 #include "../aircraft.h"
36 #include "../object_map.h"
37 #include "../object_base.h"
38 #include "../tree_map.h"
39 #include "../company_func.h"
40 #include "../road_cmd.h"
41 #include "../ai/ai.hpp"
42 #include "../script/script_gui.h"
43 #include "../game/game.hpp"
44 #include "../town.h"
45 #include "../economy_base.h"
46 #include "../animated_tile_func.h"
47 #include "../subsidy_base.h"
48 #include "../subsidy_func.h"
49 #include "../newgrf.h"
50 #include "../newgrf_station.h"
51 #include "../engine_func.h"
52 #include "../rail_gui.h"
53 #include "../core/backup_type.hpp"
54 #include "../smallmap_gui.h"
55 #include "../news_func.h"
56 #include "../order_backup.h"
57 #include "../error.h"
58 #include "../disaster_vehicle.h"
59 #include "../ship.h"
60 #include "../water.h"
61 #include "../timer/timer.h"
62 #include "../timer/timer_game_calendar.h"
63 #include "../timer/timer_game_economy.h"
64 #include "../timer/timer_game_tick.h"
66 #include "saveload_internal.h"
68 #include <signal.h>
70 #include "../safeguards.h"
71 #include "window_func.h"
73 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
75 /**
76 * Makes a tile canal or water depending on the surroundings.
78 * Must only be used for converting old savegames. Use WaterClass now.
80 * This as for example docks and shipdepots do not store
81 * whether the tile used to be canal or 'normal' water.
82 * @param t the tile to change.
83 * @param include_invalid_water_class Also consider WATER_CLASS_INVALID, i.e. industry tiles on land
85 void SetWaterClassDependingOnSurroundings(Tile t, bool include_invalid_water_class)
87 /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
88 * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
89 if (!IsTileFlat(t)) {
90 if (include_invalid_water_class) {
91 SetWaterClass(t, WATER_CLASS_INVALID);
92 return;
93 } else {
94 SlErrorCorrupt("Invalid water class for dry tile");
98 /* Mark tile dirty in all cases */
99 MarkTileDirtyByTile(t);
101 if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == Map::MaxX() - 1 || TileY(t) == Map::MaxY() - 1) {
102 /* tiles at map borders are always WATER_CLASS_SEA */
103 SetWaterClass(t, WATER_CLASS_SEA);
104 return;
107 bool has_water = false;
108 bool has_canal = false;
109 bool has_river = false;
111 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
112 Tile neighbour = TileAddByDiagDir(t, dir);
113 switch (GetTileType(neighbour)) {
114 case MP_WATER:
115 /* clear water and shipdepots have already a WaterClass associated */
116 if (IsCoast(neighbour)) {
117 has_water = true;
118 } else if (!IsLock(neighbour)) {
119 switch (GetWaterClass(neighbour)) {
120 case WATER_CLASS_SEA: has_water = true; break;
121 case WATER_CLASS_CANAL: has_canal = true; break;
122 case WATER_CLASS_RIVER: has_river = true; break;
123 default: SlErrorCorrupt("Invalid water class for tile");
126 break;
128 case MP_RAILWAY:
129 /* Shore or flooded halftile */
130 has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
131 break;
133 case MP_TREES:
134 /* trees on shore */
135 has_water |= (GB(neighbour.m2(), 4, 2) == TREE_GROUND_SHORE);
136 break;
138 default: break;
142 if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
143 SetWaterClass(t, WATER_CLASS_INVALID);
144 return;
147 if (has_river && !has_canal) {
148 SetWaterClass(t, WATER_CLASS_RIVER);
149 } else if (has_canal || !has_water) {
150 SetWaterClass(t, WATER_CLASS_CANAL);
151 } else {
152 SetWaterClass(t, WATER_CLASS_SEA);
156 static void ConvertTownOwner()
158 for (auto tile : Map::Iterate()) {
159 switch (GetTileType(tile)) {
160 case MP_ROAD:
161 if (GB(tile.m5(), 4, 2) == ROAD_TILE_CROSSING && HasBit(tile.m3(), 7)) {
162 tile.m3() = OWNER_TOWN;
164 [[fallthrough]];
166 case MP_TUNNELBRIDGE:
167 if (tile.m1() & 0x80) SetTileOwner(tile, OWNER_TOWN);
168 break;
170 default: break;
175 /* since savegame version 4.1, exclusive transport rights are stored at towns */
176 static void UpdateExclusiveRights()
178 for (Town *t : Town::Iterate()) {
179 t->exclusivity = INVALID_COMPANY;
182 /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
183 * could be implemented this way:
184 * 1.) Go through all stations
185 * Build an array town_blocked[ town_id ][ company_id ]
186 * that stores if at least one station in that town is blocked for a company
187 * 2.) Go through that array, if you find a town that is not blocked for
188 * one company, but for all others, then give it exclusivity.
192 static const uint8_t convert_currency[] = {
193 0, 1, 12, 8, 3,
194 10, 14, 19, 4, 5,
195 9, 11, 13, 6, 17,
196 16, 22, 21, 7, 15,
197 18, 2, 20,
200 /* since savegame version 4.2 the currencies are arranged differently */
201 static void UpdateCurrencies()
203 _settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
206 /* Up to revision 1413 the invisible tiles at the southern border have not been
207 * MP_VOID, even though they should have. This is fixed by this function
209 static void UpdateVoidTiles()
211 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, Map::MaxY()));
212 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(Map::MaxX(), y));
215 static inline RailType UpdateRailType(RailType rt, RailType min)
217 return rt >= min ? (RailType)(rt + 1): rt;
221 * Update the viewport coordinates of all signs.
223 void UpdateAllVirtCoords()
225 UpdateAllStationVirtCoords();
226 UpdateAllSignVirtCoords();
227 UpdateAllTownVirtCoords();
228 UpdateAllTextEffectVirtCoords();
229 RebuildViewportKdtree();
232 void ClearAllCachedNames()
234 ClearAllStationCachedNames();
235 ClearAllTownCachedNames();
236 ClearAllIndustryCachedNames();
240 * Initialization of the windows and several kinds of caches.
241 * This is not done directly in AfterLoadGame because these
242 * functions require that all saveload conversions have been
243 * done. As people tend to add savegame conversion stuff after
244 * the initialization of the windows and caches quite some bugs
245 * had been made.
246 * Moving this out of there is both cleaner and less bug-prone.
248 static void InitializeWindowsAndCaches()
250 /* Initialize windows */
251 ResetWindowSystem();
252 SetupColoursAndInitialWindow();
254 /* Update coordinates of the signs. */
255 ClearAllCachedNames();
256 UpdateAllVirtCoords();
257 ResetViewportAfterLoadGame();
259 for (Company *c : Company::Iterate()) {
260 /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
261 * accordingly if it is not the case. No need to set it on companies that are not been used already,
262 * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
263 if (_file_to_saveload.abstract_ftype == FT_SCENARIO && c->inaugurated_year != EconomyTime::MIN_YEAR) {
264 c->inaugurated_year = TimerGameEconomy::year;
268 /* Count number of objects per type */
269 for (Object *o : Object::Iterate()) {
270 Object::IncTypeCount(o->type);
273 /* Identify owners of persistent storage arrays */
274 for (Industry *i : Industry::Iterate()) {
275 if (i->psa != nullptr) {
276 i->psa->feature = GSF_INDUSTRIES;
277 i->psa->tile = i->location.tile;
280 for (Station *s : Station::Iterate()) {
281 if (s->airport.psa != nullptr) {
282 s->airport.psa->feature = GSF_AIRPORTS;
283 s->airport.psa->tile = s->airport.tile;
286 for (Town *t : Town::Iterate()) {
287 for (auto &it : t->psa_list) {
288 it->feature = GSF_FAKE_TOWNS;
289 it->tile = t->xy;
292 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
293 if (rv->IsFrontEngine()) {
294 rv->CargoChanged();
298 RecomputePrices();
300 GroupStatistics::UpdateAfterLoad();
302 RebuildSubsidisedSourceAndDestinationCache();
304 /* Towns have a noise controlled number of airports system
305 * So each airport's noise value must be added to the town->noise_reached value
306 * Reset each town's noise_reached value to '0' before. */
307 UpdateAirportsNoise();
309 CheckTrainsLengths();
310 ShowNewGRFError();
312 /* Rebuild the smallmap list of owners. */
313 BuildOwnerLegend();
316 typedef void (CDECL *SignalHandlerPointer)(int);
317 static SignalHandlerPointer _prev_segfault = nullptr;
318 static SignalHandlerPointer _prev_abort = nullptr;
319 static SignalHandlerPointer _prev_fpe = nullptr;
321 static void CDECL HandleSavegameLoadCrash(int signum);
324 * Replaces signal handlers of SIGSEGV and SIGABRT
325 * and stores pointers to original handlers in memory.
327 static void SetSignalHandlers()
329 _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
330 _prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
331 _prev_fpe = signal(SIGFPE, HandleSavegameLoadCrash);
335 * Resets signal handlers back to original handlers.
337 static void ResetSignalHandlers()
339 signal(SIGSEGV, _prev_segfault);
340 signal(SIGABRT, _prev_abort);
341 signal(SIGFPE, _prev_fpe);
344 /** Was the saveload crash because of missing NewGRFs? */
345 static bool _saveload_crash_with_missing_newgrfs = false;
348 * Did loading the savegame cause a crash? If so,
349 * were NewGRFs missing?
350 * @return when the saveload crashed due to missing NewGRFs.
352 bool SaveloadCrashWithMissingNewGRFs()
354 return _saveload_crash_with_missing_newgrfs;
358 * Signal handler used to give a user a more useful report for crashes during
359 * the savegame loading process; especially when there's problems with the
360 * NewGRFs that are required by the savegame.
361 * @param signum received signal
363 static void CDECL HandleSavegameLoadCrash(int signum)
365 ResetSignalHandlers();
367 std::string message;
368 message.reserve(1024);
369 message += "Loading your savegame caused OpenTTD to crash.\n";
371 for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != nullptr; c = c->next) {
372 _saveload_crash_with_missing_newgrfs = HasBit(c->flags, GCF_COMPATIBLE) || c->status == GCS_NOT_FOUND;
375 if (_saveload_crash_with_missing_newgrfs) {
376 message +=
377 "This is most likely caused by a missing NewGRF or a NewGRF that\n"
378 "has been loaded as replacement for a missing NewGRF. OpenTTD\n"
379 "cannot easily determine whether a replacement NewGRF is of a newer\n"
380 "or older version.\n"
381 "It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
382 "This means that if the author makes incompatible NewGRFs with the\n"
383 "same GRF ID, OpenTTD cannot magically do the right thing. In most\n"
384 "cases, OpenTTD will load the savegame and not crash, but this is an\n"
385 "exception.\n"
386 "Please load the savegame with the appropriate NewGRFs installed.\n"
387 "The missing/compatible NewGRFs are:\n";
389 for (const GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
390 if (HasBit(c->flags, GCF_COMPATIBLE)) {
391 const GRFIdentifier *replaced = _gamelog.GetOverriddenIdentifier(c);
392 fmt::format_to(std::back_inserter(message), "NewGRF {:08X} (checksum {}) not found.\n Loaded NewGRF \"{}\" (checksum {}) with same GRF ID instead.\n",
393 BSWAP32(c->ident.grfid), FormatArrayAsHex(c->original_md5sum), c->filename, FormatArrayAsHex(replaced->md5sum));
395 if (c->status == GCS_NOT_FOUND) {
396 fmt::format_to(std::back_inserter(message), "NewGRF {:08X} ({}) not found; checksum {}.\n",
397 BSWAP32(c->ident.grfid), c->filename, FormatArrayAsHex(c->ident.md5sum));
400 } else {
401 message +=
402 "This is probably caused by a corruption in the savegame.\n"
403 "Please file a bug report and attach this savegame.\n";
406 ShowInfoI(message);
408 SignalHandlerPointer call = nullptr;
409 switch (signum) {
410 case SIGSEGV: call = _prev_segfault; break;
411 case SIGABRT: call = _prev_abort; break;
412 case SIGFPE: call = _prev_fpe; break;
413 default: NOT_REACHED();
415 if (call != nullptr) call(signum);
419 * Tries to change owner of this rail tile to a valid owner. In very old versions it could happen that
420 * a rail track had an invalid owner. When conversion isn't possible, track is removed.
421 * @param t tile to update
423 static void FixOwnerOfRailTrack(Tile t)
425 assert(!Company::IsValidID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
427 /* remove leftover rail piece from crossing (from very old savegames) */
428 Train *v = nullptr;
429 for (Train *w : Train::Iterate()) {
430 if (w->tile == TileIndex(t)) {
431 v = w;
432 break;
436 if (v != nullptr) {
437 /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
438 SetTileOwner(t, v->owner);
439 return;
442 /* try to find any connected rail */
443 for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
444 TileIndex tt = t + TileOffsByDiagDir(dd);
445 if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
446 GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
447 Company::IsValidID(GetTileOwner(tt))) {
448 SetTileOwner(t, GetTileOwner(tt));
449 return;
453 if (IsLevelCrossingTile(t)) {
454 /* else change the crossing to normal road (road vehicles won't care) */
455 Owner road = GetRoadOwner(t, RTT_ROAD);
456 Owner tram = GetRoadOwner(t, RTT_TRAM);
457 RoadBits bits = GetCrossingRoadBits(t);
458 bool hasroad = HasBit(t.m7(), 6);
459 bool hastram = HasBit(t.m7(), 7);
461 /* MakeRoadNormal */
462 SetTileType(t, MP_ROAD);
463 SetTileOwner(t, road);
464 t.m3() = (hasroad ? bits : 0);
465 t.m5() = (hastram ? bits : 0) | ROAD_TILE_NORMAL << 6;
466 SB(t.m6(), 2, 4, 0);
467 SetRoadOwner(t, RTT_TRAM, tram);
468 return;
471 /* if it's not a crossing, make it clean land */
472 MakeClear(t, CLEAR_GRASS, 0);
476 * Fixes inclination of a vehicle. Older OpenTTD versions didn't update the bits correctly.
477 * @param v vehicle
478 * @param dir vehicle's direction, or # INVALID_DIR if it can be ignored
479 * @return inclination bits to set
481 static uint FixVehicleInclination(Vehicle *v, Direction dir)
483 /* Compute place where this vehicle entered the tile */
484 int entry_x = v->x_pos;
485 int entry_y = v->y_pos;
486 switch (dir) {
487 case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
488 case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
489 case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
490 case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
491 case INVALID_DIR: break;
492 default: NOT_REACHED();
494 uint8_t entry_z = GetSlopePixelZ(entry_x, entry_y, true);
496 /* Compute middle of the tile. */
497 int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
498 int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
499 uint8_t middle_z = GetSlopePixelZ(middle_x, middle_y, true);
501 /* middle_z == entry_z, no height change. */
502 if (middle_z == entry_z) return 0;
504 /* middle_z < entry_z, we are going downwards. */
505 if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
507 /* middle_z > entry_z, we are going upwards. */
508 return 1U << GVF_GOINGUP_BIT;
512 * Check whether the ground vehicles are at the correct Z-coordinate. When they
513 * are not, this will cause all kinds of problems later on as the vehicle might
514 * not get onto bridges and so on.
516 static void CheckGroundVehiclesAtCorrectZ()
518 for (Vehicle *v : Vehicle::Iterate()) {
519 if (v->IsGroundVehicle()) {
521 * Either the vehicle is not actually on the given tile, i.e. it is
522 * in the wormhole of a bridge or a tunnel, or the Z-coordinate must
523 * be the same as when it would be recalculated right now.
525 assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos, true));
531 * Checks for the possibility that a bridge may be on this tile
532 * These are in fact all the tile types on which a bridge can be found
533 * @param t The tile to analyze
534 * @return True if a bridge might have been present prior to savegame 194.
536 static inline bool MayHaveBridgeAbove(Tile t)
538 return IsTileType(t, MP_CLEAR) || IsTileType(t, MP_RAILWAY) || IsTileType(t, MP_ROAD) ||
539 IsTileType(t, MP_WATER) || IsTileType(t, MP_TUNNELBRIDGE) || IsTileType(t, MP_OBJECT);
543 * Start the scripts.
545 static void StartScripts()
547 /* Script debug window requires AIs to be started before trying to start GameScript. */
549 /* Start the AIs. */
550 for (const Company *c : Company::Iterate()) {
551 if (Company::IsValidAiID(c->index)) AI::StartNew(c->index);
554 /* Start the GameScript. */
555 Game::StartNew();
557 ShowScriptDebugWindowIfScriptError();
561 * Perform a (large) amount of savegame conversion *magic* in order to
562 * load older savegames and to fill the caches for various purposes.
563 * @return True iff conversion went without a problem.
565 bool AfterLoadGame()
567 SetSignalHandlers();
569 extern TileIndex _cur_tileloop_tile; // From landscape.cpp.
570 /* The LFSR used in RunTileLoop iteration cannot have a zeroed state, make it non-zeroed. */
571 if (_cur_tileloop_tile == 0) _cur_tileloop_tile = 1;
573 if (IsSavegameVersionBefore(SLV_98)) _gamelog.Oldver();
575 _gamelog.TestRevision();
576 _gamelog.TestMode();
578 RebuildTownKdtree();
579 RebuildStationKdtree();
580 /* This needs to be done even before conversion, because some conversions will destroy objects
581 * that otherwise won't exist in the tree. */
582 RebuildViewportKdtree();
584 if (IsSavegameVersionBefore(SLV_98)) _gamelog.GRFAddList(_grfconfig);
586 if (IsSavegameVersionBefore(SLV_119)) {
587 _pause_mode = (_pause_mode == 2) ? PM_PAUSED_NORMAL : PM_UNPAUSED;
588 } else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
589 Debug(net, 0, "The loading savegame was paused due to an error state");
590 Debug(net, 0, " This savegame cannot be used for multiplayer");
591 /* Restore the signals */
592 ResetSignalHandlers();
593 return false;
594 } else if (!_networking || _network_server) {
595 /* If we are in singleplayer mode, i.e. not networking, and loading the
596 * savegame or we are loading the savegame as network server we do
597 * not want to be bothered by being paused because of the automatic
598 * reason of a network server, e.g. joining clients or too few
599 * active clients. Note that resetting these values for a network
600 * client are very bad because then the client is going to execute
601 * the game loop when the server is not, i.e. it desyncs. */
602 _pause_mode &= ~PMB_PAUSED_NETWORK;
605 /* In very old versions, size of train stations was stored differently.
606 * They had swapped width and height if station was built along the Y axis.
607 * TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
608 * Because the data stored by TTDPatch are unusable for rail stations > 7x7,
609 * recompute the width and height. Doing this unconditionally for all old
610 * savegames simplifies the code. */
611 if (IsSavegameVersionBefore(SLV_2)) {
612 for (Station *st : Station::Iterate()) {
613 st->train_station.w = st->train_station.h = 0;
615 for (auto t : Map::Iterate()) {
616 if (!IsTileType(t, MP_STATION)) continue;
617 if (t.m5() > 7) continue; // is it a rail station tile?
618 Station *st = Station::Get(t.m2());
619 assert(st->train_station.tile != 0);
620 int dx = TileX(t) - TileX(st->train_station.tile);
621 int dy = TileY(t) - TileY(st->train_station.tile);
622 assert(dx >= 0 && dy >= 0);
623 st->train_station.w = std::max<uint>(st->train_station.w, dx + 1);
624 st->train_station.h = std::max<uint>(st->train_station.h, dy + 1);
628 if (IsSavegameVersionBefore(SLV_194)) {
629 _settings_game.construction.map_height_limit = 15;
631 /* In old savegame versions, the heightlevel was coded in bits 0..3 of the type field */
632 for (auto t : Map::Iterate()) {
633 t.height() = GB(t.type(), 0, 4);
634 SB(t.type(), 0, 2, GB(t.m6(), 0, 2));
635 SB(t.m6(), 0, 2, 0);
636 if (MayHaveBridgeAbove(t)) {
637 SB(t.type(), 2, 2, GB(t.m6(), 6, 2));
638 SB(t.m6(), 6, 2, 0);
639 } else {
640 SB(t.type(), 2, 2, 0);
645 /* in version 2.1 of the savegame, town owner was unified. */
646 if (IsSavegameVersionBefore(SLV_2, 1)) ConvertTownOwner();
648 /* from version 4.1 of the savegame, exclusive rights are stored at towns */
649 if (IsSavegameVersionBefore(SLV_4, 1)) UpdateExclusiveRights();
651 /* from version 4.2 of the savegame, currencies are in a different order */
652 if (IsSavegameVersionBefore(SLV_4, 2)) UpdateCurrencies();
654 /* In old version there seems to be a problem that water is owned by
655 * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
656 * (4.3) version, so I just check when versions are older, and then
657 * walk through the whole map.. */
658 if (IsSavegameVersionBefore(SLV_4, 3)) {
659 for (auto t : Map::Iterate()) {
660 if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
661 SetTileOwner(t, OWNER_WATER);
666 if (IsSavegameVersionBefore(SLV_84)) {
667 for (Company *c : Company::Iterate()) {
668 c->name = CopyFromOldName(c->name_1);
669 if (!c->name.empty()) c->name_1 = STR_SV_UNNAMED;
670 c->president_name = CopyFromOldName(c->president_name_1);
671 if (!c->president_name.empty()) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
674 for (Station *st : Station::Iterate()) {
675 st->name = CopyFromOldName(st->string_id);
676 /* generating new name would be too much work for little effect, use the station name fallback */
677 if (!st->name.empty()) st->string_id = STR_SV_STNAME_FALLBACK;
680 for (Town *t : Town::Iterate()) {
681 t->name = CopyFromOldName(t->townnametype);
682 if (!t->name.empty()) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
686 /* From this point the old names array is cleared. */
687 ResetOldNames();
689 if (IsSavegameVersionBefore(SLV_106)) {
690 /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
691 for (Station *st : Station::Iterate()) {
692 if (st->airport.tile == 0) st->airport.tile = INVALID_TILE;
693 if (st->train_station.tile == 0) st->train_station.tile = INVALID_TILE;
696 /* the same applies to Company::location_of_HQ */
697 for (Company *c : Company::Iterate()) {
698 if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(SLV_4) && c->location_of_HQ == 0xFFFF)) {
699 c->location_of_HQ = INVALID_TILE;
704 /* convert road side to my format. */
705 if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
707 /* Check if all NewGRFs are present, we are very strict in MP mode */
708 GRFListCompatibility gcf_res = IsGoodGRFConfigList(_grfconfig);
709 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
710 if (c->status == GCS_NOT_FOUND) {
711 _gamelog.GRFRemove(c->ident.grfid);
712 } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
713 _gamelog.GRFCompatible(&c->ident);
717 if (_networking && gcf_res != GLC_ALL_GOOD) {
718 SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
719 /* Restore the signals */
720 ResetSignalHandlers();
721 return false;
724 switch (gcf_res) {
725 case GLC_COMPATIBLE: ShowErrorMessage(STR_NEWGRF_COMPATIBLE_LOAD_WARNING, INVALID_STRING_ID, WL_CRITICAL); break;
726 case GLC_NOT_FOUND: ShowErrorMessage(STR_NEWGRF_DISABLED_WARNING, INVALID_STRING_ID, WL_CRITICAL); _pause_mode = PM_PAUSED_ERROR; break;
727 default: break;
730 /* The value of TimerGameCalendar::date_fract got divided, so make sure that old games are converted correctly. */
731 if (IsSavegameVersionBefore(SLV_11, 1) || (IsSavegameVersionBefore(SLV_147) && TimerGameCalendar::date_fract > Ticks::DAY_TICKS)) TimerGameCalendar::date_fract /= 885;
733 /* Update current year
734 * must be done before loading sprites as some newgrfs check it */
735 TimerGameCalendar::SetDate(TimerGameCalendar::date, TimerGameCalendar::date_fract);
737 /* Only new games can use wallclock units. */
738 if (IsSavegameVersionBefore(SLV_ECONOMY_MODE_TIMEKEEPING_UNITS)) _settings_game.economy.timekeeping_units = TKU_CALENDAR;
740 /* Update economy year. If we don't have a separate economy date saved, follow the calendar date. */
741 if (IsSavegameVersionBefore(SLV_ECONOMY_DATE)) {
742 TimerGameEconomy::SetDate(TimerGameCalendar::date.base(), TimerGameCalendar::date_fract);
743 } else {
744 TimerGameEconomy::SetDate(TimerGameEconomy::date, TimerGameEconomy::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(SLV_4, 2)) _settings_game.station.modified_catchment = false;
761 if (IsSavegameVersionBefore(SLV_6, 1)) _settings_game.pf.forbid_90_deg = false;
762 if (IsSavegameVersionBefore(SLV_21)) _settings_game.vehicle.train_acceleration_model = 0;
763 if (IsSavegameVersionBefore(SLV_90)) _settings_game.vehicle.plane_speed = 4;
764 if (IsSavegameVersionBefore(SLV_95)) _settings_game.vehicle.dynamic_engines = false;
765 if (IsSavegameVersionBefore(SLV_96)) _settings_game.economy.station_noise_level = false;
766 if (IsSavegameVersionBefore(SLV_133)) {
767 _settings_game.vehicle.train_slope_steepness = 3;
769 if (IsSavegameVersionBefore(SLV_134)) _settings_game.economy.feeder_payment_share = 75;
770 if (IsSavegameVersionBefore(SLV_138)) _settings_game.vehicle.plane_crashes = 2;
771 if (IsSavegameVersionBefore(SLV_139)) {
772 _settings_game.vehicle.roadveh_acceleration_model = 0;
773 _settings_game.vehicle.roadveh_slope_steepness = 7;
775 if (IsSavegameVersionBefore(SLV_143)) _settings_game.economy.allow_town_level_crossings = true;
776 if (IsSavegameVersionBefore(SLV_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(SLV_166)) _settings_game.economy.infrastructure_maintenance = false;
782 if (IsSavegameVersionBefore(SLV_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 if (IsSavegameVersionBefore(SLV_ENDING_YEAR)) {
790 _settings_game.game_creation.ending_year = CalendarTime::DEF_END_YEAR;
793 /* Convert linkgraph update settings from days to seconds. */
794 if (IsSavegameVersionBefore(SLV_LINKGRAPH_SECONDS)) {
795 _settings_game.linkgraph.recalc_interval *= CalendarTime::SECONDS_PER_DAY;
796 _settings_game.linkgraph.recalc_time *= CalendarTime::SECONDS_PER_DAY;
799 /* Load the sprites */
800 GfxLoadSprites();
801 LoadStringWidthTable();
803 /* Copy temporary data to Engine pool */
804 CopyTempEngineData();
806 /* Connect front and rear engines of multiheaded trains and converts
807 * subtype to the new format */
808 if (IsSavegameVersionBefore(SLV_17, 1)) ConvertOldMultiheadToNew();
810 /* Connect front and rear engines of multiheaded trains */
811 ConnectMultiheadedTrains();
813 /* Fix the CargoPackets *and* fix the caches of CargoLists.
814 * If this isn't done before Stations and especially Vehicles are
815 * running their AfterLoad we might get in trouble. In the case of
816 * vehicles we could give the wrong (cached) count of items in a
817 * vehicle which causes different results when getting their caches
818 * filled; and that could eventually lead to desyncs. */
819 CargoPacket::AfterLoad();
821 /* Update all vehicles: Phase 1 */
822 AfterLoadVehiclesPhase1(true);
824 /* make sure there is a town in the game */
825 if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
826 SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
827 /* Restore the signals */
828 ResetSignalHandlers();
829 return false;
832 /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
833 * This problem appears in savegame version 21 too, see r3455. But after loading the
834 * savegame and saving again, the buggy map array could be converted to new savegame
835 * version. It didn't show up before r12070. */
836 if (IsSavegameVersionBefore(SLV_87)) UpdateVoidTiles();
838 /* Fix the cache for cargo payments. */
839 for (CargoPayment *cp : CargoPayment::Iterate()) {
840 cp->front->cargo_payment = cp;
841 cp->current_station = cp->front->last_station_visited;
845 if (IsSavegameVersionBefore(SLV_WATER_TILE_TYPE)) {
846 /* Prior to SLV_WATER_TILE_TYPE, the water tile type was stored differently from the enumeration. This has to be
847 * converted before SLV_72 and SLV_82 conversions which use GetWaterTileType. */
848 static constexpr uint8_t WBL_COAST_FLAG = 0; ///< Flag for coast.
850 for (auto t : Map::Iterate()) {
851 if (!IsTileType(t, MP_WATER)) continue;
853 switch (GB(t.m5(), 4, 4)) {
854 case 0x0: /* Previously WBL_TYPE_NORMAL, Clear water or coast. */
855 SetWaterTileType(t, HasBit(t.m5(), WBL_COAST_FLAG) ? WATER_TILE_COAST : WATER_TILE_CLEAR);
856 break;
858 case 0x1: SetWaterTileType(t, WATER_TILE_LOCK); break; /* Previously WBL_TYPE_LOCK */
859 case 0x8: SetWaterTileType(t, WATER_TILE_DEPOT); break; /* Previously WBL_TYPE_DEPOT */
860 default: SetWaterTileType(t, WATER_TILE_CLEAR); break; /* Shouldn't happen... */
865 if (IsSavegameVersionBefore(SLV_72)) {
866 /* Locks in very old savegames had OWNER_WATER as owner */
867 for (auto t : Map::Iterate()) {
868 switch (GetTileType(t)) {
869 default: break;
871 case MP_WATER:
872 if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
873 break;
875 case MP_STATION: {
876 if (HasBit(t.m6(), 3)) SetBit(t.m6(), 2);
877 StationGfx gfx = GetStationGfx(t);
878 StationType st;
879 if ( IsInsideMM(gfx, 0, 8)) { // Rail station
880 st = STATION_RAIL;
881 SetStationGfx(t, gfx - 0);
882 } else if (IsInsideMM(gfx, 8, 67)) { // Airport
883 st = STATION_AIRPORT;
884 SetStationGfx(t, gfx - 8);
885 } else if (IsInsideMM(gfx, 67, 71)) { // Truck
886 st = STATION_TRUCK;
887 SetStationGfx(t, gfx - 67);
888 } else if (IsInsideMM(gfx, 71, 75)) { // Bus
889 st = STATION_BUS;
890 SetStationGfx(t, gfx - 71);
891 } else if (gfx == 75) { // Oil rig
892 st = STATION_OILRIG;
893 SetStationGfx(t, gfx - 75);
894 } else if (IsInsideMM(gfx, 76, 82)) { // Dock
895 st = STATION_DOCK;
896 SetStationGfx(t, gfx - 76);
897 } else if (gfx == 82) { // Buoy
898 st = STATION_BUOY;
899 SetStationGfx(t, gfx - 82);
900 } else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
901 st = STATION_AIRPORT;
902 SetStationGfx(t, gfx - 83 + 67 - 8);
903 } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
904 st = STATION_TRUCK;
905 SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
906 } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
907 st = STATION_BUS;
908 SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
909 } else {
910 /* Restore the signals */
911 ResetSignalHandlers();
912 return false;
914 SB(t.m6(), 3, 3, st);
915 break;
921 if (IsSavegameVersionBefore(SLV_INCREASE_STATION_TYPE_FIELD_SIZE)) {
922 /* Expansion of station type field in m6 */
923 for (auto t : Map::Iterate()) {
924 if (IsTileType(t, MP_STATION)) {
925 ClrBit(t.m6(), 6);
930 for (auto t : Map::Iterate()) {
931 switch (GetTileType(t)) {
932 case MP_STATION: {
933 BaseStation *bst = BaseStation::GetByTile(t);
935 /* Sanity check */
936 if (!IsBuoy(t) && bst->owner != GetTileOwner(t)) SlErrorCorrupt("Wrong owner for station tile");
938 /* Set up station spread */
939 bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
941 /* Waypoints don't have road stops/oil rigs in the old format */
942 if (!Station::IsExpected(bst)) break;
943 Station *st = Station::From(bst);
945 switch (GetStationType(t)) {
946 case STATION_TRUCK:
947 case STATION_BUS:
948 if (IsSavegameVersionBefore(SLV_6)) {
949 /* Before version 5 you could not have more than 250 stations.
950 * Version 6 adds large maps, so you could only place 253*253
951 * road stops on a map (no freeform edges) = 64009. So, yes
952 * someone could in theory create such a full map to trigger
953 * this assertion, it's safe to assume that's only something
954 * theoretical and does not happen in normal games. */
955 assert(RoadStop::CanAllocateItem());
957 /* From this version on there can be multiple road stops of the
958 * same type per station. Convert the existing stops to the new
959 * internal data structure. */
960 RoadStop *rs = new RoadStop(t);
962 RoadStop **head =
963 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
964 *head = rs;
966 break;
968 case STATION_OILRIG: {
969 /* The internal encoding of oil rigs was changed twice.
970 * It was 3 (till 2.2) and later 5 (till 5.1).
971 * DeleteOilRig asserts on the correct type, and
972 * setting it unconditionally does not hurt.
974 Station::GetByTile(t)->airport.type = AT_OILRIG;
976 /* Very old savegames sometimes have phantom oil rigs, i.e.
977 * an oil rig which got shut down, but not completely removed from
978 * the map
980 TileIndex t1 = TileAddXY(t, 0, 1);
981 if (!IsTileType(t1, MP_INDUSTRY) || GetIndustryGfx(t1) != GFX_OILRIG_1) {
982 DeleteOilRig(t);
984 break;
987 default: break;
989 break;
992 default: break;
996 /* In version 6.1 we put the town index in the map-array. To do this, we need
997 * to use m2 (16bit big), so we need to clean m2, and that is where this is
998 * all about ;) */
999 if (IsSavegameVersionBefore(SLV_6, 1)) {
1000 for (auto t : Map::Iterate()) {
1001 switch (GetTileType(t)) {
1002 case MP_HOUSE:
1003 t.m4() = t.m2();
1004 SetTownIndex(t, CalcClosestTownFromTile(t)->index);
1005 break;
1007 case MP_ROAD:
1008 t.m4() |= (t.m2() << 4);
1009 if ((GB(t.m5(), 4, 2) == ROAD_TILE_CROSSING ? (Owner)t.m3() : GetTileOwner(t)) == OWNER_TOWN) {
1010 SetTownIndex(t, CalcClosestTownFromTile(t)->index);
1011 } else {
1012 SetTownIndex(t, 0);
1014 break;
1016 default: break;
1021 /* Force the freeform edges to false for old savegames. */
1022 if (IsSavegameVersionBefore(SLV_111)) {
1023 _settings_game.construction.freeform_edges = false;
1026 /* From version 9.0, we update the max passengers of a town (was sometimes negative
1027 * before that. */
1028 if (IsSavegameVersionBefore(SLV_9)) {
1029 for (Town *t : Town::Iterate()) UpdateTownMaxPass(t);
1032 /* From version 16.0, we included autorenew on engines, which are now saved, but
1033 * of course, we do need to initialize them for older savegames. */
1034 if (IsSavegameVersionBefore(SLV_16)) {
1035 for (Company *c : Company::Iterate()) {
1036 c->engine_renew_list = nullptr;
1037 c->settings.engine_renew = false;
1038 c->settings.engine_renew_months = 6;
1039 c->settings.engine_renew_money = 100000;
1042 /* When loading a game, _local_company is not yet set to the correct value.
1043 * However, in a dedicated server we are a spectator, so nothing needs to
1044 * happen. In case we are not a dedicated server, the local company always
1045 * becomes the first available company, unless we are in the scenario editor
1046 * where all the companies are 'invalid'.
1048 Company *c = Company::GetIfValid(GetFirstPlayableCompanyID());
1049 if (!_network_dedicated && c != nullptr) {
1050 c->settings = _settings_client.company;
1054 if (IsSavegameVersionBefore(SLV_48)) {
1055 for (auto t : Map::Iterate()) {
1056 switch (GetTileType(t)) {
1057 case MP_RAILWAY:
1058 if (IsPlainRail(t)) {
1059 /* Swap ground type and signal type for plain rail tiles, so the
1060 * ground type uses the same bits as for depots and waypoints. */
1061 uint tmp = GB(t.m4(), 0, 4);
1062 SB(t.m4(), 0, 4, GB(t.m2(), 0, 4));
1063 SB(t.m2(), 0, 4, tmp);
1064 } else if (HasBit(t.m5(), 2)) {
1065 /* Split waypoint and depot rail type and remove the subtype. */
1066 ClrBit(t.m5(), 2);
1067 ClrBit(t.m5(), 6);
1069 break;
1071 case MP_ROAD:
1072 /* Swap m3 and m4, so the track type for rail crossings is the
1073 * same as for normal rail. */
1074 Swap(t.m3(), t.m4());
1075 break;
1077 default: break;
1082 if (IsSavegameVersionBefore(SLV_61)) {
1083 /* Added the RoadType */
1084 bool old_bridge = IsSavegameVersionBefore(SLV_42);
1085 for (auto t : Map::Iterate()) {
1086 switch (GetTileType(t)) {
1087 case MP_ROAD:
1088 SB(t.m5(), 6, 2, GB(t.m5(), 4, 2));
1089 switch (GetRoadTileType(t)) {
1090 default: SlErrorCorrupt("Invalid road tile type");
1091 case ROAD_TILE_NORMAL:
1092 SB(t.m4(), 0, 4, GB(t.m5(), 0, 4));
1093 SB(t.m4(), 4, 4, 0);
1094 SB(t.m6(), 2, 4, 0);
1095 break;
1096 case ROAD_TILE_CROSSING:
1097 SB(t.m4(), 5, 2, GB(t.m5(), 2, 2));
1098 break;
1099 case ROAD_TILE_DEPOT: break;
1101 SB(t.m7(), 6, 2, 1); // Set pre-NRT road type bits for conversion later.
1102 break;
1104 case MP_STATION:
1105 if (IsStationRoadStop(t)) SB(t.m7(), 6, 2, 1);
1106 break;
1108 case MP_TUNNELBRIDGE:
1109 /* Middle part of "old" bridges */
1110 if (old_bridge && IsBridge(t) && HasBit(t.m5(), 6)) break;
1111 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(t.m5(), 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1112 SB(t.m7(), 6, 2, 1); // Set pre-NRT road type bits for conversion later.
1114 break;
1116 default: break;
1121 if (IsSavegameVersionBefore(SLV_114)) {
1122 bool fix_roadtypes = !IsSavegameVersionBefore(SLV_61);
1123 bool old_bridge = IsSavegameVersionBefore(SLV_42);
1125 for (auto t : Map::Iterate()) {
1126 switch (GetTileType(t)) {
1127 case MP_ROAD:
1128 if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m7(), 5, 3));
1129 SB(t.m7(), 5, 1, GB(t.m3(), 7, 1)); // snow/desert
1130 switch (GetRoadTileType(t)) {
1131 default: SlErrorCorrupt("Invalid road tile type");
1132 case ROAD_TILE_NORMAL:
1133 SB(t.m7(), 0, 4, GB(t.m3(), 0, 4)); // road works
1134 SB(t.m6(), 3, 3, GB(t.m3(), 4, 3)); // ground
1135 SB(t.m3(), 0, 4, GB(t.m4(), 4, 4)); // tram bits
1136 SB(t.m3(), 4, 4, GB(t.m5(), 0, 4)); // tram owner
1137 SB(t.m5(), 0, 4, GB(t.m4(), 0, 4)); // road bits
1138 break;
1140 case ROAD_TILE_CROSSING:
1141 SB(t.m7(), 0, 5, GB(t.m4(), 0, 5)); // road owner
1142 SB(t.m6(), 3, 3, GB(t.m3(), 4, 3)); // ground
1143 SB(t.m3(), 4, 4, GB(t.m5(), 0, 4)); // tram owner
1144 SB(t.m5(), 0, 1, GB(t.m4(), 6, 1)); // road axis
1145 SB(t.m5(), 5, 1, GB(t.m4(), 5, 1)); // crossing state
1146 break;
1148 case ROAD_TILE_DEPOT:
1149 break;
1151 if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1152 const Town *town = CalcClosestTownFromTile(t);
1153 if (town != nullptr) SetTownIndex(t, town->index);
1155 t.m4() = 0;
1156 break;
1158 case MP_STATION:
1159 if (!IsStationRoadStop(t)) break;
1161 if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m3(), 0, 3));
1162 SB(t.m7(), 0, 5, HasBit(t.m6(), 2) ? OWNER_TOWN : GetTileOwner(t));
1163 SB(t.m3(), 4, 4, t.m1());
1164 t.m4() = 0;
1165 break;
1167 case MP_TUNNELBRIDGE:
1168 if (old_bridge && IsBridge(t) && HasBit(t.m5(), 6)) break;
1169 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(t.m5(), 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1170 if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m3(), 0, 3));
1172 Owner o = GetTileOwner(t);
1173 SB(t.m7(), 0, 5, o); // road owner
1174 SB(t.m3(), 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
1176 SB(t.m6(), 2, 4, GB(t.m2(), 4, 4)); // bridge type
1177 SB(t.m7(), 5, 1, GB(t.m4(), 7, 1)); // snow/desert
1179 t.m2() = 0;
1180 t.m4() = 0;
1181 break;
1183 default: break;
1188 /* Railtype moved from m3 to m8 in version SLV_EXTEND_RAILTYPES. */
1189 if (IsSavegameVersionBefore(SLV_EXTEND_RAILTYPES)) {
1190 for (auto t : Map::Iterate()) {
1191 switch (GetTileType(t)) {
1192 case MP_RAILWAY:
1193 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1194 break;
1196 case MP_ROAD:
1197 if (IsLevelCrossing(t)) {
1198 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1200 break;
1202 case MP_STATION:
1203 if (HasStationRail(t)) {
1204 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1206 break;
1208 case MP_TUNNELBRIDGE:
1209 if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
1210 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1212 break;
1214 default:
1215 break;
1220 if (IsSavegameVersionBefore(SLV_42)) {
1221 for (auto t : Map::Iterate()) {
1222 if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
1223 if (IsBridgeTile(t)) {
1224 if (HasBit(t.m5(), 6)) { // middle part
1225 Axis axis = (Axis)GB(t.m5(), 0, 1);
1227 if (HasBit(t.m5(), 5)) { // transport route under bridge?
1228 if (GB(t.m5(), 3, 2) == TRANSPORT_RAIL) {
1229 MakeRailNormal(
1231 GetTileOwner(t),
1232 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
1233 GetRailType(t)
1235 } else {
1236 TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
1238 /* MakeRoadNormal */
1239 SetTileType(t, MP_ROAD);
1240 t.m2() = town;
1241 t.m3() = 0;
1242 t.m5() = (axis == AXIS_X ? ROAD_Y : ROAD_X) | ROAD_TILE_NORMAL << 6;
1243 SB(t.m6(), 2, 4, 0);
1244 t.m7() = 1 << 6;
1245 SetRoadOwner(t, RTT_TRAM, OWNER_NONE);
1247 } else {
1248 if (GB(t.m5(), 3, 2) == 0) {
1249 MakeClear(t, CLEAR_GRASS, 3);
1250 } else {
1251 if (!IsTileFlat(t)) {
1252 MakeShore(t);
1253 } else {
1254 if (GetTileOwner(t) == OWNER_WATER) {
1255 MakeSea(t);
1256 } else {
1257 MakeCanal(t, GetTileOwner(t), Random());
1262 SetBridgeMiddle(t, axis);
1263 } else { // ramp
1264 Axis axis = (Axis)GB(t.m5(), 0, 1);
1265 uint north_south = GB(t.m5(), 5, 1);
1266 DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
1267 TransportType type = (TransportType)GB(t.m5(), 1, 2);
1269 t.m5() = 1 << 7 | type << 2 | dir;
1274 for (Vehicle *v : Vehicle::Iterate()) {
1275 if (!v->IsGroundVehicle()) continue;
1276 if (IsBridgeTile(v->tile)) {
1277 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
1279 if (dir != DirToDiagDir(v->direction)) continue;
1280 switch (dir) {
1281 default: SlErrorCorrupt("Invalid vehicle direction");
1282 case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
1283 case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
1284 case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
1285 case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
1287 } else if (v->z_pos > GetTileMaxPixelZ(TileVirtXY(v->x_pos, v->y_pos))) {
1288 v->tile = GetNorthernBridgeEnd(v->tile);
1289 v->UpdatePosition();
1290 } else {
1291 continue;
1293 if (v->type == VEH_TRAIN) {
1294 Train::From(v)->track = TRACK_BIT_WORMHOLE;
1295 } else {
1296 RoadVehicle::From(v)->state = RVSB_WORMHOLE;
1301 if (IsSavegameVersionBefore(SLV_ROAD_TYPES)) {
1302 /* Add road subtypes */
1303 for (auto t : Map::Iterate()) {
1304 bool has_road = false;
1305 switch (GetTileType(t)) {
1306 case MP_ROAD:
1307 has_road = true;
1308 break;
1309 case MP_STATION:
1310 has_road = IsAnyRoadStop(t);
1311 break;
1312 case MP_TUNNELBRIDGE:
1313 has_road = GetTunnelBridgeTransportType(t) == TRANSPORT_ROAD;
1314 break;
1315 default:
1316 break;
1319 if (has_road) {
1320 RoadType road_rt = HasBit(t.m7(), 6) ? ROADTYPE_ROAD : INVALID_ROADTYPE;
1321 RoadType tram_rt = HasBit(t.m7(), 7) ? ROADTYPE_TRAM : INVALID_ROADTYPE;
1323 assert(road_rt != INVALID_ROADTYPE || tram_rt != INVALID_ROADTYPE);
1324 SetRoadTypes(t, road_rt, tram_rt);
1325 SB(t.m7(), 6, 2, 0); // Clear pre-NRT road type bits.
1330 /* Elrails got added in rev 24 */
1331 if (IsSavegameVersionBefore(SLV_24)) {
1332 RailType min_rail = RAILTYPE_ELECTRIC;
1334 for (Train *v : Train::Iterate()) {
1335 RailType rt = RailVehInfo(v->engine_type)->railtype;
1337 v->railtype = rt;
1338 if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
1341 /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
1342 for (auto t : Map::Iterate()) {
1343 switch (GetTileType(t)) {
1344 case MP_RAILWAY:
1345 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1346 break;
1348 case MP_ROAD:
1349 if (IsLevelCrossing(t)) {
1350 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1352 break;
1354 case MP_STATION:
1355 if (HasStationRail(t)) {
1356 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1358 break;
1360 case MP_TUNNELBRIDGE:
1361 if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
1362 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1364 break;
1366 default:
1367 break;
1372 /* In version 16.1 of the savegame a company can decide if trains, which get
1373 * replaced, shall keep their old length. In all prior versions, just default
1374 * to false */
1375 if (IsSavegameVersionBefore(SLV_16, 1)) {
1376 for (Company *c : Company::Iterate()) c->settings.renew_keep_length = false;
1379 if (IsSavegameVersionBefore(SLV_123)) {
1380 /* Waypoints became subclasses of stations ... */
1381 MoveWaypointsToBaseStations();
1382 /* ... and buoys were moved to waypoints. */
1383 MoveBuoysToWaypoints();
1386 /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
1387 * room for PBS. Now in version 21 move it back :P. */
1388 if (IsSavegameVersionBefore(SLV_21) && !IsSavegameVersionBefore(SLV_15)) {
1389 for (auto t : Map::Iterate()) {
1390 switch (GetTileType(t)) {
1391 case MP_RAILWAY:
1392 if (HasSignals(t)) {
1393 /* Original signal type/variant was stored in m4 but since saveload
1394 * version 48 they are in m2. The bits has been already moved to m2
1395 * (see the code somewhere above) so don't use m4, use m2 instead. */
1397 /* convert PBS signals to combo-signals */
1398 if (HasBit(t.m2(), 2)) SB(t.m2(), 0, 2, SIGTYPE_COMBO);
1400 /* move the signal variant back */
1401 SB(t.m2(), 2, 1, HasBit(t.m2(), 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1402 ClrBit(t.m2(), 3);
1405 /* Clear PBS reservation on track */
1406 if (!IsRailDepotTile(t)) {
1407 SB(t.m4(), 4, 4, 0);
1408 } else {
1409 ClrBit(t.m3(), 6);
1411 break;
1413 case MP_STATION: // Clear PBS reservation on station
1414 ClrBit(t.m3(), 6);
1415 break;
1417 default: break;
1422 if (IsSavegameVersionBefore(SLV_25)) {
1423 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
1424 rv->vehstatus &= ~0x40;
1428 if (IsSavegameVersionBefore(SLV_26)) {
1429 for (Station *st : Station::Iterate()) {
1430 st->last_vehicle_type = VEH_INVALID;
1434 YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
1436 if (IsSavegameVersionBefore(SLV_34)) {
1437 for (Company *c : Company::Iterate()) ResetCompanyLivery(c);
1440 for (Company *c : Company::Iterate()) {
1441 c->avail_railtypes = GetCompanyRailTypes(c->index);
1442 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
1445 AfterLoadStations();
1447 /* Time starts at 0 instead of 1920.
1448 * Account for this in older games by adding an offset */
1449 if (IsSavegameVersionBefore(SLV_31)) {
1450 TimerGameCalendar::date += CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1451 TimerGameCalendar::year += CalendarTime::ORIGINAL_BASE_YEAR;
1452 TimerGameEconomy::date += EconomyTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1453 TimerGameEconomy::year += EconomyTime::ORIGINAL_BASE_YEAR;
1455 for (Station *st : Station::Iterate()) st->build_date += CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1456 for (Waypoint *wp : Waypoint::Iterate()) wp->build_date += CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1457 for (Engine *e : Engine::Iterate()) e->intro_date += CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1458 for (Company *c : Company::Iterate()) c->inaugurated_year += EconomyTime::ORIGINAL_BASE_YEAR;
1459 for (Industry *i : Industry::Iterate()) i->last_prod_year += EconomyTime::ORIGINAL_BASE_YEAR;
1461 for (Vehicle *v : Vehicle::Iterate()) {
1462 v->date_of_last_service += EconomyTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1463 v->build_year += CalendarTime::ORIGINAL_BASE_YEAR;
1467 /* From 32 on we save the industry who made the farmland.
1468 * To give this prettiness to old savegames, we remove all farmfields and
1469 * plant new ones. */
1470 if (IsSavegameVersionBefore(SLV_32)) {
1471 for (auto t : Map::Iterate()) {
1472 if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
1473 /* remove fields */
1474 MakeClear(t, CLEAR_GRASS, 3);
1478 for (Industry *i : Industry::Iterate()) {
1479 uint j;
1481 if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
1482 for (j = 0; j != 50; j++) PlantRandomFarmField(i);
1487 /* Setting no refit flags to all orders in savegames from before refit in orders were added */
1488 if (IsSavegameVersionBefore(SLV_36)) {
1489 for (Order *order : Order::Iterate()) {
1490 order->SetRefit(CARGO_NO_REFIT);
1493 for (Vehicle *v : Vehicle::Iterate()) {
1494 v->current_order.SetRefit(CARGO_NO_REFIT);
1498 /* from version 38 we have optional elrails, since we cannot know the
1499 * preference of a user, let elrails enabled; it can be disabled manually */
1500 if (IsSavegameVersionBefore(SLV_38)) _settings_game.vehicle.disable_elrails = false;
1501 /* do the same as when elrails were enabled/disabled manually just now */
1502 UpdateDisableElrailSettingState(_settings_game.vehicle.disable_elrails, false);
1503 InitializeRailGUI();
1505 /* From version 53, the map array was changed for house tiles to allow
1506 * space for newhouses grf features. A new byte, m7, was also added. */
1507 if (IsSavegameVersionBefore(SLV_53)) {
1508 for (auto t : Map::Iterate()) {
1509 if (IsTileType(t, MP_HOUSE)) {
1510 if (GB(t.m3(), 6, 2) != TOWN_HOUSE_COMPLETED) {
1511 /* Move the construction stage from m3[7..6] to m5[5..4].
1512 * The construction counter does not have to move. */
1513 SB(t.m5(), 3, 2, GB(t.m3(), 6, 2));
1514 SB(t.m3(), 6, 2, 0);
1516 /* The "house is completed" bit is now in m6[2]. */
1517 SetHouseCompleted(t, false);
1518 } else {
1519 /* The "lift has destination" bit has been moved from
1520 * m5[7] to m7[0]. */
1521 AssignBit(t.m7(), 0, HasBit(t.m5(), 7));
1522 ClrBit(t.m5(), 7);
1524 /* The "lift is moving" bit has been removed, as it does
1525 * the same job as the "lift has destination" bit. */
1526 ClrBit(t.m1(), 7);
1528 /* The position of the lift goes from m1[7..0] to m6[7..2],
1529 * making m1 totally free, now. The lift position does not
1530 * have to be a full byte since the maximum value is 36. */
1531 SetLiftPosition(t, GB(t.m1(), 0, 6 ));
1533 t.m1() = 0;
1534 t.m3() = 0;
1535 SetHouseCompleted(t, true);
1541 /* Check and update house and town values */
1542 UpdateHousesAndTowns();
1544 if (IsSavegameVersionBefore(SLV_43)) {
1545 for (auto t : Map::Iterate()) {
1546 if (IsTileType(t, MP_INDUSTRY)) {
1547 switch (GetIndustryGfx(t)) {
1548 case GFX_POWERPLANT_SPARKS:
1549 t.m3() = GB(t.m1(), 2, 5);
1550 break;
1552 case GFX_OILWELL_ANIMATED_1:
1553 case GFX_OILWELL_ANIMATED_2:
1554 case GFX_OILWELL_ANIMATED_3:
1555 t.m3() = GB(t.m1(), 0, 2);
1556 break;
1558 case GFX_COAL_MINE_TOWER_ANIMATED:
1559 case GFX_COPPER_MINE_TOWER_ANIMATED:
1560 case GFX_GOLD_MINE_TOWER_ANIMATED:
1561 t.m3() = t.m1();
1562 break;
1564 default: // No animation states to change
1565 break;
1571 if (IsSavegameVersionBefore(SLV_45)) {
1572 /* Originally just the fact that some cargo had been paid for was
1573 * stored to stop people cheating and cashing in several times. This
1574 * wasn't enough though as it was cleared when the vehicle started
1575 * loading again, even if it didn't actually load anything, so now the
1576 * amount that has been paid is stored. */
1577 for (Vehicle *v : Vehicle::Iterate()) {
1578 ClrBit(v->vehicle_flags, 2);
1582 /* Buoys do now store the owner of the previous water tile, which can never
1583 * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
1584 if (IsSavegameVersionBefore(SLV_46)) {
1585 for (Waypoint *wp : Waypoint::Iterate()) {
1586 if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
1590 if (IsSavegameVersionBefore(SLV_50)) {
1591 /* Aircraft units changed from 8 mph to 1 km-ish/h */
1592 for (Aircraft *v : Aircraft::Iterate()) {
1593 if (v->subtype <= AIR_AIRCRAFT) {
1594 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
1595 v->cur_speed *= 128;
1596 v->cur_speed /= 10;
1597 v->acceleration = avi->acceleration;
1602 if (IsSavegameVersionBefore(SLV_49)) for (Company *c : Company::Iterate()) c->face = ConvertFromOldCompanyManagerFace(c->face);
1604 if (IsSavegameVersionBefore(SLV_52)) {
1605 for (auto t : Map::Iterate()) {
1606 if (IsTileType(t, MP_OBJECT) && t.m5() == OBJECT_STATUE) {
1607 t.m2() = CalcClosestTownFromTile(t)->index;
1612 /* A setting containing the proportion of towns that grow twice as
1613 * fast was added in version 54. From version 56 this is now saved in the
1614 * town as cities can be built specifically in the scenario editor. */
1615 if (IsSavegameVersionBefore(SLV_56)) {
1616 for (Town *t : Town::Iterate()) {
1617 if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
1618 t->larger_town = true;
1623 if (IsSavegameVersionBefore(SLV_57)) {
1624 /* Added a FIFO queue of vehicles loading at stations */
1625 for (Vehicle *v : Vehicle::Iterate()) {
1626 if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) && // for all locs
1627 !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
1628 v->current_order.IsType(OT_LOADING)) { // loading
1629 Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
1631 /* The loading finished flag is *only* set when actually completely
1632 * finished. Because the vehicle is loading, it is not finished. */
1633 ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
1636 } else if (IsSavegameVersionBefore(SLV_59)) {
1637 /* For some reason non-loading vehicles could be in the station's loading vehicle list */
1639 for (Station *st : Station::Iterate()) {
1640 for (auto iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); /* nothing */) {
1641 Vehicle *v = *iter;
1642 if (!v->current_order.IsType(OT_LOADING)) {
1643 iter = st->loading_vehicles.erase(iter);
1644 } else {
1645 ++iter;
1651 if (IsSavegameVersionBefore(SLV_58)) {
1652 /* Setting difficulty industry_density other than zero get bumped to +1
1653 * since a new option (very low at position 1) has been added */
1654 if (_settings_game.difficulty.industry_density > 0) {
1655 _settings_game.difficulty.industry_density++;
1658 /* Same goes for number of towns, although no test is needed, just an increment */
1659 _settings_game.difficulty.number_towns++;
1662 if (IsSavegameVersionBefore(SLV_64)) {
1663 /* Since now we allow different signal types and variants on a single tile.
1664 * Move signal states to m4 to make room and clone the signal type/variant. */
1665 for (auto t : Map::Iterate()) {
1666 if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
1667 /* move signal states */
1668 SetSignalStates(t, GB(t.m2(), 4, 4));
1669 SB(t.m2(), 4, 4, 0);
1670 /* clone signal type and variant */
1671 SB(t.m2(), 4, 3, GB(t.m2(), 0, 3));
1676 if (IsSavegameVersionBefore(SLV_69)) {
1677 /* In some old savegames a bit was cleared when it should not be cleared */
1678 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
1679 if (rv->state == 250 || rv->state == 251) {
1680 SetBit(rv->state, 2);
1685 if (IsSavegameVersionBefore(SLV_70)) {
1686 /* Added variables to support newindustries */
1687 for (Industry *i : Industry::Iterate()) i->founder = OWNER_NONE;
1690 /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
1691 Replace the owner for those by OWNER_NONE. */
1692 if (IsSavegameVersionBefore(SLV_82)) {
1693 for (auto t : Map::Iterate()) {
1694 if (IsTileType(t, MP_WATER) &&
1695 GetWaterTileType(t) == WATER_TILE_CLEAR &&
1696 GetTileOwner(t) == OWNER_WATER &&
1697 TileHeight(t) != 0) {
1698 SetTileOwner(t, OWNER_NONE);
1704 * Add the 'previous' owner to the ship depots so we can reset it with
1705 * the correct values when it gets destroyed. This prevents that
1706 * someone can remove canals owned by somebody else and it prevents
1707 * making floods using the removal of ship depots.
1709 if (IsSavegameVersionBefore(SLV_83)) {
1710 for (auto t : Map::Iterate()) {
1711 if (IsShipDepotTile(t)) {
1712 t.m4() = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
1717 if (IsSavegameVersionBefore(SLV_74)) {
1718 for (Station *st : Station::Iterate()) {
1719 for (GoodsEntry &ge : st->goods) {
1720 ge.last_speed = 0;
1721 if (ge.cargo.AvailableCount() != 0) SetBit(ge.status, GoodsEntry::GES_RATING);
1726 /* At version 78, industry cargo types can be changed, and are stored with the industry. For older save versions
1727 * copy the IndustrySpec's cargo types over to the Industry. */
1728 if (IsSavegameVersionBefore(SLV_78)) {
1729 for (Industry *i : Industry::Iterate()) {
1730 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1731 for (uint j = 0; j < std::size(i->produced); j++) {
1732 i->produced[j].cargo = indsp->produced_cargo[j];
1734 for (uint j = 0; j < std::size(i->accepted); j++) {
1735 i->accepted[j].cargo = indsp->accepts_cargo[j];
1740 /* Industry cargo slots were fixed size before (and including) SLV_VEHICLE_ECONOMY_AGE (either 2/3 or 16/16),
1741 * after this they are dynamic. Trim excess slots. */
1742 if (IsSavegameVersionBeforeOrAt(SLV_VEHICLE_ECONOMY_AGE)) {
1743 for (Industry *i : Industry::Iterate()) {
1744 TrimIndustryAcceptedProduced(i);
1748 /* Before version 81, the density of grass was always stored as zero, and
1749 * grassy trees were always drawn fully grassy. Furthermore, trees on rough
1750 * land used to have zero density, now they have full density. Therefore,
1751 * make all grassy/rough land trees have a density of 3. */
1752 if (IsSavegameVersionBefore(SLV_81)) {
1753 for (auto t : Map::Iterate()) {
1754 if (GetTileType(t) == MP_TREES) {
1755 TreeGround groundType = (TreeGround)GB(t.m2(), 4, 2);
1756 if (groundType != TREE_GROUND_SNOW_DESERT) SB(t.m2(), 6, 2, 3);
1762 if (IsSavegameVersionBefore(SLV_93)) {
1763 /* Rework of orders. */
1764 for (Order *order : Order::Iterate()) order->ConvertFromOldSavegame();
1766 for (Vehicle *v : Vehicle::Iterate()) {
1767 if (v->orders != nullptr && v->orders->GetFirstOrder() != nullptr && v->orders->GetFirstOrder()->IsType(OT_NOTHING)) {
1768 v->orders->FreeChain();
1769 v->orders = nullptr;
1772 v->current_order.ConvertFromOldSavegame();
1773 if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
1774 for (Order *order : v->Orders()) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
1777 } else if (IsSavegameVersionBefore(SLV_94)) {
1778 /* Unload and transfer are now mutual exclusive. */
1779 for (Order *order : Order::Iterate()) {
1780 if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1781 order->SetUnloadType(OUFB_TRANSFER);
1782 order->SetLoadType(OLFB_NO_LOAD);
1786 for (Vehicle *v : Vehicle::Iterate()) {
1787 if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1788 v->current_order.SetUnloadType(OUFB_TRANSFER);
1789 v->current_order.SetLoadType(OLFB_NO_LOAD);
1792 } else if (IsSavegameVersionBefore(SLV_DEPOT_UNBUNCHING)) {
1793 /* OrderDepotActionFlags were moved, instead of starting at bit 4 they now start at bit 3. */
1794 for (Order *order : Order::Iterate()) {
1795 if (!order->IsType(OT_GOTO_DEPOT)) continue;
1796 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() >> 1));
1799 for (Vehicle *v : Vehicle::Iterate()) {
1800 if (!v->current_order.IsType(OT_GOTO_DEPOT)) continue;
1801 v->current_order.SetDepotActionType((OrderDepotActionFlags)(v->current_order.GetDepotActionType() >> 1));
1805 /* The water class was moved/unified. */
1806 if (IsSavegameVersionBefore(SLV_146)) {
1807 for (auto t : Map::Iterate()) {
1808 switch (GetTileType(t)) {
1809 case MP_STATION:
1810 switch (GetStationType(t)) {
1811 case STATION_OILRIG:
1812 case STATION_DOCK:
1813 case STATION_BUOY:
1814 SetWaterClass(t, (WaterClass)GB(t.m3(), 0, 2));
1815 SB(t.m3(), 0, 2, 0);
1816 break;
1818 default:
1819 SetWaterClass(t, WATER_CLASS_INVALID);
1820 break;
1822 break;
1824 case MP_WATER:
1825 SetWaterClass(t, (WaterClass)GB(t.m3(), 0, 2));
1826 SB(t.m3(), 0, 2, 0);
1827 break;
1829 case MP_OBJECT:
1830 SetWaterClass(t, WATER_CLASS_INVALID);
1831 break;
1833 default:
1834 /* No water class. */
1835 break;
1840 if (IsSavegameVersionBefore(SLV_86)) {
1841 for (auto t : Map::Iterate()) {
1842 /* Move river flag and update canals to use water class */
1843 if (IsTileType(t, MP_WATER)) {
1844 if (GetWaterClass(t) != WATER_CLASS_RIVER) {
1845 if (IsWater(t)) {
1846 Owner o = GetTileOwner(t);
1847 if (o == OWNER_WATER) {
1848 MakeSea(t);
1849 } else {
1850 MakeCanal(t, o, Random());
1852 } else if (IsShipDepot(t)) {
1853 Owner o = (Owner)t.m4(); // Original water owner
1854 SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
1860 /* Update locks, depots, docks and buoys to have a water class based
1861 * on its neighbouring tiles. Done after river and canal updates to
1862 * ensure neighbours are correct. */
1863 for (auto t : Map::Iterate()) {
1864 if (!IsTileFlat(t)) continue;
1866 if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
1867 if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
1871 if (IsSavegameVersionBefore(SLV_87)) {
1872 for (auto t : Map::Iterate()) {
1873 /* skip oil rigs at borders! */
1874 if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
1875 (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == Map::MaxX() - 1 || TileY(t) == Map::MaxY() - 1)) {
1876 /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
1877 * This conversion has to be done before buoys with invalid owner are removed. */
1878 SetWaterClass(t, WATER_CLASS_SEA);
1881 if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
1882 Owner o = GetTileOwner(t);
1883 if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
1884 Backup<CompanyID> cur_company(_current_company, o);
1885 ChangeTileOwner(t, o, INVALID_OWNER);
1886 cur_company.Restore();
1888 if (IsBuoyTile(t)) {
1889 /* reset buoy owner to OWNER_NONE in the station struct
1890 * (even if it is owned by active company) */
1891 Waypoint::GetByTile(t)->owner = OWNER_NONE;
1893 } else if (IsTileType(t, MP_ROAD)) {
1894 /* works for all RoadTileType */
1895 for (RoadTramType rtt : _roadtramtypes) {
1896 /* update even non-existing road types to update tile owner too */
1897 Owner o = GetRoadOwner(t, rtt);
1898 if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rtt, OWNER_NONE);
1900 if (IsLevelCrossing(t)) {
1901 if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
1903 } else if (IsPlainRailTile(t)) {
1904 if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
1909 if (IsSavegameVersionBefore(SLV_88)) {
1910 /* Profits are now with 8 bit fract */
1911 for (Vehicle *v : Vehicle::Iterate()) {
1912 v->profit_this_year <<= 8;
1913 v->profit_last_year <<= 8;
1914 v->running_ticks = 0;
1918 if (IsSavegameVersionBefore(SLV_91)) {
1919 /* Increase HouseAnimationFrame from 5 to 7 bits */
1920 for (auto t : Map::Iterate()) {
1921 if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
1922 SB(t.m6(), 2, 6, GB(t.m6(), 3, 5));
1923 SB(t.m3(), 5, 1, 0);
1928 if (IsSavegameVersionBefore(SLV_62)) {
1929 GroupStatistics::UpdateAfterLoad(); // Ensure statistics pool is initialised before trying to delete vehicles
1930 /* Remove all trams from savegames without tram support.
1931 * There would be trams without tram track under causing crashes sooner or later. */
1932 for (RoadVehicle *v : RoadVehicle::Iterate()) {
1933 if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
1934 ShowErrorMessage(STR_WARNING_LOADGAME_REMOVED_TRAMS, INVALID_STRING_ID, WL_CRITICAL);
1935 delete v;
1940 if (IsSavegameVersionBefore(SLV_99)) {
1941 for (auto t : Map::Iterate()) {
1942 /* Set newly introduced WaterClass of industry tiles */
1943 if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
1944 SetWaterClassDependingOnSurroundings(t, true);
1946 if (IsTileType(t, MP_INDUSTRY)) {
1947 if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
1948 SetWaterClassDependingOnSurroundings(t, true);
1949 } else {
1950 SetWaterClass(t, WATER_CLASS_INVALID);
1954 /* Replace "house construction year" with "house age" */
1955 if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
1956 t.m5() = ClampTo<uint8_t>(TimerGameCalendar::year - (t.m5() + CalendarTime::ORIGINAL_BASE_YEAR));
1961 /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
1962 * format here, as an old layout wouldn't work properly anyway. To be safe, we
1963 * clear any possible PBS reservations as well. */
1964 if (IsSavegameVersionBefore(SLV_100)) {
1965 for (auto t : Map::Iterate()) {
1966 switch (GetTileType(t)) {
1967 case MP_RAILWAY:
1968 if (HasSignals(t)) {
1969 /* move the signal variant */
1970 SetSignalVariant(t, TRACK_UPPER, HasBit(t.m2(), 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1971 SetSignalVariant(t, TRACK_LOWER, HasBit(t.m2(), 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1972 ClrBit(t.m2(), 2);
1973 ClrBit(t.m2(), 6);
1976 /* Clear PBS reservation on track */
1977 if (IsRailDepot(t)) {
1978 SetDepotReservation(t, false);
1979 } else {
1980 SetTrackReservation(t, TRACK_BIT_NONE);
1982 break;
1984 case MP_ROAD: // Clear PBS reservation on crossing
1985 if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
1986 break;
1988 case MP_STATION: // Clear PBS reservation on station
1989 if (HasStationRail(t)) SetRailStationReservation(t, false);
1990 break;
1992 case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/bridges
1993 if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
1994 break;
1996 default: break;
2001 /* Reserve all tracks trains are currently on. */
2002 if (IsSavegameVersionBefore(SLV_101)) {
2003 for (const Train *t : Train::Iterate()) {
2004 if (t->First() == t) t->ReserveTrackUnderConsist();
2008 if (IsSavegameVersionBefore(SLV_103)) {
2009 /* Non-town-owned roads now store the closest town */
2010 UpdateNearestTownForRoadTiles(false);
2012 /* signs with invalid owner left from older savegames */
2013 for (Sign *si : Sign::Iterate()) {
2014 if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
2017 /* Station can get named based on an industry type, but the current ones
2018 * are not, so mark them as if they are not named by an industry. */
2019 for (Station *st : Station::Iterate()) {
2020 st->indtype = IT_INVALID;
2024 if (IsSavegameVersionBefore(SLV_104)) {
2025 for (Aircraft *a : Aircraft::Iterate()) {
2026 /* Set engine_type of shadow and rotor */
2027 if (!a->IsNormalAircraft()) {
2028 a->engine_type = a->First()->engine_type;
2032 /* More companies ... */
2033 for (Company *c : Company::Iterate()) {
2034 if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = MAX_UVALUE(CompanyMask);
2037 for (Engine *e : Engine::Iterate()) {
2038 if (e->company_avail == 0xFF) e->company_avail = MAX_UVALUE(CompanyMask);
2041 for (Town *t : Town::Iterate()) {
2042 if (t->have_ratings == 0xFF) t->have_ratings = MAX_UVALUE(CompanyMask);
2043 for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
2047 if (IsSavegameVersionBefore(SLV_112)) {
2048 for (auto t : Map::Iterate()) {
2049 /* Check for HQ bit being set, instead of using map accessor,
2050 * since we've already changed it code-wise */
2051 if (IsTileType(t, MP_OBJECT) && HasBit(t.m5(), 7)) {
2052 /* Move size and part identification of HQ out of the m5 attribute,
2053 * on new locations */
2054 t.m3() = GB(t.m5(), 0, 5);
2055 t.m5() = OBJECT_HQ;
2059 if (IsSavegameVersionBefore(SLV_144)) {
2060 for (auto t : Map::Iterate()) {
2061 if (!IsTileType(t, MP_OBJECT)) continue;
2063 /* Reordering/generalisation of the object bits. */
2064 ObjectType type = t.m5();
2065 SB(t.m6(), 2, 4, type == OBJECT_HQ ? GB(t.m3(), 2, 3) : 0);
2066 t.m3() = type == OBJECT_HQ ? GB(t.m3(), 1, 1) | GB(t.m3(), 0, 1) << 4 : 0;
2068 /* Make sure those bits are clear as well! */
2069 t.m4() = 0;
2070 t.m7() = 0;
2074 if (IsSavegameVersionBefore(SLV_147) && Object::GetNumItems() == 0) {
2075 /* Make real objects for object tiles. */
2076 for (auto t : Map::Iterate()) {
2077 if (!IsTileType(t, MP_OBJECT)) continue;
2079 if (Town::GetNumItems() == 0) {
2080 /* No towns, so remove all objects! */
2081 DoClearSquare(t);
2082 } else {
2083 uint offset = t.m3();
2085 /* Also move the animation state. */
2086 t.m3() = GB(t.m6(), 2, 4);
2087 SB(t.m6(), 2, 4, 0);
2089 if (offset == 0) {
2090 /* No offset, so make the object. */
2091 ObjectType type = t.m5();
2092 int size = type == OBJECT_HQ ? 2 : 1;
2094 if (!Object::CanAllocateItem()) {
2095 /* Nice... you managed to place 64k lighthouses and
2096 * antennae on the map... boohoo. */
2097 SlError(STR_ERROR_TOO_MANY_OBJECTS);
2100 Object *o = new Object();
2101 o->location.tile = (TileIndex)t;
2102 o->location.w = size;
2103 o->location.h = size;
2104 o->build_date = TimerGameCalendar::date;
2105 o->town = type == OBJECT_STATUE ? Town::Get(t.m2()) : CalcClosestTownFromTile(t, UINT_MAX);
2106 t.m2() = o->index;
2107 Object::IncTypeCount(type);
2108 } else {
2109 /* We're at an offset, so get the ID from our "root". */
2110 Tile northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
2111 assert(IsTileType(northern_tile, MP_OBJECT));
2112 t.m2() = northern_tile.m2();
2118 if (IsSavegameVersionBefore(SLV_113)) {
2119 /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
2120 if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
2121 _settings_game.economy.allow_town_roads = false;
2122 _settings_game.economy.town_layout = TL_BETTER_ROADS;
2123 } else {
2124 _settings_game.economy.allow_town_roads = true;
2125 _settings_game.economy.town_layout = static_cast<TownLayout>(_settings_game.economy.town_layout - 1);
2128 /* Initialize layout of all towns. Older versions were using different
2129 * generator for random town layout, use it if needed. */
2130 for (Town *t : Town::Iterate()) {
2131 if (_settings_game.economy.town_layout != TL_RANDOM) {
2132 t->layout = _settings_game.economy.town_layout;
2133 continue;
2136 /* Use old layout randomizer code */
2137 uint8_t layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
2138 switch (layout) {
2139 default: break;
2140 case 5: layout = 1; break;
2141 case 0: layout = 2; break;
2143 t->layout = static_cast<TownLayout>(layout - 1);
2147 if (IsSavegameVersionBefore(SLV_114)) {
2148 /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
2149 * The conversion affects oil rigs and buoys too, but it doesn't matter as
2150 * they have st->owner == OWNER_NONE already. */
2151 for (Station *st : Station::Iterate()) {
2152 if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
2156 /* Trains could now stop in a specific location. */
2157 if (IsSavegameVersionBefore(SLV_117)) {
2158 for (Order *o : Order::Iterate()) {
2159 if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
2163 if (IsSavegameVersionBefore(SLV_120)) {
2164 extern VehicleDefaultSettings _old_vds;
2165 for (Company *c : Company::Iterate()) {
2166 c->settings.vehicle = _old_vds;
2170 if (IsSavegameVersionBefore(SLV_121)) {
2171 /* Delete small ufos heading for non-existing vehicles */
2172 for (DisasterVehicle *v : DisasterVehicle::Iterate()) {
2173 if (v->subtype == 2 /* ST_SMALL_UFO */ && v->state != 0) {
2174 const Vehicle *u = Vehicle::GetIfValid(v->dest_tile.base());
2175 if (u == nullptr || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
2176 delete v;
2181 /* We didn't store cargo payment yet, so make them for vehicles that are
2182 * currently at a station and loading/unloading. If they don't get any
2183 * payment anymore they just removed in the next load/unload cycle.
2184 * However, some 0.7 versions might have cargo payment. For those we just
2185 * add cargopayment for the vehicles that don't have it.
2187 for (Station *st : Station::Iterate()) {
2188 for (Vehicle *v : st->loading_vehicles) {
2189 /* There are always as many CargoPayments as Vehicles. We need to make the
2190 * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
2191 static_assert(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
2192 assert(CargoPayment::CanAllocateItem());
2193 if (v->cargo_payment == nullptr) v->cargo_payment = new CargoPayment(v);
2198 if (IsSavegameVersionBefore(SLV_122)) {
2199 /* Animated tiles would sometimes not be actually animated or
2200 * in case of old savegames duplicate. */
2202 extern std::vector<TileIndex> _animated_tiles;
2204 for (auto tile = _animated_tiles.begin(); tile < _animated_tiles.end(); /* Nothing */) {
2205 /* Remove if tile is not animated */
2206 bool remove = _tile_type_procs[GetTileType(*tile)]->animate_tile_proc == nullptr;
2208 /* and remove if duplicate */
2209 for (auto j = _animated_tiles.begin(); !remove && j < tile; j++) {
2210 remove = *tile == *j;
2213 if (remove) {
2214 tile = _animated_tiles.erase(tile);
2215 } else {
2216 tile++;
2221 if (IsSavegameVersionBefore(SLV_124) && !IsSavegameVersionBefore(SLV_1)) {
2222 /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
2223 for (Waypoint *wp : Waypoint::Iterate()) {
2224 if (wp->facilities & FACIL_TRAIN) {
2225 wp->train_station.tile = wp->xy;
2226 wp->train_station.w = 1;
2227 wp->train_station.h = 1;
2228 } else {
2229 wp->train_station.tile = INVALID_TILE;
2230 wp->train_station.w = 0;
2231 wp->train_station.h = 0;
2236 if (IsSavegameVersionBefore(SLV_125)) {
2237 /* Convert old subsidies */
2238 for (Subsidy *s : Subsidy::Iterate()) {
2239 if (s->remaining < 12) {
2240 /* Converting nonawarded subsidy */
2241 s->remaining = 12 - s->remaining; // convert "age" to "remaining"
2242 s->awarded = INVALID_COMPANY; // not awarded to anyone
2243 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2244 switch (cs->town_acceptance_effect) {
2245 case TAE_PASSENGERS:
2246 case TAE_MAIL:
2247 /* Town -> Town */
2248 s->src_type = s->dst_type = SourceType::Town;
2249 if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2250 break;
2251 case TAE_GOODS:
2252 case TAE_FOOD:
2253 /* Industry -> Town */
2254 s->src_type = SourceType::Industry;
2255 s->dst_type = SourceType::Town;
2256 if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2257 break;
2258 default:
2259 /* Industry -> Industry */
2260 s->src_type = s->dst_type = SourceType::Industry;
2261 if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
2262 break;
2264 } else {
2265 /* Do our best for awarded subsidies. The original source or destination industry
2266 * can't be determined anymore for awarded subsidies, so invalidate them.
2267 * Town -> Town subsidies are converted using simple heuristic */
2268 s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
2269 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2270 switch (cs->town_acceptance_effect) {
2271 case TAE_PASSENGERS:
2272 case TAE_MAIL: {
2273 /* Town -> Town */
2274 const Station *ss = Station::GetIfValid(s->src);
2275 const Station *sd = Station::GetIfValid(s->dst);
2276 if (ss != nullptr && sd != nullptr && ss->owner == sd->owner &&
2277 Company::IsValidID(ss->owner)) {
2278 s->src_type = s->dst_type = SourceType::Town;
2279 s->src = ss->town->index;
2280 s->dst = sd->town->index;
2281 s->awarded = ss->owner;
2282 continue;
2284 break;
2286 default:
2287 break;
2290 /* Awarded non-town subsidy or invalid source/destination, invalidate */
2291 delete s;
2295 if (IsSavegameVersionBefore(SLV_126)) {
2296 /* Recompute inflation based on old unround loan limit
2297 * Note: Max loan is 500000. With an inflation of 4% across 170 years
2298 * that results in a max loan of about 0.7 * 2^31.
2299 * So taking the 16 bit fractional part into account there are plenty of bits left
2300 * for unmodified savegames ...
2302 uint64_t aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
2304 /* ... well, just clamp it then. */
2305 if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
2307 /* Simulate the inflation, so we also get the payment inflation */
2308 while (_economy.inflation_prices < aimed_inflation) {
2309 if (AddInflation(false)) break;
2313 if (IsSavegameVersionBefore(SLV_128)) {
2314 for (const Depot *d : Depot::Iterate()) {
2315 Tile tile = d->xy;
2316 /* At some point, invalid depots were saved into the game (possibly those removed in the past?)
2317 * Remove them here, so they don't cause issues further down the line */
2318 if (!IsDepotTile(tile)) {
2319 Debug(sl, 0, "Removing invalid depot {} at {}, {}", d->index, TileX(d->xy), TileY(d->xy));
2320 delete d;
2321 d = nullptr;
2322 continue;
2324 tile.m2() = d->index;
2325 if (IsTileType(tile, MP_WATER)) Tile(GetOtherShipDepotTile(tile)).m2() = d->index;
2329 /* The behaviour of force_proceed has been changed. Now
2330 * it counts signals instead of some random time out. */
2331 if (IsSavegameVersionBefore(SLV_131)) {
2332 for (Train *t : Train::Iterate()) {
2333 if (t->force_proceed != TFP_NONE) {
2334 t->force_proceed = TFP_STUCK;
2339 /* The bits for the tree ground and tree density have
2340 * been swapped (m2 bits 7..6 and 5..4. */
2341 if (IsSavegameVersionBefore(SLV_135)) {
2342 for (auto t : Map::Iterate()) {
2343 if (IsTileType(t, MP_CLEAR)) {
2344 if (GetRawClearGround(t) == CLEAR_SNOW) {
2345 SetClearGroundDensity(t, CLEAR_GRASS, GetClearDensity(t));
2346 SetBit(t.m3(), 4);
2347 } else {
2348 ClrBit(t.m3(), 4);
2351 if (IsTileType(t, MP_TREES)) {
2352 uint density = GB(t.m2(), 6, 2);
2353 uint ground = GB(t.m2(), 4, 2);
2354 t.m2() = ground << 6 | density << 4;
2359 /* Wait counter and load/unload ticks got split. */
2360 if (IsSavegameVersionBefore(SLV_136)) {
2361 for (Aircraft *a : Aircraft::Iterate()) {
2362 a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
2365 for (Train *t : Train::Iterate()) {
2366 t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
2370 /* Airport tile animation uses animation frame instead of other graphics id */
2371 if (IsSavegameVersionBefore(SLV_137)) {
2372 struct AirportTileConversion {
2373 uint8_t old_start;
2374 uint8_t num_frames;
2376 static const AirportTileConversion atcs[] = {
2377 {31, 12}, // APT_RADAR_GRASS_FENCE_SW
2378 {50, 4}, // APT_GRASS_FENCE_NE_FLAG
2379 {62, 2}, // 1 unused tile
2380 {66, 12}, // APT_RADAR_FENCE_SW
2381 {78, 12}, // APT_RADAR_FENCE_NE
2382 {101, 10}, // 9 unused tiles
2383 {111, 8}, // 7 unused tiles
2384 {119, 15}, // 14 unused tiles (radar)
2385 {140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
2387 for (auto t : Map::Iterate()) {
2388 if (IsAirportTile(t)) {
2389 StationGfx old_gfx = GetStationGfx(t);
2390 uint8_t offset = 0;
2391 for (const auto &atc : atcs) {
2392 if (old_gfx < atc.old_start) {
2393 SetStationGfx(t, old_gfx - offset);
2394 break;
2396 if (old_gfx < atc.old_start + atc.num_frames) {
2397 SetAnimationFrame(t, old_gfx - atc.old_start);
2398 SetStationGfx(t, atc.old_start - offset);
2399 break;
2401 offset += atc.num_frames - 1;
2407 /* Oilrig was moved from id 15 to 9. */
2408 if (IsSavegameVersionBefore(SLV_139)) {
2409 for (Station *st : Station::Iterate()) {
2410 if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
2411 st->airport.type = AT_OILRIG;
2416 if (IsSavegameVersionBefore(SLV_140)) {
2417 for (Station *st : Station::Iterate()) {
2418 if (st->airport.tile != INVALID_TILE) {
2419 st->airport.w = st->airport.GetSpec()->size_x;
2420 st->airport.h = st->airport.GetSpec()->size_y;
2425 if (IsSavegameVersionBefore(SLV_141)) {
2426 for (auto t : Map::Iterate()) {
2427 /* Reset tropic zone for VOID tiles, they shall not have any. */
2428 if (IsTileType(t, MP_VOID)) SetTropicZone(t, TROPICZONE_NORMAL);
2431 /* We need to properly number/name the depots.
2432 * The first step is making sure none of the depots uses the
2433 * 'default' names, after that we can assign the names. */
2434 for (Depot *d : Depot::Iterate()) d->town_cn = UINT16_MAX;
2436 for (Depot *d : Depot::Iterate()) MakeDefaultName(d);
2439 if (IsSavegameVersionBefore(SLV_142)) {
2440 for (Depot *d : Depot::Iterate()) d->build_date = TimerGameCalendar::date;
2443 /* In old versions it was possible to remove an airport while a plane was
2444 * taking off or landing. This gives all kind of problems when building
2445 * another airport in the same station so we don't allow that anymore.
2446 * For old savegames with such aircraft we just throw them in the air and
2447 * treat the aircraft like they were flying already. */
2448 if (IsSavegameVersionBefore(SLV_146)) {
2449 for (Aircraft *v : Aircraft::Iterate()) {
2450 if (!v->IsNormalAircraft()) continue;
2451 Station *st = GetTargetAirportIfValid(v);
2452 if (st == nullptr && v->state != FLYING) {
2453 v->state = FLYING;
2454 UpdateAircraftCache(v);
2455 AircraftNextAirportPos_and_Order(v);
2456 /* get aircraft back on running altitude */
2457 if ((v->vehstatus & VS_CRASHED) == 0) {
2458 GetAircraftFlightLevelBounds(v, &v->z_pos, nullptr);
2459 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
2465 /* Move the animation frame to the same location (m7) for all objects. */
2466 if (IsSavegameVersionBefore(SLV_147)) {
2467 for (auto t : Map::Iterate()) {
2468 switch (GetTileType(t)) {
2469 case MP_HOUSE:
2470 if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
2471 uint per_proc = t.m7();
2472 t.m7() = GB(t.m6(), 2, 6) | (GB(t.m3(), 5, 1) << 6);
2473 SB(t.m3(), 5, 1, 0);
2474 SB(t.m6(), 2, 6, std::min(per_proc, 63U));
2476 break;
2478 case MP_INDUSTRY: {
2479 uint rand = t.m7();
2480 t.m7() = t.m3();
2481 t.m3() = rand;
2482 break;
2485 case MP_OBJECT:
2486 t.m7() = t.m3();
2487 t.m3() = 0;
2488 break;
2490 default:
2491 /* For stations/airports it's already at m7 */
2492 break;
2497 /* Add (random) colour to all objects. */
2498 if (IsSavegameVersionBefore(SLV_148)) {
2499 for (Object *o : Object::Iterate()) {
2500 Owner owner = GetTileOwner(o->location.tile);
2501 o->colour = (owner == OWNER_NONE) ? static_cast<Colours>(GB(Random(), 0, 4)) : Company::Get(owner)->livery->colour1;
2505 if (IsSavegameVersionBefore(SLV_149)) {
2506 for (auto t : Map::Iterate()) {
2507 if (!IsTileType(t, MP_STATION)) continue;
2508 if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && IsTileFlat(t))) {
2509 SetWaterClass(t, WATER_CLASS_INVALID);
2513 /* Waypoints with custom name may have a non-unique town_cn,
2514 * renumber those. First set all affected waypoints to the
2515 * highest possible number to get them numbered in the
2516 * order they have in the pool. */
2517 for (Waypoint *wp : Waypoint::Iterate()) {
2518 if (!wp->name.empty()) wp->town_cn = UINT16_MAX;
2521 for (Waypoint *wp : Waypoint::Iterate()) {
2522 if (!wp->name.empty()) MakeDefaultName(wp);
2526 if (IsSavegameVersionBefore(SLV_152)) {
2527 _industry_builder.Reset(); // Initialize industry build data.
2529 /* The moment vehicles go from hidden to visible changed. This means
2530 * that vehicles don't always get visible anymore causing things to
2531 * get messed up just after loading the savegame. This fixes that. */
2532 for (Vehicle *v : Vehicle::Iterate()) {
2533 /* Not all vehicle types can be inside a tunnel. Furthermore,
2534 * testing IsTunnelTile() for invalid tiles causes a crash. */
2535 if (!v->IsGroundVehicle()) continue;
2537 /* Is the vehicle in a tunnel? */
2538 if (!IsTunnelTile(v->tile)) continue;
2540 /* Is the vehicle actually at a tunnel entrance/exit? */
2541 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
2542 if (!IsTunnelTile(vtile)) continue;
2544 /* Are we actually in this tunnel? Or maybe a lower tunnel? */
2545 if (GetSlopePixelZ(v->x_pos, v->y_pos, true) != v->z_pos) continue;
2547 /* What way are we going? */
2548 const DiagDirection dir = GetTunnelBridgeDirection(vtile);
2549 const DiagDirection vdir = DirToDiagDir(v->direction);
2551 /* Have we passed the visibility "switch" state already? */
2552 uint8_t pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
2553 uint8_t frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2554 extern const uint8_t _tunnel_visibility_frame[DIAGDIR_END];
2556 /* Should the vehicle be hidden or not? */
2557 bool hidden;
2558 if (dir == vdir) { // Entering tunnel
2559 hidden = frame >= _tunnel_visibility_frame[dir];
2560 v->tile = vtile;
2561 } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
2562 hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
2563 /* v->tile changes at the moment when the vehicle leaves the tunnel. */
2564 v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
2565 } else {
2566 /* We could get here in two cases:
2567 * - for road vehicles, it is reversing at the end of the tunnel
2568 * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
2569 * Whatever case it is, do not change anything and use the old values.
2570 * Especially changing RV's state would break its reversing in the middle. */
2571 continue;
2574 if (hidden) {
2575 v->vehstatus |= VS_HIDDEN;
2577 switch (v->type) {
2578 case VEH_TRAIN: Train::From(v)->track = TRACK_BIT_WORMHOLE; break;
2579 case VEH_ROAD: RoadVehicle::From(v)->state = RVSB_WORMHOLE; break;
2580 default: NOT_REACHED();
2582 } else {
2583 v->vehstatus &= ~VS_HIDDEN;
2585 switch (v->type) {
2586 case VEH_TRAIN: Train::From(v)->track = DiagDirToDiagTrackBits(vdir); break;
2587 case VEH_ROAD: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
2588 default: NOT_REACHED();
2594 if (IsSavegameVersionBefore(SLV_153)) {
2595 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
2596 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
2598 bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
2599 if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
2600 extern const uint8_t _road_stop_stop_frame[];
2601 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)]);
2602 } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
2603 SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
2608 if (IsSavegameVersionBefore(SLV_156)) {
2609 /* The train's pathfinder lost flag got moved. */
2610 for (Train *t : Train::Iterate()) {
2611 if (!HasBit(t->flags, 5)) continue;
2613 ClrBit(t->flags, 5);
2614 SetBit(t->vehicle_flags, VF_PATHFINDER_LOST);
2617 /* Introduced terraform/clear limits. */
2618 for (Company *c : Company::Iterate()) {
2619 c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
2620 c->clear_limit = _settings_game.construction.clear_frame_burst << 16;
2625 if (IsSavegameVersionBefore(SLV_CONSISTENT_PARTIAL_Z)) {
2627 * The logic of GetPartialPixelZ has been changed, so the resulting Zs on
2628 * the map are consistent. This requires that the Z position of some
2629 * vehicles is updated to reflect this new situation.
2631 * This needs to be before SLV_158, because that performs asserts using
2632 * GetSlopePixelZ which internally uses GetPartialPixelZ.
2634 for (Vehicle *v : Vehicle::Iterate()) {
2635 if (v->IsGroundVehicle() && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2636 /* Vehicle is on the ground, and not in a wormhole. */
2637 v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos, true);
2642 if (IsSavegameVersionBefore(SLV_158)) {
2643 for (Vehicle *v : Vehicle::Iterate()) {
2644 switch (v->type) {
2645 case VEH_TRAIN: {
2646 Train *t = Train::From(v);
2648 /* Clear old GOINGUP / GOINGDOWN flags.
2649 * It was changed in savegame version 139, but savegame
2650 * version 158 doesn't use these bits, so it doesn't hurt
2651 * to clear them unconditionally. */
2652 ClrBit(t->flags, 1);
2653 ClrBit(t->flags, 2);
2655 /* Clear both bits first. */
2656 ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
2657 ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
2659 /* Crashed vehicles can't be going up/down. */
2660 if (t->vehstatus & VS_CRASHED) break;
2662 /* Only X/Y tracks can be sloped. */
2663 if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
2665 t->gv_flags |= FixVehicleInclination(t, t->direction);
2666 break;
2668 case VEH_ROAD: {
2669 RoadVehicle *rv = RoadVehicle::From(v);
2670 ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
2671 ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
2673 /* Crashed vehicles can't be going up/down. */
2674 if (rv->vehstatus & VS_CRASHED) break;
2676 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
2678 TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, GetRoadTramType(rv->roadtype));
2679 TrackBits trackbits = TrackStatusToTrackBits(ts);
2681 /* Only X/Y tracks can be sloped. */
2682 if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
2684 Direction dir = rv->direction;
2686 /* Test if we are reversing. */
2687 Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
2688 if (AxisToDirection(a) != dir &&
2689 AxisToDirection(a) != ReverseDir(dir)) {
2690 /* When reversing, the road vehicle is on the edge of the tile,
2691 * so it can be safely compared to the middle of the tile. */
2692 dir = INVALID_DIR;
2695 rv->gv_flags |= FixVehicleInclination(rv, dir);
2696 break;
2698 case VEH_SHIP:
2699 break;
2701 default:
2702 continue;
2705 if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2706 /* In old versions, z_pos was 1 unit lower on bridge heads.
2707 * However, this invalid state could be converted to new savegames
2708 * by loading and saving the game in a new version. */
2709 v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos, true);
2710 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
2711 if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
2712 v->direction != DiagDirToDir(dir)) {
2713 /* If the train has left the bridge, it shouldn't have
2714 * track == TRACK_BIT_WORMHOLE - this could happen
2715 * when the train was reversed while on the last "tick"
2716 * on the ramp before leaving the ramp to the bridge. */
2717 Train::From(v)->track = DiagDirToDiagTrackBits(dir);
2721 /* If the vehicle is really above v->tile (not in a wormhole),
2722 * it should have set v->z_pos correctly. */
2723 assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos, true));
2726 /* Fill Vehicle::cur_real_order_index */
2727 for (Vehicle *v : Vehicle::Iterate()) {
2728 if (!v->IsPrimaryVehicle()) continue;
2730 /* Older versions are less strict with indices being in range and fix them on the fly */
2731 if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
2733 v->cur_real_order_index = v->cur_implicit_order_index;
2734 v->UpdateRealOrderIndex();
2738 if (IsSavegameVersionBefore(SLV_159)) {
2739 /* If the savegame is old (before version 100), then the value of 255
2740 * for these settings did not mean "disabled". As such everything
2741 * before then did reverse.
2742 * To simplify stuff we disable all turning around or we do not
2743 * disable anything at all. So, if some reversing was disabled we
2744 * will keep reversing disabled, otherwise it'll be turned on. */
2745 _settings_game.pf.reverse_at_signals = IsSavegameVersionBefore(SLV_100) || (_settings_game.pf.wait_oneway_signal != 255 && _settings_game.pf.wait_twoway_signal != 255 && _settings_game.pf.wait_for_pbs_path != 255);
2747 for (Train *t : Train::Iterate()) {
2748 _settings_game.vehicle.max_train_length = std::max<uint8_t>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
2752 if (IsSavegameVersionBefore(SLV_160)) {
2753 /* Setting difficulty industry_density other than zero get bumped to +1
2754 * since a new option (minimal at position 1) has been added */
2755 if (_settings_game.difficulty.industry_density > 0) {
2756 _settings_game.difficulty.industry_density++;
2760 if (IsSavegameVersionBefore(SLV_161)) {
2761 /* Before savegame version 161, persistent storages were not stored in a pool. */
2763 if (!IsSavegameVersionBefore(SLV_76)) {
2764 for (Industry *ind : Industry::Iterate()) {
2765 assert(ind->psa != nullptr);
2767 /* Check if the old storage was empty. */
2768 bool is_empty = true;
2769 for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
2770 if (ind->psa->GetValue(i) != 0) {
2771 is_empty = false;
2772 break;
2776 if (!is_empty) {
2777 ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
2778 } else {
2779 delete ind->psa;
2780 ind->psa = nullptr;
2785 if (!IsSavegameVersionBefore(SLV_145)) {
2786 for (Station *st : Station::Iterate()) {
2787 if (!(st->facilities & FACIL_AIRPORT)) continue;
2788 assert(st->airport.psa != nullptr);
2790 /* Check if the old storage was empty. */
2791 bool is_empty = true;
2792 for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
2793 if (st->airport.psa->GetValue(i) != 0) {
2794 is_empty = false;
2795 break;
2799 if (!is_empty) {
2800 st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
2801 } else {
2802 delete st->airport.psa;
2803 st->airport.psa = nullptr;
2810 /* This triggers only when old snow_lines were copied into the snow_line_height. */
2811 if (IsSavegameVersionBefore(SLV_164) && _settings_game.game_creation.snow_line_height >= MIN_SNOWLINE_HEIGHT * TILE_HEIGHT) {
2812 _settings_game.game_creation.snow_line_height /= TILE_HEIGHT;
2815 if (IsSavegameVersionBefore(SLV_164) && !IsSavegameVersionBefore(SLV_32)) {
2816 /* We store 4 fences in the field tiles instead of only SE and SW. */
2817 for (auto t : Map::Iterate()) {
2818 if (!IsTileType(t, MP_CLEAR) && !IsTileType(t, MP_TREES)) continue;
2819 if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) continue;
2820 uint fence = GB(t.m4(), 5, 3);
2821 if (fence != 0 && IsTileType(TileAddXY(t, 1, 0), MP_CLEAR) && IsClearGround(TileAddXY(t, 1, 0), CLEAR_FIELDS)) {
2822 SetFence(TileAddXY(t, 1, 0), DIAGDIR_NE, fence);
2824 fence = GB(t.m4(), 2, 3);
2825 if (fence != 0 && IsTileType(TileAddXY(t, 0, 1), MP_CLEAR) && IsClearGround(TileAddXY(t, 0, 1), CLEAR_FIELDS)) {
2826 SetFence(TileAddXY(t, 0, 1), DIAGDIR_NW, fence);
2828 SB(t.m4(), 2, 3, 0);
2829 SB(t.m4(), 5, 3, 0);
2833 if (IsSavegameVersionBefore(SLV_165)) {
2834 for (Town *t : Town::Iterate()) {
2835 /* Set the default cargo requirement for town growth */
2836 switch (_settings_game.game_creation.landscape) {
2837 case LT_ARCTIC:
2838 if (FindFirstCargoWithTownAcceptanceEffect(TAE_FOOD) != nullptr) t->goal[TAE_FOOD] = TOWN_GROWTH_WINTER;
2839 break;
2841 case LT_TROPIC:
2842 if (FindFirstCargoWithTownAcceptanceEffect(TAE_FOOD) != nullptr) t->goal[TAE_FOOD] = TOWN_GROWTH_DESERT;
2843 if (FindFirstCargoWithTownAcceptanceEffect(TAE_WATER) != nullptr) t->goal[TAE_WATER] = TOWN_GROWTH_DESERT;
2844 break;
2849 if (IsSavegameVersionBefore(SLV_165)) {
2850 /* Adjust zoom level to account for new levels */
2851 _saved_scrollpos_zoom = static_cast<ZoomLevel>(_saved_scrollpos_zoom + ZOOM_BASE_SHIFT);
2852 _saved_scrollpos_x *= ZOOM_BASE;
2853 _saved_scrollpos_y *= ZOOM_BASE;
2856 /* When any NewGRF has been changed the availability of some vehicles might
2857 * have been changed too. e->company_avail must be set to 0 in that case
2858 * which is done by StartupEngines(). */
2859 if (gcf_res != GLC_ALL_GOOD) StartupEngines();
2861 /* The road owner of standard road stops was not properly accounted for. */
2862 if (IsSavegameVersionBefore(SLV_172)) {
2863 for (auto t : Map::Iterate()) {
2864 if (!IsBayRoadStopTile(t)) continue;
2865 Owner o = GetTileOwner(t);
2866 SetRoadOwner(t, RTT_ROAD, o);
2867 SetRoadOwner(t, RTT_TRAM, o);
2871 if (IsSavegameVersionBefore(SLV_175)) {
2872 /* Introduced tree planting limit. */
2873 for (Company *c : Company::Iterate()) c->tree_limit = _settings_game.construction.tree_frame_burst << 16;
2876 if (IsSavegameVersionBefore(SLV_177)) {
2877 /* Fix too high inflation rates */
2878 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
2879 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
2881 /* We have to convert the quarters of bankruptcy into months of bankruptcy */
2882 for (Company *c : Company::Iterate()) {
2883 c->months_of_bankruptcy = 3 * c->months_of_bankruptcy;
2888 /* Station blocked, wires and pylon flags need to be stored in the map. This is effectively cached data, so no
2889 * version check is necessary. This is done here as the SLV_182 check below needs the blocked status. */
2890 for (auto t : Map::Iterate()) {
2891 if (HasStationTileRail(t)) SetRailStationTileFlags(t, GetStationSpec(t));
2895 if (IsSavegameVersionBefore(SLV_182)) {
2896 /* Aircraft acceleration variable was bonkers */
2897 for (Aircraft *v : Aircraft::Iterate()) {
2898 if (v->subtype <= AIR_AIRCRAFT) {
2899 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
2900 v->acceleration = avi->acceleration;
2904 /* Blocked tiles could be reserved due to a bug, which causes
2905 * other places to assert upon e.g. station reconstruction. */
2906 for (auto t : Map::Iterate()) {
2907 if (HasStationTileRail(t) && IsStationTileBlocked(t)) {
2908 SetRailStationReservation(t, false);
2913 if (IsSavegameVersionBefore(SLV_184)) {
2914 /* The global units configuration is split up in multiple configurations. */
2915 extern uint8_t _old_units;
2916 _settings_game.locale.units_velocity = Clamp(_old_units, 0, 2);
2917 _settings_game.locale.units_power = Clamp(_old_units, 0, 2);
2918 _settings_game.locale.units_weight = Clamp(_old_units, 1, 2);
2919 _settings_game.locale.units_volume = Clamp(_old_units, 1, 2);
2920 _settings_game.locale.units_force = 2;
2921 _settings_game.locale.units_height = Clamp(_old_units, 0, 2);
2924 if (IsSavegameVersionBefore(SLV_VELOCITY_NAUTICAL)) {
2925 /* Match nautical velocity with land velocity units. */
2926 _settings_game.locale.units_velocity_nautical = _settings_game.locale.units_velocity;
2929 if (IsSavegameVersionBefore(SLV_186)) {
2930 /* Move ObjectType from map to pool */
2931 for (auto t : Map::Iterate()) {
2932 if (IsTileType(t, MP_OBJECT)) {
2933 Object *o = Object::Get(t.m2());
2934 o->type = t.m5();
2935 t.m5() = 0; // zero upper bits of (now bigger) ObjectID
2940 /* Beyond this point, tile types which can be accessed by vehicles must be in a valid state. */
2942 /* Update all vehicles: Phase 2 */
2943 AfterLoadVehiclesPhase2(true);
2945 /* The center of train vehicles was changed, fix up spacing. */
2946 if (IsSavegameVersionBefore(SLV_164)) FixupTrainLengths();
2948 /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
2949 * This has to be called after all map array updates */
2950 if (IsSavegameVersionBefore(SLV_2, 2)) UpdateOldAircraft();
2952 if (IsSavegameVersionBefore(SLV_188)) {
2953 /* Fix articulated road vehicles.
2954 * Some curves were shorter than other curves.
2955 * Now they have the same length, but that means that trailing articulated parts will
2956 * take longer to go through the curve than the parts in front which already left the courve.
2957 * So, make articulated parts catch up. */
2958 bool roadside = _settings_game.vehicle.road_side == 1;
2959 std::vector<uint> skip_frames;
2960 for (RoadVehicle *v : RoadVehicle::Iterate()) {
2961 if (!v->IsFrontEngine()) continue;
2962 skip_frames.clear();
2963 TileIndex prev_tile = v->tile;
2964 uint prev_tile_skip = 0;
2965 uint cur_skip = 0;
2966 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
2967 if (u->tile != prev_tile) {
2968 prev_tile_skip = cur_skip;
2969 prev_tile = u->tile;
2970 } else {
2971 cur_skip = prev_tile_skip;
2974 uint &this_skip = skip_frames.emplace_back(prev_tile_skip);
2976 /* The following 3 curves now take longer than before */
2977 switch (u->state) {
2978 case 2:
2979 cur_skip++;
2980 if (u->frame <= (roadside ? 9 : 5)) this_skip = cur_skip;
2981 break;
2983 case 4:
2984 cur_skip++;
2985 if (u->frame <= (roadside ? 5 : 9)) this_skip = cur_skip;
2986 break;
2988 case 5:
2989 cur_skip++;
2990 if (u->frame <= (roadside ? 4 : 2)) this_skip = cur_skip;
2991 break;
2993 default:
2994 break;
2997 while (cur_skip > skip_frames[0]) {
2998 RoadVehicle *u = v;
2999 RoadVehicle *prev = nullptr;
3000 for (uint sf : skip_frames) {
3001 if (sf >= cur_skip) IndividualRoadVehicleController(u, prev);
3003 prev = u;
3004 u = u->Next();
3006 cur_skip--;
3011 if (IsSavegameVersionBefore(SLV_190)) {
3012 for (Order *order : Order::Iterate()) {
3013 order->SetTravelTimetabled(order->GetTravelTime() > 0);
3014 order->SetWaitTimetabled(order->GetWaitTime() > 0);
3016 for (OrderList *orderlist : OrderList::Iterate()) {
3017 orderlist->RecalculateTimetableDuration();
3022 * Only keep order-backups for network clients (and when replaying).
3023 * If we are a network server or not networking, then we just loaded a previously
3024 * saved-by-server savegame. There are no clients with a backup, so clear it.
3025 * Furthermore before savegame version SLV_192 the actual content was always corrupt.
3027 if (!_networking || _network_server || IsSavegameVersionBefore(SLV_192)) {
3028 #ifndef DEBUG_DUMP_COMMANDS
3029 /* Note: We cannot use CleanPool since that skips part of the destructor
3030 * and then leaks un-reachable Orders in the order pool. */
3031 for (OrderBackup *ob : OrderBackup::Iterate()) {
3032 delete ob;
3034 #endif
3037 if (IsSavegameVersionBefore(SLV_198)) {
3038 /* Convert towns growth_rate and grow_counter to ticks */
3039 for (Town *t : Town::Iterate()) {
3040 /* 0x8000 = TOWN_GROWTH_RATE_CUSTOM previously */
3041 if (t->growth_rate & 0x8000) SetBit(t->flags, TOWN_CUSTOM_GROWTH);
3042 if (t->growth_rate != TOWN_GROWTH_RATE_NONE) {
3043 t->growth_rate = TownTicksToGameTicks(t->growth_rate & ~0x8000);
3045 /* Add t->index % TOWN_GROWTH_TICKS to spread growth across ticks. */
3046 t->grow_counter = TownTicksToGameTicks(t->grow_counter) + t->index % Ticks::TOWN_GROWTH_TICKS;
3050 if (IsSavegameVersionBefore(SLV_EXTEND_INDUSTRY_CARGO_SLOTS)) {
3051 /* Make sure added industry cargo slots are cleared */
3052 for (Industry *i : Industry::Iterate()) {
3053 /* Make sure last_cargo_accepted_at is copied to elements for every valid input cargo.
3054 * The loading routine should put the original singular value into the first array element. */
3055 for (auto &a : i->accepted) {
3056 if (IsValidCargoID(a.cargo)) {
3057 a.last_accepted = i->GetAccepted(0).last_accepted;
3058 } else {
3059 a.last_accepted = 0;
3065 if (IsSavegameVersionBefore(SLV_SHIPS_STOP_IN_LOCKS)) {
3066 /* Move ships from lock slope to upper or lower position. */
3067 for (Ship *s : Ship::Iterate()) {
3068 /* Suitable tile? */
3069 if (!IsTileType(s->tile, MP_WATER) || !IsLock(s->tile) || GetLockPart(s->tile) != LOCK_PART_MIDDLE) continue;
3071 /* We don't need to adjust position when at the tile centre */
3072 int x = s->x_pos & 0xF;
3073 int y = s->y_pos & 0xF;
3074 if (x == 8 && y == 8) continue;
3076 /* Test if ship is on the second half of the tile */
3077 bool second_half;
3078 DiagDirection shipdiagdir = DirToDiagDir(s->direction);
3079 switch (shipdiagdir) {
3080 default: NOT_REACHED();
3081 case DIAGDIR_NE: second_half = x < 8; break;
3082 case DIAGDIR_NW: second_half = y < 8; break;
3083 case DIAGDIR_SW: second_half = x > 8; break;
3084 case DIAGDIR_SE: second_half = y > 8; break;
3087 DiagDirection slopediagdir = GetInclinedSlopeDirection(GetTileSlope(s->tile));
3089 /* Heading up slope == passed half way */
3090 if ((shipdiagdir == slopediagdir) == second_half) {
3091 /* On top half of lock */
3092 s->z_pos = GetTileMaxZ(s->tile) * (int)TILE_HEIGHT;
3093 } else {
3094 /* On lower half of lock */
3095 s->z_pos = GetTileZ(s->tile) * (int)TILE_HEIGHT;
3100 if (IsSavegameVersionBefore(SLV_TOWN_CARGOGEN)) {
3101 /* Ensure the original cargo generation mode is used */
3102 _settings_game.economy.town_cargogen_mode = TCGM_ORIGINAL;
3105 if (IsSavegameVersionBefore(SLV_SERVE_NEUTRAL_INDUSTRIES)) {
3106 /* Ensure the original neutral industry/station behaviour is used */
3107 _settings_game.station.serve_neutral_industries = true;
3109 /* Link oil rigs to their industry and back. */
3110 for (Station *st : Station::Iterate()) {
3111 if (IsTileType(st->xy, MP_STATION) && IsOilRig(st->xy)) {
3112 /* Industry tile is always adjacent during construction by TileDiffXY(0, 1) */
3113 st->industry = Industry::GetByTile(st->xy + TileDiffXY(0, 1));
3114 st->industry->neutral_station = st;
3117 } else {
3118 /* Link neutral station back to industry, as this is not saved. */
3119 for (Industry *ind : Industry::Iterate()) if (ind->neutral_station != nullptr) ind->neutral_station->industry = ind;
3122 if (IsSavegameVersionBefore(SLV_TREES_WATER_CLASS)) {
3123 /* Update water class for trees. */
3124 for (auto t : Map::Iterate()) {
3125 if (IsTileType(t, MP_TREES)) SetWaterClass(t, GetTreeGround(t) == TREE_GROUND_SHORE ? WATER_CLASS_SEA : WATER_CLASS_INVALID);
3129 /* Update structures for multitile docks */
3130 if (IsSavegameVersionBefore(SLV_MULTITILE_DOCKS)) {
3131 for (auto t : Map::Iterate()) {
3132 /* Clear docking tile flag from relevant tiles as it
3133 * was not previously cleared. */
3134 if (IsTileType(t, MP_WATER) || IsTileType(t, MP_RAILWAY) || IsTileType(t, MP_STATION) || IsTileType(t, MP_TUNNELBRIDGE)) {
3135 SetDockingTile(t, false);
3137 /* Add docks and oilrigs to Station::ship_station. */
3138 if (IsTileType(t, MP_STATION)) {
3139 if (IsDock(t) || IsOilRig(t)) Station::GetByTile(t)->ship_station.Add(t);
3144 if (IsSavegameVersionBefore(SLV_REPAIR_OBJECT_DOCKING_TILES)) {
3145 /* Placing objects on docking tiles was not updating adjacent station's docking tiles. */
3146 for (Station *st : Station::Iterate()) {
3147 if (st->ship_station.tile != INVALID_TILE) UpdateStationDockingTiles(st);
3151 if (IsSavegameVersionBeforeOrAt(SLV_ENDING_YEAR)) {
3152 /* Reset roadtype/streetcartype info for non-road bridges. */
3153 for (auto t : Map::Iterate()) {
3154 if (IsTileType(t, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(t) != TRANSPORT_ROAD) {
3155 SetRoadTypes(t, INVALID_ROADTYPE, INVALID_ROADTYPE);
3160 /* Make sure all industries exclusive supplier/consumer set correctly. */
3161 if (IsSavegameVersionBefore(SLV_GS_INDUSTRY_CONTROL)) {
3162 for (Industry *i : Industry::Iterate()) {
3163 i->exclusive_supplier = INVALID_OWNER;
3164 i->exclusive_consumer = INVALID_OWNER;
3168 if (IsSavegameVersionBefore(SLV_GROUP_REPLACE_WAGON_REMOVAL)) {
3169 /* Propagate wagon removal flag for compatibility */
3170 /* Temporary bitmask of company wagon removal setting */
3171 uint16_t wagon_removal = 0;
3172 for (const Company *c : Company::Iterate()) {
3173 if (c->settings.renew_keep_length) SetBit(wagon_removal, c->index);
3175 for (Group *g : Group::Iterate()) {
3176 if (g->flags != 0) {
3177 /* Convert old replace_protection value to flag. */
3178 g->flags = 0;
3179 SetBit(g->flags, GroupFlags::GF_REPLACE_PROTECTION);
3181 if (HasBit(wagon_removal, g->owner)) SetBit(g->flags, GroupFlags::GF_REPLACE_WAGON_REMOVAL);
3185 /* Use current order time to approximate last loading time */
3186 if (IsSavegameVersionBefore(SLV_LAST_LOADING_TICK)) {
3187 for (Vehicle *v : Vehicle::Iterate()) {
3188 v->last_loading_tick = std::max(TimerGameTick::counter, static_cast<uint64_t>(v->current_order_time)) - v->current_order_time;
3192 /* Road stops is 'only' updating some caches, but they are needed for PF calls in SLV_MULTITRACK_LEVEL_CROSSINGS teleporting. */
3193 AfterLoadRoadStops();
3195 /* Road vehicles stopped on multitrack level crossings need teleporting to a depot
3196 * to avoid crashing into the side of the train they're waiting for. */
3197 if (IsSavegameVersionBefore(SLV_MULTITRACK_LEVEL_CROSSINGS)) {
3198 /* Teleport road vehicles to the nearest depot. */
3199 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
3200 /* Ignore trailers of articulated vehicles. */
3201 if (rv->IsArticulatedPart()) continue;
3203 /* Ignore moving vehicles. */
3204 if (rv->cur_speed > 0) continue;
3206 /* Ignore crashed vehicles. */
3207 if (rv->vehstatus & VS_CRASHED) continue;
3209 /* Ignore vehicles not on level crossings. */
3210 TileIndex cur_tile = rv->tile;
3211 if (!IsLevelCrossingTile(cur_tile)) continue;
3213 ClosestDepot closestDepot = rv->FindClosestDepot();
3215 /* Try to find a depot with a distance limit of 512 tiles (Manhattan distance). */
3216 if (closestDepot.found && DistanceManhattan(rv->tile, closestDepot.location) < 512u) {
3217 /* Teleport all parts of articulated vehicles. */
3218 for (RoadVehicle *u = rv; u != nullptr; u = u->Next()) {
3219 u->tile = closestDepot.location;
3220 int x = TileX(closestDepot.location) * TILE_SIZE + TILE_SIZE / 2;
3221 int y = TileY(closestDepot.location) * TILE_SIZE + TILE_SIZE / 2;
3222 u->x_pos = x;
3223 u->y_pos = y;
3224 u->z_pos = GetSlopePixelZ(x, y, true);
3226 u->vehstatus |= VS_HIDDEN;
3227 u->state = RVSB_IN_DEPOT;
3228 u->UpdatePosition();
3230 RoadVehLeaveDepot(rv, false);
3234 if (IsSavegameVersionBeforeOrAt(SLV_MULTITRACK_LEVEL_CROSSINGS)) {
3235 /* Reset unused tree counters to reduce the savegame size. */
3236 for (auto t : Map::Iterate()) {
3237 if (IsTileType(t, MP_TREES)) {
3238 SB(t.m2(), 0, 4, 0);
3243 /* Refresh all level crossings to bar adjacent crossing tiles, if needed. */
3244 for (auto tile : Map::Iterate()) {
3245 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile, false);
3249 /* Compute station catchment areas. This is needed here in case UpdateStationAcceptance is called below. */
3250 Station::RecomputeCatchmentForAll();
3252 /* Station acceptance is some kind of cache */
3253 if (IsSavegameVersionBefore(SLV_127)) {
3254 for (Station *st : Station::Iterate()) UpdateStationAcceptance(st, false);
3257 if (IsSavegameVersionBefore(SLV_SAVEGAME_ID)) {
3258 GenerateSavegameId();
3261 if (IsSavegameVersionBefore(SLV_AI_START_DATE)) {
3262 /* For older savegames, we don't now the actual interval; so set it to the newgame value. */
3263 _settings_game.difficulty.competitors_interval = _settings_newgame.difficulty.competitors_interval;
3265 /* We did load the "period" of the timer, but not the fired/elapsed. We can deduce that here. */
3266 extern TimeoutTimer<TimerGameTick> _new_competitor_timeout;
3267 _new_competitor_timeout.storage.elapsed = 0;
3268 _new_competitor_timeout.fired = _new_competitor_timeout.period.value == 0;
3271 if (IsSavegameVersionBefore(SLV_NEWGRF_LAST_SERVICE)) {
3272 /* Set service date provided to NewGRF. */
3273 for (Vehicle *v : Vehicle::Iterate()) {
3274 v->date_of_last_service_newgrf = v->date_of_last_service.base();
3278 if (IsSavegameVersionBefore(SLV_SHIP_ACCELERATION)) {
3279 /* NewGRF acceleration information was added to ships. */
3280 for (Ship *s : Ship::Iterate()) {
3281 if (s->acceleration == 0) s->acceleration = ShipVehInfo(s->engine_type)->acceleration;
3285 if (IsSavegameVersionBefore(SLV_MAX_LOAN_FOR_COMPANY)) {
3286 for (Company *c : Company::Iterate()) {
3287 c->max_loan = COMPANY_MAX_LOAN_DEFAULT;
3291 if (IsSavegameVersionBefore(SLV_SCRIPT_RANDOMIZER)) {
3292 ScriptObject::InitializeRandomizers();
3295 if (IsSavegameVersionBefore(SLV_COMPANY_INAUGURATED_PERIOD)) {
3296 for (Company *c : Company::Iterate()) {
3297 c->inaugurated_year_calendar = _settings_game.game_creation.starting_year;
3301 for (Company *c : Company::Iterate()) {
3302 UpdateCompanyLiveries(c);
3305 /* Update free group numbers data for each company, required regardless of savegame version. */
3306 for (Group *g : Group::Iterate()) {
3307 Company *c = Company::Get(g->owner);
3308 if (IsSavegameVersionBefore(SLV_GROUP_NUMBERS)) {
3309 /* Use the index as group number when converting old savegames. */
3310 g->number = c->freegroups.UseID(g->index);
3311 } else {
3312 c->freegroups.UseID(g->number);
3316 AfterLoadLabelMaps();
3317 AfterLoadCompanyStats();
3318 AfterLoadStoryBook();
3320 _gamelog.PrintDebug(1);
3322 InitializeWindowsAndCaches();
3323 /* Restore the signals */
3324 ResetSignalHandlers();
3326 AfterLoadLinkGraphs();
3328 CheckGroundVehiclesAtCorrectZ();
3330 /* Start the scripts. This MUST happen after everything else except
3331 * starting a new company. */
3332 StartScripts();
3334 /* If Load Scenario / New (Scenario) Game is used,
3335 * a company does not exist yet. So create one here.
3336 * 1 exception: network-games. Those can have 0 companies
3337 * But this exception is not true for non-dedicated network servers! */
3338 if (!_networking || (_networking && _network_server && !_network_dedicated)) {
3339 CompanyID first_human_company = GetFirstPlayableCompanyID();
3340 if (!Company::IsValidID(first_human_company)) {
3341 Company *c = DoStartupNewCompany(false, first_human_company);
3342 c->settings = _settings_client.company;
3346 return true;
3350 * Reload all NewGRF files during a running game. This is a cut-down
3351 * version of AfterLoadGame().
3352 * XXX - We need to reset the vehicle position hash because with a non-empty
3353 * hash AfterLoadVehicles() will loop infinitely. We need AfterLoadVehicles()
3354 * to recalculate vehicle data as some NewGRF vehicle sets could have been
3355 * removed or added and changed statistics
3357 void ReloadNewGRFData()
3359 /* reload grf data */
3360 GfxLoadSprites();
3361 LoadStringWidthTable();
3362 RecomputePrices();
3363 /* reload vehicles */
3364 ResetVehicleHash();
3365 AfterLoadVehiclesPhase1(false);
3366 AfterLoadVehiclesPhase2(false);
3367 StartupEngines();
3368 GroupStatistics::UpdateAfterLoad();
3369 /* update station graphics */
3370 AfterLoadStations();
3371 /* Update company statistics. */
3372 AfterLoadCompanyStats();
3373 /* Check and update house and town values */
3374 UpdateHousesAndTowns();
3375 /* Delete news referring to no longer existing entities */
3376 DeleteInvalidEngineNews();
3377 /* Update livery selection windows */
3378 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i);
3379 /* Update company infrastructure counts. */
3380 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
3381 InvalidateWindowClassesData(WC_BUILD_TOOLBAR);
3382 /* redraw the whole screen */
3383 MarkWholeScreenDirty();
3384 CheckTrainsLengths();