OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

afterload.cpp
Go to the documentation of this file.
1 /* $Id: afterload.cpp 27320 2015-06-27 11:46:41Z frosch $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
9
12 #include "../stdafx.h"
13 #include "../void_map.h"
14 #include "../signs_base.h"
15 #include "../depot_base.h"
16 #include "../fios.h"
17 #include "../gamelog_internal.h"
18 #include "../network/network.h"
19 #include "../network/network_func.h"
20 #include "../gfxinit.h"
21 #include "../viewport_func.h"
22 #include "../industry.h"
23 #include "../clear_map.h"
24 #include "../vehicle_func.h"
25 #include "../string_func.h"
26 #include "../date_func.h"
27 #include "../roadveh.h"
28 #include "../train.h"
29 #include "../station_base.h"
30 #include "../waypoint_base.h"
31 #include "../roadstop_base.h"
32 #include "../tunnelbridge_map.h"
33 #include "../pathfinder/yapf/yapf_cache.h"
34 #include "../elrail_func.h"
35 #include "../signs_func.h"
36 #include "../aircraft.h"
37 #include "../object_map.h"
38 #include "../object_base.h"
39 #include "../tree_map.h"
40 #include "../company_func.h"
41 #include "../road_cmd.h"
42 #include "../ai/ai.hpp"
43 #include "../ai/ai_gui.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 "../engine_func.h"
51 #include "../rail_gui.h"
52 #include "../core/backup_type.hpp"
53 #include "../smallmap_gui.h"
54 #include "../news_func.h"
55 #include "../order_backup.h"
56 #include "../error.h"
57 #include "../disaster_vehicle.h"
58
59
60 #include "saveload_internal.h"
61
62 #include <signal.h>
63
64 #include "../safeguards.h"
65
66 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
67
78 void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
79 {
80 /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
81 * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
82 if (!IsTileFlat(t)) {
83 if (include_invalid_water_class) {
84 SetWaterClass(t, WATER_CLASS_INVALID);
85 return;
86 } else {
87 SlErrorCorrupt("Invalid water class for dry tile");
88 }
89 }
90
91 /* Mark tile dirty in all cases */
92 MarkTileDirtyByTile(t);
93
94 if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
95 /* tiles at map borders are always WATER_CLASS_SEA */
96 SetWaterClass(t, WATER_CLASS_SEA);
97 return;
98 }
99
100 bool has_water = false;
101 bool has_canal = false;
102 bool has_river = false;
103
104 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
105 TileIndex neighbour = TileAddByDiagDir(t, dir);
106 switch (GetTileType(neighbour)) {
107 case MP_WATER:
108 /* clear water and shipdepots have already a WaterClass associated */
109 if (IsCoast(neighbour)) {
110 has_water = true;
111 } else if (!IsLock(neighbour)) {
112 switch (GetWaterClass(neighbour)) {
113 case WATER_CLASS_SEA: has_water = true; break;
114 case WATER_CLASS_CANAL: has_canal = true; break;
115 case WATER_CLASS_RIVER: has_river = true; break;
116 default: SlErrorCorrupt("Invalid water class for tile");
117 }
118 }
119 break;
120
121 case MP_RAILWAY:
122 /* Shore or flooded halftile */
123 has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
124 break;
125
126 case MP_TREES:
127 /* trees on shore */
128 has_water |= (GB(_m[neighbour].m2, 4, 2) == TREE_GROUND_SHORE);
129 break;
130
131 default: break;
132 }
133 }
134
135 if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
136 SetWaterClass(t, WATER_CLASS_INVALID);
137 return;
138 }
139
140 if (has_river && !has_canal) {
141 SetWaterClass(t, WATER_CLASS_RIVER);
142 } else if (has_canal || !has_water) {
143 SetWaterClass(t, WATER_CLASS_CANAL);
144 } else {
145 SetWaterClass(t, WATER_CLASS_SEA);
146 }
147 }
148
149 static void ConvertTownOwner()
150 {
151 for (TileIndex tile = 0; tile != MapSize(); tile++) {
152 switch (GetTileType(tile)) {
153 case MP_ROAD:
154 if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
155 _m[tile].m3 = OWNER_TOWN;
156 }
157 /* FALL THROUGH */
158
159 case MP_TUNNELBRIDGE:
160 if (_m[tile].m1 & 0x80) SetTileOwner(tile, OWNER_TOWN);
161 break;
162
163 default: break;
164 }
165 }
166 }
167
168 /* since savegame version 4.1, exclusive transport rights are stored at towns */
169 static void UpdateExclusiveRights()
170 {
171 Town *t;
172
173 FOR_ALL_TOWNS(t) {
174 t->exclusivity = INVALID_COMPANY;
175 }
176
177 /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
178 * could be implemented this way:
179 * 1.) Go through all stations
180 * Build an array town_blocked[ town_id ][ company_id ]
181 * that stores if at least one station in that town is blocked for a company
182 * 2.) Go through that array, if you find a town that is not blocked for
183 * one company, but for all others, then give him exclusivity.
184 */
185 }
186
187 static const byte convert_currency[] = {
188 0, 1, 12, 8, 3,
189 10, 14, 19, 4, 5,
190 9, 11, 13, 6, 17,
191 16, 22, 21, 7, 15,
192 18, 2, 20,
193 };
194
195 /* since savegame version 4.2 the currencies are arranged differently */
196 static void UpdateCurrencies()
197 {
198 _settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
199 }
200
201 /* Up to revision 1413 the invisible tiles at the southern border have not been
202 * MP_VOID, even though they should have. This is fixed by this function
203 */
204 static void UpdateVoidTiles()
205 {
206 uint i;
207
208 for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
209 for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
210 }
211
212 static inline RailType UpdateRailType(RailType rt, RailType min)
213 {
214 return rt >= min ? (RailType)(rt + 1): rt;
215 }
216
220 void UpdateAllVirtCoords()
221 {
222 UpdateAllStationVirtCoords();
223 UpdateAllSignVirtCoords();
224 UpdateAllTownVirtCoords();
225 }
226
236 static void InitializeWindowsAndCaches()
237 {
238 /* Initialize windows */
239 ResetWindowSystem();
240 SetupColoursAndInitialWindow();
241
242 /* Update coordinates of the signs. */
243 UpdateAllVirtCoords();
244 ResetViewportAfterLoadGame();
245
246 Company *c;
247 FOR_ALL_COMPANIES(c) {
248 /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
249 * accordingly if it is not the case. No need to set it on companies that are not been used already,
250 * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
251 if (_file_to_saveload.filetype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
252 c->inaugurated_year = _cur_year;
253 }
254 }
255
256 /* Count number of objects per type */
257 Object *o;
258 FOR_ALL_OBJECTS(o) {
259 Object::IncTypeCount(o->type);
260 }
261
262 /* Identify owners of persistent storage arrays */
263 Industry *i;
264 FOR_ALL_INDUSTRIES(i) {
265 if (i->psa != NULL) {
266 i->psa->feature = GSF_INDUSTRIES;
267 i->psa->tile = i->location.tile;
268 }
269 }
270 Station *s;
271 FOR_ALL_STATIONS(s) {
272 if (s->airport.psa != NULL) {
273 s->airport.psa->feature = GSF_AIRPORTS;
274 s->airport.psa->tile = s->airport.tile;
275 }
276 }
277 Town *t;
278 FOR_ALL_TOWNS(t) {
279 for (std::list<PersistentStorage *>::iterator it = t->psa_list.begin(); it != t->psa_list.end(); ++it) {
280 (*it)->feature = GSF_FAKE_TOWNS;
281 (*it)->tile = t->xy;
282 }
283 }
284
285 RecomputePrices();
286
287 GroupStatistics::UpdateAfterLoad();
288
289 Station::RecomputeIndustriesNearForAll();
290 RebuildSubsidisedSourceAndDestinationCache();
291
292 /* Towns have a noise controlled number of airports system
293 * So each airport's noise value must be added to the town->noise_reached value
294 * Reset each town's noise_reached value to '0' before. */
295 UpdateAirportsNoise();
296
297 CheckTrainsLengths();
298 ShowNewGRFError();
299 ShowAIDebugWindowIfAIError();
300
301 /* Rebuild the smallmap list of owners. */
302 BuildOwnerLegend();
303 }
304
305 typedef void (CDECL *SignalHandlerPointer)(int);
306 static SignalHandlerPointer _prev_segfault = NULL;
307 static SignalHandlerPointer _prev_abort = NULL;
308 static SignalHandlerPointer _prev_fpe = NULL;
309
310 static void CDECL HandleSavegameLoadCrash(int signum);
311
316 static void SetSignalHandlers()
317 {
318 _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
319 _prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
320 _prev_fpe = signal(SIGFPE, HandleSavegameLoadCrash);
321 }
322
326 static void ResetSignalHandlers()
327 {
328 signal(SIGSEGV, _prev_segfault);
329 signal(SIGABRT, _prev_abort);
330 signal(SIGFPE, _prev_fpe);
331 }
332
338 static const GRFIdentifier *GetOverriddenIdentifier(const GRFConfig *c)
339 {
340 const LoggedAction *la = &_gamelog_action[_gamelog_actions - 1];
341 if (la->at != GLAT_LOAD) return &c->ident;
342
343 const LoggedChange *lcend = &la->change[la->changes];
344 for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
345 if (lc->ct == GLCT_GRFCOMPAT && lc->grfcompat.grfid == c->ident.grfid) return &lc->grfcompat;
346 }
347
348 return &c->ident;
349 }
350
352 static bool _saveload_crash_with_missing_newgrfs = false;
353
359 bool SaveloadCrashWithMissingNewGRFs()
360 {
361 return _saveload_crash_with_missing_newgrfs;
362 }
363
370 static void CDECL HandleSavegameLoadCrash(int signum)
371 {
372 ResetSignalHandlers();
373
374 char buffer[8192];
375 char *p = buffer;
376 p += seprintf(p, lastof(buffer), "Loading your savegame caused OpenTTD to crash.\n");
377
378 for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != NULL; c = c->next) {
379 _saveload_crash_with_missing_newgrfs = HasBit(c->flags, GCF_COMPATIBLE) || c->status == GCS_NOT_FOUND;
380 }
381
382 if (_saveload_crash_with_missing_newgrfs) {
383 p += seprintf(p, lastof(buffer),
384 "This is most likely caused by a missing NewGRF or a NewGRF that\n"
385 "has been loaded as replacement for a missing NewGRF. OpenTTD\n"
386 "cannot easily determine whether a replacement NewGRF is of a newer\n"
387 "or older version.\n"
388 "It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
389 "This means that if the author makes incompatible NewGRFs with the\n"
390 "same GRF ID OpenTTD cannot magically do the right thing. In most\n"
391 "cases OpenTTD will load the savegame and not crash, but this is an\n"
392 "exception.\n"
393 "Please load the savegame with the appropriate NewGRFs installed.\n"
394 "The missing/compatible NewGRFs are:\n");
395
396 for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
397 if (HasBit(c->flags, GCF_COMPATIBLE)) {
398 const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
399 char buf[40];
400 md5sumToString(buf, lastof(buf), replaced->md5sum);
401 p += seprintf(p, lastof(buffer), "NewGRF %08X (checksum %s) not found.\n Loaded NewGRF \"%s\" with same GRF ID instead.\n", BSWAP32(c->ident.grfid), buf, c->filename);
402 }
403 if (c->status == GCS_NOT_FOUND) {
404 char buf[40];
405 md5sumToString(buf, lastof(buf), c->ident.md5sum);
406 p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s.\n", BSWAP32(c->ident.grfid), c->filename, buf);
407 }
408 }
409 } else {
410 p += seprintf(p, lastof(buffer),
411 "This is probably caused by a corruption in the savegame.\n"
412 "Please file a bug report and attach this savegame.\n");
413 }
414
415 ShowInfo(buffer);
416
417 SignalHandlerPointer call = NULL;
418 switch (signum) {
419 case SIGSEGV: call = _prev_segfault; break;
420 case SIGABRT: call = _prev_abort; break;
421 case SIGFPE: call = _prev_fpe; break;
422 default: NOT_REACHED();
423 }
424 if (call != NULL) call(signum);
425 }
426
432 static void FixOwnerOfRailTrack(TileIndex t)
433 {
434 assert(!Company::IsValidID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
435
436 /* remove leftover rail piece from crossing (from very old savegames) */
437 Train *v = NULL, *w;
438 FOR_ALL_TRAINS(w) {
439 if (w->tile == t) {
440 v = w;
441 break;
442 }
443 }
444
445 if (v != NULL) {
446 /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
447 SetTileOwner(t, v->owner);
448 return;
449 }
450
451 /* try to find any connected rail */
452 for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
453 TileIndex tt = t + TileOffsByDiagDir(dd);
454 if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
455 GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
456 Company::IsValidID(GetTileOwner(tt))) {
457 SetTileOwner(t, GetTileOwner(tt));
458 return;
459 }
460 }
461
462 if (IsLevelCrossingTile(t)) {
463 /* else change the crossing to normal road (road vehicles won't care) */
464 MakeRoadNormal(t, GetCrossingRoadBits(t), GetRoadTypes(t), GetTownIndex(t),
465 GetRoadOwner(t, ROADTYPE_ROAD), GetRoadOwner(t, ROADTYPE_TRAM));
466 return;
467 }
468
469 /* if it's not a crossing, make it clean land */
470 MakeClear(t, CLEAR_GRASS, 0);
471 }
472
479 static uint FixVehicleInclination(Vehicle *v, Direction dir)
480 {
481 /* Compute place where this vehicle entered the tile */
482 int entry_x = v->x_pos;
483 int entry_y = v->y_pos;
484 switch (dir) {
485 case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
486 case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
487 case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
488 case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
489 case INVALID_DIR: break;
490 default: NOT_REACHED();
491 }
492 byte entry_z = GetSlopePixelZ(entry_x, entry_y);
493
494 /* Compute middle of the tile. */
495 int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
496 int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
497 byte middle_z = GetSlopePixelZ(middle_x, middle_y);
498
499 /* middle_z == entry_z, no height change. */
500 if (middle_z == entry_z) return 0;
501
502 /* middle_z < entry_z, we are going downwards. */
503 if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
504
505 /* middle_z > entry_z, we are going upwards. */
506 return 1U << GVF_GOINGUP_BIT;
507 }
508
515 static inline bool MayHaveBridgeAbove(TileIndex t)
516 {
517 return IsTileType(t, MP_CLEAR) || IsTileType(t, MP_RAILWAY) || IsTileType(t, MP_ROAD) ||
518 IsTileType(t, MP_WATER) || IsTileType(t, MP_TUNNELBRIDGE) || IsTileType(t, MP_OBJECT);
519 }
520
526 bool AfterLoadGame()
527 {
528 SetSignalHandlers();
529
530 TileIndex map_size = MapSize();
531
532 extern TileIndex _cur_tileloop_tile; // From landscape.cpp.
533 /* The LFSR used in RunTileLoop iteration cannot have a zeroed state, make it non-zeroed. */
534 if (_cur_tileloop_tile == 0) _cur_tileloop_tile = 1;
535
536 if (IsSavegameVersionBefore(98)) GamelogOldver();
537
538 GamelogTestRevision();
539 GamelogTestMode();
540
541 if (IsSavegameVersionBefore(98)) GamelogGRFAddList(_grfconfig);
542
543 if (IsSavegameVersionBefore(119)) {
544 _pause_mode = (_pause_mode == 2) ? PM_PAUSED_NORMAL : PM_UNPAUSED;
545 } else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
546 DEBUG(net, 0, "The loading savegame was paused due to an error state.");
547 DEBUG(net, 0, " The savegame cannot be used for multiplayer!");
548 /* Restore the signals */
549 ResetSignalHandlers();
550 return false;
551 } else if (!_networking || _network_server) {
552 /* If we are in single player, i.e. not networking, and loading the
553 * savegame or we are loading the savegame as network server we do
554 * not want to be bothered by being paused because of the automatic
555 * reason of a network server, e.g. joining clients or too few
556 * active clients. Note that resetting these values for a network
557 * client are very bad because then the client is going to execute
558 * the game loop when the server is not, i.e. it desyncs. */
559 _pause_mode &= ~PMB_PAUSED_NETWORK;
560 }
561
562 /* In very old versions, size of train stations was stored differently.
563 * They had swapped width and height if station was built along the Y axis.
564 * TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
565 * Because the data stored by TTDPatch are unusable for rail stations > 7x7,
566 * recompute the width and height. Doing this unconditionally for all old
567 * savegames simplifies the code. */
568 if (IsSavegameVersionBefore(2)) {
569 Station *st;
570 FOR_ALL_STATIONS(st) {
571 st->train_station.w = st->train_station.h = 0;
572 }
573 for (TileIndex t = 0; t < map_size; t++) {
574 if (!IsTileType(t, MP_STATION)) continue;
575 if (_m[t].m5 > 7) continue; // is it a rail station tile?
576 st = Station::Get(_m[t].m2);
577 assert(st->train_station.tile != 0);
578 int dx = TileX(t) - TileX(st->train_station.tile);
579 int dy = TileY(t) - TileY(st->train_station.tile);
580 assert(dx >= 0 && dy >= 0);
581 st->train_station.w = max<uint>(st->train_station.w, dx + 1);
582 st->train_station.h = max<uint>(st->train_station.h, dy + 1);
583 }
584 }
585
586 if (IsSavegameVersionBefore(194)) {
587 _settings_game.construction.max_heightlevel = 15;
588
589 /* In old savegame versions, the heightlevel was coded in bits 0..3 of the type field */
590 for (TileIndex t = 0; t < map_size; t++) {
591 _m[t].height = GB(_m[t].type, 0, 4);
592 SB(_m[t].type, 0, 2, GB(_me[t].m6, 0, 2));
593 SB(_me[t].m6, 0, 2, 0);
594 if (MayHaveBridgeAbove(t)) {
595 SB(_m[t].type, 2, 2, GB(_me[t].m6, 6, 2));
596 SB(_me[t].m6, 6, 2, 0);
597 } else {
598 SB(_m[t].type, 2, 2, 0);
599 }
600 }
601 }
602
603 /* in version 2.1 of the savegame, town owner was unified. */
604 if (IsSavegameVersionBefore(2, 1)) ConvertTownOwner();
605
606 /* from version 4.1 of the savegame, exclusive rights are stored at towns */
607 if (IsSavegameVersionBefore(4, 1)) UpdateExclusiveRights();
608
609 /* from version 4.2 of the savegame, currencies are in a different order */
610 if (IsSavegameVersionBefore(4, 2)) UpdateCurrencies();
611
612 /* In old version there seems to be a problem that water is owned by
613 * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
614 * (4.3) version, so I just check when versions are older, and then
615 * walk through the whole map.. */
616 if (IsSavegameVersionBefore(4, 3)) {
617 for (TileIndex t = 0; t < map_size; t++) {
618 if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
619 SetTileOwner(t, OWNER_WATER);
620 }
621 }
622 }
623
624 if (IsSavegameVersionBefore(84)) {
625 Company *c;
626 FOR_ALL_COMPANIES(c) {
627 c->name = CopyFromOldName(c->name_1);
628 if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
629 c->president_name = CopyFromOldName(c->president_name_1);
630 if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
631 }
632
633 Station *st;
634 FOR_ALL_STATIONS(st) {
635 st->name = CopyFromOldName(st->string_id);
636 /* generating new name would be too much work for little effect, use the station name fallback */
637 if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
638 }
639
640 Town *t;
641 FOR_ALL_TOWNS(t) {
642 t->name = CopyFromOldName(t->townnametype);
643 if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
644 }
645 }
646
647 /* From this point the old names array is cleared. */
648 ResetOldNames();
649
650 if (IsSavegameVersionBefore(106)) {
651 /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
652 Station *st;
653 FOR_ALL_STATIONS(st) {
654 if (st->airport.tile == 0) st->airport.tile = INVALID_TILE;
655 if (st->dock_tile == 0) st->dock_tile = INVALID_TILE;
656 if (st->train_station.tile == 0) st->train_station.tile = INVALID_TILE;
657 }
658
659 /* the same applies to Company::location_of_HQ */
660 Company *c;
661 FOR_ALL_COMPANIES(c) {
662 if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(4) && c->location_of_HQ == 0xFFFF)) {
663 c->location_of_HQ = INVALID_TILE;
664 }
665 }
666 }
667
668 /* convert road side to my format. */
669 if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
670
671 /* Check if all NewGRFs are present, we are very strict in MP mode */
672 GRFListCompatibility gcf_res = IsGoodGRFConfigList(_grfconfig);
673 for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
674 if (c->status == GCS_NOT_FOUND) {
675 GamelogGRFRemove(c->ident.grfid);
676 } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
677 GamelogGRFCompatible(&c->ident);
678 }
679 }
680
681 if (_networking && gcf_res != GLC_ALL_GOOD) {
682 SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
683 /* Restore the signals */
684 ResetSignalHandlers();
685 return false;
686 }
687
688 switch (gcf_res) {
689 case GLC_COMPATIBLE: ShowErrorMessage(STR_NEWGRF_COMPATIBLE_LOAD_WARNING, INVALID_STRING_ID, WL_CRITICAL); break;
690 case GLC_NOT_FOUND: ShowErrorMessage(STR_NEWGRF_DISABLED_WARNING, INVALID_STRING_ID, WL_CRITICAL); _pause_mode = PM_PAUSED_ERROR; break;
691 default: break;
692 }
693
694 /* The value of _date_fract got divided, so make sure that old games are converted correctly. */
695 if (IsSavegameVersionBefore(11, 1) || (IsSavegameVersionBefore(147) && _date_fract > DAY_TICKS)) _date_fract /= 885;
696
697 /* Update current year
698 * must be done before loading sprites as some newgrfs check it */
699 SetDate(_date, _date_fract);
700
701 /*
702 * Force the old behaviour for compatibility reasons with old savegames. As new
703 * settings can only be loaded from new savegames loading old savegames with new
704 * versions of OpenTTD will normally initialize settings newer than the savegame
705 * version with "new game" defaults which the player can define to their liking.
706 * For some settings we override that to keep the behaviour the same as when the
707 * game was saved.
708 *
709 * Note that there is no non-stop in here. This is because the setting could have
710 * either value in TTDPatch. To convert it properly the user has to make sure the
711 * right value has been chosen in the settings. Otherwise we will be converting
712 * it incorrectly in half of the times without a means to correct that.
713 */
714 if (IsSavegameVersionBefore(4, 2)) _settings_game.station.modified_catchment = false;
715 if (IsSavegameVersionBefore(6, 1)) _settings_game.pf.forbid_90_deg = false;
716 if (IsSavegameVersionBefore(21)) _settings_game.vehicle.train_acceleration_model = 0;
717 if (IsSavegameVersionBefore(90)) _settings_game.vehicle.plane_speed = 4;
718 if (IsSavegameVersionBefore(95)) _settings_game.vehicle.dynamic_engines = 0;
719 if (IsSavegameVersionBefore(96)) _settings_game.economy.station_noise_level = false;
720 if (IsSavegameVersionBefore(133)) {
721 _settings_game.vehicle.roadveh_acceleration_model = 0;
722 _settings_game.vehicle.train_slope_steepness = 3;
723 }
724 if (IsSavegameVersionBefore(134)) _settings_game.economy.feeder_payment_share = 75;
725 if (IsSavegameVersionBefore(138)) _settings_game.vehicle.plane_crashes = 2;
726 if (IsSavegameVersionBefore(139)) _settings_game.vehicle.roadveh_slope_steepness = 7;
727 if (IsSavegameVersionBefore(143)) _settings_game.economy.allow_town_level_crossings = true;
728 if (IsSavegameVersionBefore(159)) {
729 _settings_game.vehicle.max_train_length = 50;
730 _settings_game.construction.max_bridge_length = 64;
731 _settings_game.construction.max_tunnel_length = 64;
732 }
733 if (IsSavegameVersionBefore(166)) _settings_game.economy.infrastructure_maintenance = false;
734 if (IsSavegameVersionBefore(183)) {
735 _settings_game.linkgraph.distribution_pax = DT_MANUAL;
736 _settings_game.linkgraph.distribution_mail = DT_MANUAL;
737 _settings_game.linkgraph.distribution_armoured = DT_MANUAL;
738 _settings_game.linkgraph.distribution_default = DT_MANUAL;
739 }
740
741 /* Load the sprites */
742 GfxLoadSprites();
743 LoadStringWidthTable();
744
745 /* Copy temporary data to Engine pool */
746 CopyTempEngineData();
747
748 /* Connect front and rear engines of multiheaded trains and converts
749 * subtype to the new format */
750 if (IsSavegameVersionBefore(17, 1)) ConvertOldMultiheadToNew();
751
752 /* Connect front and rear engines of multiheaded trains */
753 ConnectMultiheadedTrains();
754
755 /* Fix the CargoPackets *and* fix the caches of CargoLists.
756 * If this isn't done before Stations and especially Vehicles are
757 * running their AfterLoad we might get in trouble. In the case of
758 * vehicles we could give the wrong (cached) count of items in a
759 * vehicle which causes different results when getting their caches
760 * filled; and that could eventually lead to desyncs. */
761 CargoPacket::AfterLoad();
762
763 /* Oilrig was moved from id 15 to 9. We have to do this conversion
764 * here as AfterLoadVehicles can check it indirectly via the newgrf
765 * code. */
766 if (IsSavegameVersionBefore(139)) {
767 Station *st;
768 FOR_ALL_STATIONS(st) {
769 if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
770 st->airport.type = AT_OILRIG;
771 }
772 }
773 }
774
775 /* Update all vehicles */
776 AfterLoadVehicles(true);
777
778 /* Make sure there is an AI attached to an AI company */
779 {
780 Company *c;
781 FOR_ALL_COMPANIES(c) {
782 if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
783 }
784 }
785
786 /* make sure there is a town in the game */
787 if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
788 SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
789 /* Restore the signals */
790 ResetSignalHandlers();
791 return false;
792 }
793
794 /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
795 * This problem appears in savegame version 21 too, see r3455. But after loading the
796 * savegame and saving again, the buggy map array could be converted to new savegame
797 * version. It didn't show up before r12070. */
798 if (IsSavegameVersionBefore(87)) UpdateVoidTiles();
799
800 /* If Load Scenario / New (Scenario) Game is used,
801 * a company does not exist yet. So create one here.
802 * 1 exception: network-games. Those can have 0 companies
803 * But this exception is not true for non-dedicated network servers! */
804 if (!Company::IsValidID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated))) {
805 DoStartupNewCompany(false);
806 Company *c = Company::Get(COMPANY_FIRST);
807 c->settings = _settings_client.company;
808 }
809
810 /* Fix the cache for cargo payments. */
811 CargoPayment *cp;
812 FOR_ALL_CARGO_PAYMENTS(cp) {
813 cp->front->cargo_payment = cp;
814 cp->current_station = cp->front->last_station_visited;
815 }
816
817 if (IsSavegameVersionBefore(72)) {
818 /* Locks in very old savegames had OWNER_WATER as owner */
819 for (TileIndex t = 0; t < MapSize(); t++) {
820 switch (GetTileType(t)) {
821 default: break;
822
823 case MP_WATER:
824 if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
825 break;
826
827 case MP_STATION: {
828 if (HasBit(_me[t].m6, 3)) SetBit(_me[t].m6, 2);
829 StationGfx gfx = GetStationGfx(t);
830 StationType st;
831 if ( IsInsideMM(gfx, 0, 8)) { // Rail station
832 st = STATION_RAIL;
833 SetStationGfx(t, gfx - 0);
834 } else if (IsInsideMM(gfx, 8, 67)) { // Airport
835 st = STATION_AIRPORT;
836 SetStationGfx(t, gfx - 8);
837 } else if (IsInsideMM(gfx, 67, 71)) { // Truck
838 st = STATION_TRUCK;
839 SetStationGfx(t, gfx - 67);
840 } else if (IsInsideMM(gfx, 71, 75)) { // Bus
841 st = STATION_BUS;
842 SetStationGfx(t, gfx - 71);
843 } else if (gfx == 75) { // Oil rig
844 st = STATION_OILRIG;
845 SetStationGfx(t, gfx - 75);
846 } else if (IsInsideMM(gfx, 76, 82)) { // Dock
847 st = STATION_DOCK;
848 SetStationGfx(t, gfx - 76);
849 } else if (gfx == 82) { // Buoy
850 st = STATION_BUOY;
851 SetStationGfx(t, gfx - 82);
852 } else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
853 st = STATION_AIRPORT;
854 SetStationGfx(t, gfx - 83 + 67 - 8);
855 } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
856 st = STATION_TRUCK;
857 SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
858 } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
859 st = STATION_BUS;
860 SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
861 } else {
862 /* Restore the signals */
863 ResetSignalHandlers();
864 return false;
865 }
866 SB(_me[t].m6, 3, 3, st);
867 break;
868 }
869 }
870 }
871 }
872
873 for (TileIndex t = 0; t < map_size; t++) {
874 switch (GetTileType(t)) {
875 case MP_STATION: {
876 BaseStation *bst = BaseStation::GetByTile(t);
877
878 /* Set up station spread */
879 bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
880
881 /* Waypoints don't have road stops/oil rigs in the old format */
882 if (!Station::IsExpected(bst)) break;
883 Station *st = Station::From(bst);
884
885 switch (GetStationType(t)) {
886 case STATION_TRUCK:
887 case STATION_BUS:
888 if (IsSavegameVersionBefore(6)) {
889 /* Before version 5 you could not have more than 250 stations.
890 * Version 6 adds large maps, so you could only place 253*253
891 * road stops on a map (no freeform edges) = 64009. So, yes
892 * someone could in theory create such a full map to trigger
893 * this assertion, it's safe to assume that's only something
894 * theoretical and does not happen in normal games. */
895 assert(RoadStop::CanAllocateItem());
896
897 /* From this version on there can be multiple road stops of the
898 * same type per station. Convert the existing stops to the new
899 * internal data structure. */
900 RoadStop *rs = new RoadStop(t);
901
902 RoadStop **head =
903 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
904 *head = rs;
905 }
906 break;
907
908 case STATION_OILRIG: {
909 /* Very old savegames sometimes have phantom oil rigs, i.e.
910 * an oil rig which got shut down, but not completely removed from
911 * the map
912 */
913 TileIndex t1 = TILE_ADDXY(t, 0, 1);
914 if (IsTileType(t1, MP_INDUSTRY) &&
915 GetIndustryGfx(t1) == GFX_OILRIG_1) {
916 /* The internal encoding of oil rigs was changed twice.
917 * It was 3 (till 2.2) and later 5 (till 5.1).
918 * Setting it unconditionally does not hurt.
919 */
920 Station::GetByTile(t)->airport.type = AT_OILRIG;
921 } else {
922 DeleteOilRig(t);
923 }
924 break;
925 }
926
927 default: break;
928 }
929 break;
930 }
931
932 default: break;
933 }
934 }
935
936 /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
937 * This has to be called after the oilrig airport_type update above ^^^ ! */
938 if (IsSavegameVersionBefore(2, 2)) UpdateOldAircraft();
939
940 /* In version 6.1 we put the town index in the map-array. To do this, we need
941 * to use m2 (16bit big), so we need to clean m2, and that is where this is
942 * all about ;) */
943 if (IsSavegameVersionBefore(6, 1)) {
944 for (TileIndex t = 0; t < map_size; t++) {
945 switch (GetTileType(t)) {
946 case MP_HOUSE:
947 _m[t].m4 = _m[t].m2;
948 SetTownIndex(t, CalcClosestTownFromTile(t)->index);
949 break;
950
951 case MP_ROAD:
952 _m[t].m4 |= (_m[t].m2 << 4);
953 if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
954 SetTownIndex(t, CalcClosestTownFromTile(t)->index);
955 } else {
956 SetTownIndex(t, 0);
957 }
958 break;
959
960 default: break;
961 }
962 }
963 }
964
965 /* Force the freeform edges to false for old savegames. */
966 if (IsSavegameVersionBefore(111)) {
967 _settings_game.construction.freeform_edges = false;
968 }
969
970 /* From version 9.0, we update the max passengers of a town (was sometimes negative
971 * before that. */
972 if (IsSavegameVersionBefore(9)) {
973 Town *t;
974 FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
975 }
976
977 /* From version 16.0, we included autorenew on engines, which are now saved, but
978 * of course, we do need to initialize them for older savegames. */
979 if (IsSavegameVersionBefore(16)) {
980 Company *c;
981 FOR_ALL_COMPANIES(c) {
982 c->engine_renew_list = NULL;
983 c->settings.engine_renew = false;
984 c->settings.engine_renew_months = 6;
985 c->settings.engine_renew_money = 100000;
986 }
987
988 /* When loading a game, _local_company is not yet set to the correct value.
989 * However, in a dedicated server we are a spectator, so nothing needs to
990 * happen. In case we are not a dedicated server, the local company always
991 * becomes company 0, unless we are in the scenario editor where all the
992 * companies are 'invalid'.
993 */
994 c = Company::GetIfValid(COMPANY_FIRST);
995 if (!_network_dedicated && c != NULL) {
996 c->settings = _settings_client.company;
997 }
998 }
999
1000 if (IsSavegameVersionBefore(48)) {
1001 for (TileIndex t = 0; t < map_size; t++) {
1002 switch (GetTileType(t)) {
1003 case MP_RAILWAY:
1004 if (IsPlainRail(t)) {
1005 /* Swap ground type and signal type for plain rail tiles, so the
1006 * ground type uses the same bits as for depots and waypoints. */
1007 uint tmp = GB(_m[t].m4, 0, 4);
1008 SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
1009 SB(_m[t].m2, 0, 4, tmp);
1010 } else if (HasBit(_m[t].m5, 2)) {
1011 /* Split waypoint and depot rail type and remove the subtype. */
1012 ClrBit(_m[t].m5, 2);
1013 ClrBit(_m[t].m5, 6);
1014 }
1015 break;
1016
1017 case MP_ROAD:
1018 /* Swap m3 and m4, so the track type for rail crossings is the
1019 * same as for normal rail. */
1020 Swap(_m[t].m3, _m[t].m4);
1021 break;
1022
1023 default: break;
1024 }
1025 }
1026 }
1027
1028 if (IsSavegameVersionBefore(61)) {
1029 /* Added the RoadType */
1030 bool old_bridge = IsSavegameVersionBefore(42);
1031 for (TileIndex t = 0; t < map_size; t++) {
1032 switch (GetTileType(t)) {
1033 case MP_ROAD:
1034 SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
1035 switch (GetRoadTileType(t)) {
1036 default: SlErrorCorrupt("Invalid road tile type");
1037 case ROAD_TILE_NORMAL:
1038 SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
1039 SB(_m[t].m4, 4, 4, 0);
1040 SB(_me[t].m6, 2, 4, 0);
1041 break;
1042 case ROAD_TILE_CROSSING:
1043 SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
1044 break;
1045 case ROAD_TILE_DEPOT: break;
1046 }
1047 SetRoadTypes(t, ROADTYPES_ROAD);
1048 break;
1049
1050 case MP_STATION:
1051 if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
1052 break;
1053
1054 case MP_TUNNELBRIDGE:
1055 /* Middle part of "old" bridges */
1056 if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
1057 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1058 SetRoadTypes(t, ROADTYPES_ROAD);
1059 }
1060 break;
1061
1062 default: break;
1063 }
1064 }
1065 }
1066
1067 if (IsSavegameVersionBefore(114)) {
1068 bool fix_roadtypes = !IsSavegameVersionBefore(61);
1069 bool old_bridge = IsSavegameVersionBefore(42);
1070
1071 for (TileIndex t = 0; t < map_size; t++) {
1072 switch (GetTileType(t)) {
1073 case MP_ROAD:
1074 if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
1075 SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
1076 switch (GetRoadTileType(t)) {
1077 default: SlErrorCorrupt("Invalid road tile type");
1078 case ROAD_TILE_NORMAL:
1079 SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
1080 SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
1081 SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4)); // tram bits
1082 SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
1083 SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4)); // road bits
1084 break;
1085
1086 case ROAD_TILE_CROSSING:
1087 SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
1088 SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
1089 SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
1090 SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1)); // road axis
1091 SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1)); // crossing state
1092 break;
1093
1094 case ROAD_TILE_DEPOT:
1095 break;
1096 }
1097 if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1098 const Town *town = CalcClosestTownFromTile(t);
1099 if (town != NULL) SetTownIndex(t, town->index);
1100 }
1101 _m[t].m4 = 0;
1102 break;
1103
1104 case MP_STATION:
1105 if (!IsRoadStop(t)) break;
1106
1107 if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
1108 SB(_me[t].m7, 0, 5, HasBit(_me[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
1109 SB(_m[t].m3, 4, 4, _m[t].m1);
1110 _m[t].m4 = 0;
1111 break;
1112
1113 case MP_TUNNELBRIDGE:
1114 if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
1115 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1116 if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
1117
1118 Owner o = GetTileOwner(t);
1119 SB(_me[t].m7, 0, 5, o); // road owner
1120 SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
1121 }
1122 SB(_me[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
1123 SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
1124
1125 _m[t].m2 = 0;
1126 _m[t].m4 = 0;
1127 break;
1128
1129 default: break;
1130 }
1131 }
1132 }
1133
1134 if (IsSavegameVersionBefore(42)) {
1135 Vehicle *v;
1136
1137 for (TileIndex t = 0; t < map_size; t++) {
1138 if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
1139 if (IsBridgeTile(t)) {
1140 if (HasBit(_m[t].m5, 6)) { // middle part
1141 Axis axis = (Axis)GB(_m[t].m5, 0, 1);
1142
1143 if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
1144 if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
1145 MakeRailNormal(
1146 t,
1147 GetTileOwner(t),
1148 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
1149 GetRailType(t)
1150 );
1151 } else {
1152 TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
1153
1154 MakeRoadNormal(
1155 t,
1156 axis == AXIS_X ? ROAD_Y : ROAD_X,
1157 ROADTYPES_ROAD,
1158 town,
1159 GetTileOwner(t), OWNER_NONE
1160 );
1161 }
1162 } else {
1163 if (GB(_m[t].m5, 3, 2) == 0) {
1164 MakeClear(t, CLEAR_GRASS, 3);
1165 } else {
1166 if (!IsTileFlat(t)) {
1167 MakeShore(t);
1168 } else {
1169 if (GetTileOwner(t) == OWNER_WATER) {
1170 MakeSea(t);
1171 } else {
1172 MakeCanal(t, GetTileOwner(t), Random());
1173 }
1174 }
1175 }
1176 }
1177 SetBridgeMiddle(t, axis);
1178 } else { // ramp
1179 Axis axis = (Axis)GB(_m[t].m5, 0, 1);
1180 uint north_south = GB(_m[t].m5, 5, 1);
1181 DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
1182 TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
1183
1184 _m[t].m5 = 1 << 7 | type << 2 | dir;
1185 }
1186 }
1187 }
1188
1189 FOR_ALL_VEHICLES(v) {
1190 if (!v->IsGroundVehicle()) continue;
1191 if (IsBridgeTile(v->tile)) {
1192 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
1193
1194 if (dir != DirToDiagDir(v->direction)) continue;
1195 switch (dir) {
1196 default: SlErrorCorrupt("Invalid vehicle direction");
1197 case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
1198 case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
1199 case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
1200 case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
1201 }
1202 } else if (v->z_pos > GetSlopePixelZ(v->x_pos, v->y_pos)) {
1203 v->tile = GetNorthernBridgeEnd(v->tile);
1204 } else {
1205 continue;
1206 }
1207 if (v->type == VEH_TRAIN) {
1208 Train::From(v)->track = TRACK_BIT_WORMHOLE;
1209 } else {
1210 RoadVehicle::From(v)->state = RVSB_WORMHOLE;
1211 }
1212 }
1213 }
1214
1215 /* Elrails got added in rev 24 */
1216 if (IsSavegameVersionBefore(24)) {
1217 RailType min_rail = RAILTYPE_ELECTRIC;
1218
1219 Train *v;
1220 FOR_ALL_TRAINS(v) {
1221 RailType rt = RailVehInfo(v->engine_type)->railtype;
1222
1223 v->railtype = rt;
1224 if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
1225 }
1226
1227 /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
1228 for (TileIndex t = 0; t < map_size; t++) {
1229 switch (GetTileType(t)) {
1230 case MP_RAILWAY:
1231 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1232 break;
1233
1234 case MP_ROAD:
1235 if (IsLevelCrossing(t)) {
1236 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1237 }
1238 break;
1239
1240 case MP_STATION:
1241 if (HasStationRail(t)) {
1242 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1243 }
1244 break;
1245
1246 case MP_TUNNELBRIDGE:
1247 if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
1248 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1249 }
1250 break;
1251
1252 default:
1253 break;
1254 }
1255 }
1256
1257 FOR_ALL_TRAINS(v) {
1258 if (v->IsFrontEngine() || v->IsFreeWagon()) v->ConsistChanged(CCF_TRACK);
1259 }
1260
1261 }
1262
1263 /* In version 16.1 of the savegame a company can decide if trains, which get
1264 * replaced, shall keep their old length. In all prior versions, just default
1265 * to false */
1266 if (IsSavegameVersionBefore(16, 1)) {
1267 Company *c;
1268 FOR_ALL_COMPANIES(c) c->settings.renew_keep_length = false;
1269 }
1270
1271 if (IsSavegameVersionBefore(123)) {
1272 /* Waypoints became subclasses of stations ... */
1273 MoveWaypointsToBaseStations();
1274 /* ... and buoys were moved to waypoints. */
1275 MoveBuoysToWaypoints();
1276 }
1277
1278 /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
1279 * room for PBS. Now in version 21 move it back :P. */
1280 if (IsSavegameVersionBefore(21) && !IsSavegameVersionBefore(15)) {
1281 for (TileIndex t = 0; t < map_size; t++) {
1282 switch (GetTileType(t)) {
1283 case MP_RAILWAY:
1284 if (HasSignals(t)) {
1285 /* Original signal type/variant was stored in m4 but since saveload
1286 * version 48 they are in m2. The bits has been already moved to m2
1287 * (see the code somewhere above) so don't use m4, use m2 instead. */
1288
1289 /* convert PBS signals to combo-signals */
1290 if (HasBit(_m[t].m2, 2)) SB(_m[t].m2, 0, 2, SIGTYPE_COMBO);
1291
1292 /* move the signal variant back */
1293 SB(_m[t].m2, 2, 1, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1294 ClrBit(_m[t].m2, 3);
1295 }
1296
1297 /* Clear PBS reservation on track */
1298 if (!IsRailDepotTile(t)) {
1299 SB(_m[t].m4, 4, 4, 0);
1300 } else {
1301 ClrBit(_m[t].m3, 6);
1302 }
1303 break;
1304
1305 case MP_STATION: // Clear PBS reservation on station
1306 ClrBit(_m[t].m3, 6);
1307 break;
1308
1309 default: break;
1310 }
1311 }
1312 }
1313
1314 if (IsSavegameVersionBefore(25)) {
1315 RoadVehicle *rv;
1316 FOR_ALL_ROADVEHICLES(rv) {
1317 rv->vehstatus &= ~0x40;
1318 }
1319 }
1320
1321 if (IsSavegameVersionBefore(26)) {
1322 Station *st;
1323 FOR_ALL_STATIONS(st) {
1324 st->last_vehicle_type = VEH_INVALID;
1325 }
1326 }
1327
1328 YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
1329
1330 if (IsSavegameVersionBefore(34)) {
1331 Company *c;
1332 FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
1333 }
1334
1335 Company *c;
1336 FOR_ALL_COMPANIES(c) {
1337 c->avail_railtypes = GetCompanyRailtypes(c->index);
1338 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
1339 }
1340
1341 if (!IsSavegameVersionBefore(27)) AfterLoadStations();
1342
1343 /* Time starts at 0 instead of 1920.
1344 * Account for this in older games by adding an offset */
1345 if (IsSavegameVersionBefore(31)) {
1346 Station *st;
1347 Waypoint *wp;
1348 Engine *e;
1349 Industry *i;
1350 Vehicle *v;
1351
1352 _date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1353 _cur_year += ORIGINAL_BASE_YEAR;
1354
1355 FOR_ALL_STATIONS(st) st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1356 FOR_ALL_WAYPOINTS(wp) wp->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1357 FOR_ALL_ENGINES(e) e->intro_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1358 FOR_ALL_COMPANIES(c) c->inaugurated_year += ORIGINAL_BASE_YEAR;
1359 FOR_ALL_INDUSTRIES(i) i->last_prod_year += ORIGINAL_BASE_YEAR;
1360
1361 FOR_ALL_VEHICLES(v) {
1362 v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
1363 v->build_year += ORIGINAL_BASE_YEAR;
1364 }
1365 }
1366
1367 /* From 32 on we save the industry who made the farmland.
1368 * To give this prettiness to old savegames, we remove all farmfields and
1369 * plant new ones. */
1370 if (IsSavegameVersionBefore(32)) {
1371 Industry *i;
1372
1373 for (TileIndex t = 0; t < map_size; t++) {
1374 if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
1375 /* remove fields */
1376 MakeClear(t, CLEAR_GRASS, 3);
1377 }
1378 }
1379
1380 FOR_ALL_INDUSTRIES(i) {
1381 uint j;
1382
1383 if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
1384 for (j = 0; j != 50; j++) PlantRandomFarmField(i);
1385 }
1386 }
1387 }
1388
1389 /* Setting no refit flags to all orders in savegames from before refit in orders were added */
1390 if (IsSavegameVersionBefore(36)) {
1391 Order *order;
1392 Vehicle *v;
1393
1394 FOR_ALL_ORDERS(order) {
1395 order->SetRefit(CT_NO_REFIT);
1396 }
1397
1398 FOR_ALL_VEHICLES(v) {
1399 v->current_order.SetRefit(CT_NO_REFIT);
1400 }
1401 }
1402
1403 /* from version 38 we have optional elrails, since we cannot know the
1404 * preference of a user, let elrails enabled; it can be disabled manually */
1405 if (IsSavegameVersionBefore(38)) _settings_game.vehicle.disable_elrails = false;
1406 /* do the same as when elrails were enabled/disabled manually just now */
1407 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
1408 InitializeRailGUI();
1409
1410 /* From version 53, the map array was changed for house tiles to allow
1411 * space for newhouses grf features. A new byte, m7, was also added. */
1412 if (IsSavegameVersionBefore(53)) {
1413 for (TileIndex t = 0; t < map_size; t++) {
1414 if (IsTileType(t, MP_HOUSE)) {
1415 if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
1416 /* Move the construction stage from m3[7..6] to m5[5..4].
1417 * The construction counter does not have to move. */
1418 SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
1419 SB(_m[t].m3, 6, 2, 0);
1420
1421 /* The "house is completed" bit is now in m6[2]. */
1422 SetHouseCompleted(t, false);
1423 } else {
1424 /* The "lift has destination" bit has been moved from
1425 * m5[7] to m7[0]. */
1426 SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
1427 ClrBit(_m[t].m5, 7);
1428
1429 /* The "lift is moving" bit has been removed, as it does
1430 * the same job as the "lift has destination" bit. */
1431 ClrBit(_m[t].m1, 7);
1432
1433 /* The position of the lift goes from m1[7..0] to m6[7..2],
1434 * making m1 totally free, now. The lift position does not
1435 * have to be a full byte since the maximum value is 36. */
1436 SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
1437
1438 _m[t].m1 = 0;
1439 _m[t].m3 = 0;
1440 SetHouseCompleted(t, true);
1441 }
1442 }
1443 }
1444 }
1445
1446 /* Check and update house and town values */
1447 UpdateHousesAndTowns();
1448
1449 if (IsSavegameVersionBefore(43)) {
1450 for (TileIndex t = 0; t < map_size; t++) {
1451 if (IsTileType(t, MP_INDUSTRY)) {
1452 switch (GetIndustryGfx(t)) {
1453 case GFX_POWERPLANT_SPARKS:
1454 _m[t].m3 = GB(_m[t].m1, 2, 5);
1455 break;
1456
1457 case GFX_OILWELL_ANIMATED_1:
1458 case GFX_OILWELL_ANIMATED_2:
1459 case GFX_OILWELL_ANIMATED_3:
1460 _m[t].m3 = GB(_m[t].m1, 0, 2);
1461 break;
1462
1463 case GFX_COAL_MINE_TOWER_ANIMATED:
1464 case GFX_COPPER_MINE_TOWER_ANIMATED:
1465 case GFX_GOLD_MINE_TOWER_ANIMATED:
1466 _m[t].m3 = _m[t].m1;
1467 break;
1468
1469 default: // No animation states to change
1470 break;
1471 }
1472 }
1473 }
1474 }
1475
1476 if (IsSavegameVersionBefore(45)) {
1477 Vehicle *v;
1478 /* Originally just the fact that some cargo had been paid for was
1479 * stored to stop people cheating and cashing in several times. This
1480 * wasn't enough though as it was cleared when the vehicle started
1481 * loading again, even if it didn't actually load anything, so now the
1482 * amount that has been paid is stored. */
1483 FOR_ALL_VEHICLES(v) {
1484 ClrBit(v->vehicle_flags, 2);
1485 }
1486 }
1487
1488 /* Buoys do now store the owner of the previous water tile, which can never
1489 * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
1490 if (IsSavegameVersionBefore(46)) {
1491 Waypoint *wp;
1492 FOR_ALL_WAYPOINTS(wp) {
1493 if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
1494 }
1495 }
1496
1497 if (IsSavegameVersionBefore(50)) {
1498 Aircraft *v;
1499 /* Aircraft units changed from 8 mph to 1 km-ish/h */
1500 FOR_ALL_AIRCRAFT(v) {
1501 if (v->subtype <= AIR_AIRCRAFT) {
1502 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
1503 v->cur_speed *= 128;
1504 v->cur_speed /= 10;
1505 v->acceleration = avi->acceleration;
1506 }
1507 }
1508 }
1509
1510 if (IsSavegameVersionBefore(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
1511
1512 if (IsSavegameVersionBefore(52)) {
1513 for (TileIndex t = 0; t < map_size; t++) {
1514 if (IsTileType(t, MP_OBJECT) && _m[t].m5 == OBJECT_STATUE) {
1515 _m[t].m2 = CalcClosestTownFromTile(t)->index;
1516 }
1517 }
1518 }
1519
1520 /* A setting containing the proportion of towns that grow twice as
1521 * fast was added in version 54. From version 56 this is now saved in the
1522 * town as cities can be built specifically in the scenario editor. */
1523 if (IsSavegameVersionBefore(56)) {
1524 Town *t;
1525
1526 FOR_ALL_TOWNS(t) {
1527 if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
1528 t->larger_town = true;
1529 }
1530 }
1531 }
1532
1533 if (IsSavegameVersionBefore(57)) {
1534 Vehicle *v;
1535 /* Added a FIFO queue of vehicles loading at stations */
1536 FOR_ALL_VEHICLES(v) {
1537 if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) && // for all locs
1538 !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
1539 v->current_order.IsType(OT_LOADING)) { // loading
1540 Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
1541
1542 /* The loading finished flag is *only* set when actually completely
1543 * finished. Because the vehicle is loading, it is not finished. */
1544 ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
1545 }
1546 }
1547 } else if (IsSavegameVersionBefore(59)) {
1548 /* For some reason non-loading vehicles could be in the station's loading vehicle list */
1549
1550 Station *st;
1551 FOR_ALL_STATIONS(st) {
1552 std::list<Vehicle *>::iterator iter;
1553 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
1554 Vehicle *v = *iter;
1555 iter++;
1556 if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
1557 }
1558 }
1559 }
1560
1561 if (IsSavegameVersionBefore(58)) {
1562 /* Setting difficulty industry_density other than zero get bumped to +1
1563 * since a new option (very low at position 1) has been added */
1564 if (_settings_game.difficulty.industry_density > 0) {
1565 _settings_game.difficulty.industry_density++;
1566 }
1567
1568 /* Same goes for number of towns, although no test is needed, just an increment */
1569 _settings_game.difficulty.number_towns++;
1570 }
1571
1572 if (IsSavegameVersionBefore(64)) {
1573 /* Since now we allow different signal types and variants on a single tile.
1574 * Move signal states to m4 to make room and clone the signal type/variant. */
1575 for (TileIndex t = 0; t < map_size; t++) {
1576 if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
1577 /* move signal states */
1578 SetSignalStates(t, GB(_m[t].m2, 4, 4));
1579 SB(_m[t].m2, 4, 4, 0);
1580 /* clone signal type and variant */
1581 SB(_m[t].m2, 4, 3, GB(_m[t].m2, 0, 3));
1582 }
1583 }
1584 }
1585
1586 if (IsSavegameVersionBefore(69)) {
1587 /* In some old savegames a bit was cleared when it should not be cleared */
1588 RoadVehicle *rv;
1589 FOR_ALL_ROADVEHICLES(rv) {
1590 if (rv->state == 250 || rv->state == 251) {
1591 SetBit(rv->state, 2);
1592 }
1593 }
1594 }
1595
1596 if (IsSavegameVersionBefore(70)) {
1597 /* Added variables to support newindustries */
1598 Industry *i;
1599 FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
1600 }
1601
1602 /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
1603 Replace the owner for those by OWNER_NONE. */
1604 if (IsSavegameVersionBefore(82)) {
1605 for (TileIndex t = 0; t < map_size; t++) {
1606 if (IsTileType(t, MP_WATER) &&
1607 GetWaterTileType(t) == WATER_TILE_CLEAR &&
1608 GetTileOwner(t) == OWNER_WATER &&
1609 TileHeight(t) != 0) {
1610 SetTileOwner(t, OWNER_NONE);
1611 }
1612 }
1613 }
1614
1615 /*
1616 * Add the 'previous' owner to the ship depots so we can reset it with
1617 * the correct values when it gets destroyed. This prevents that
1618 * someone can remove canals owned by somebody else and it prevents
1619 * making floods using the removal of ship depots.
1620 */
1621 if (IsSavegameVersionBefore(83)) {
1622 for (TileIndex t = 0; t < map_size; t++) {
1623 if (IsShipDepotTile(t)) {
1624 _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
1625 }
1626 }
1627 }
1628
1629 if (IsSavegameVersionBefore(74)) {
1630 Station *st;
1631 FOR_ALL_STATIONS(st) {
1632 for (CargoID c = 0; c < NUM_CARGO; c++) {
1633 st->goods[c].last_speed = 0;
1634 if (st->goods[c].cargo.AvailableCount() != 0) SetBit(st->goods[c].status, GoodsEntry::GES_RATING);
1635 }
1636 }
1637 }
1638
1639 if (IsSavegameVersionBefore(78)) {
1640 Industry *i;
1641 uint j;
1642 FOR_ALL_INDUSTRIES(i) {
1643 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1644 for (j = 0; j < lengthof(i->produced_cargo); j++) {
1645 i->produced_cargo[j] = indsp->produced_cargo[j];
1646 }
1647 for (j = 0; j < lengthof(i->accepts_cargo); j++) {
1648 i->accepts_cargo[j] = indsp->accepts_cargo[j];
1649 }
1650 }
1651 }
1652
1653 /* Before version 81, the density of grass was always stored as zero, and
1654 * grassy trees were always drawn fully grassy. Furthermore, trees on rough
1655 * land used to have zero density, now they have full density. Therefore,
1656 * make all grassy/rough land trees have a density of 3. */
1657 if (IsSavegameVersionBefore(81)) {
1658 for (TileIndex t = 0; t < map_size; t++) {
1659 if (GetTileType(t) == MP_TREES) {
1660 TreeGround groundType = (TreeGround)GB(_m[t].m2, 4, 2);
1661 if (groundType != TREE_GROUND_SNOW_DESERT) SB(_m[t].m2, 6, 2, 3);
1662 }
1663 }
1664 }
1665
1666
1667 if (IsSavegameVersionBefore(93)) {
1668 /* Rework of orders. */
1669 Order *order;
1670 FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
1671
1672 Vehicle *v;
1673 FOR_ALL_VEHICLES(v) {
1674 if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && v->orders.list->GetFirstOrder()->IsType(OT_NOTHING)) {
1675 v->orders.list->FreeChain();
1676 v->orders.list = NULL;
1677 }
1678
1679 v->current_order.ConvertFromOldSavegame();
1680 if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
1681 FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
1682 }
1683 }
1684 } else if (IsSavegameVersionBefore(94)) {
1685 /* Unload and transfer are now mutual exclusive. */
1686 Order *order;
1687 FOR_ALL_ORDERS(order) {
1688 if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1689 order->SetUnloadType(OUFB_TRANSFER);
1690 order->SetLoadType(OLFB_NO_LOAD);
1691 }
1692 }
1693
1694 Vehicle *v;
1695 FOR_ALL_VEHICLES(v) {
1696 if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1697 v->current_order.SetUnloadType(OUFB_TRANSFER);
1698 v->current_order.SetLoadType(OLFB_NO_LOAD);
1699 }
1700 }
1701 }
1702
1703 if (IsSavegameVersionBefore(84)) {
1704 /* Set all share owners to INVALID_COMPANY for
1705 * 1) all inactive companies
1706 * (when inactive companies were stored in the savegame - TTD, TTDP and some
1707 * *really* old revisions of OTTD; else it is already set in InitializeCompanies())
1708 * 2) shares that are owned by inactive companies or self
1709 * (caused by cheating clients in earlier revisions) */
1710 FOR_ALL_COMPANIES(c) {
1711 for (uint i = 0; i < 4; i++) {
1712 CompanyID company = c->share_owners[i];
1713 if (company == INVALID_COMPANY) continue;
1714 if (!Company::IsValidID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
1715 }
1716 }
1717 }
1718
1719 /* The water class was moved/unified. */
1720 if (IsSavegameVersionBefore(146)) {
1721 for (TileIndex t = 0; t < map_size; t++) {
1722 switch (GetTileType(t)) {
1723 case MP_STATION:
1724 switch (GetStationType(t)) {
1725 case STATION_OILRIG:
1726 case STATION_DOCK:
1727 case STATION_BUOY:
1728 SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
1729 SB(_m[t].m3, 0, 2, 0);
1730 break;
1731
1732 default:
1733 SetWaterClass(t, WATER_CLASS_INVALID);
1734 break;
1735 }
1736 break;
1737
1738 case MP_WATER:
1739 SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
1740 SB(_m[t].m3, 0, 2, 0);
1741 break;
1742
1743 case MP_OBJECT:
1744 SetWaterClass(t, WATER_CLASS_INVALID);
1745 break;
1746
1747 default:
1748 /* No water class. */
1749 break;
1750 }
1751 }
1752 }
1753
1754 if (IsSavegameVersionBefore(86)) {
1755 for (TileIndex t = 0; t < map_size; t++) {
1756 /* Move river flag and update canals to use water class */
1757 if (IsTileType(t, MP_WATER)) {
1758 if (GetWaterClass(t) != WATER_CLASS_RIVER) {
1759 if (IsWater(t)) {
1760 Owner o = GetTileOwner(t);
1761 if (o == OWNER_WATER) {
1762 MakeSea(t);
1763 } else {
1764 MakeCanal(t, o, Random());
1765 }
1766 } else if (IsShipDepot(t)) {
1767 Owner o = (Owner)_m[t].m4; // Original water owner
1768 SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
1769 }
1770 }
1771 }
1772 }
1773
1774 /* Update locks, depots, docks and buoys to have a water class based
1775 * on its neighbouring tiles. Done after river and canal updates to
1776 * ensure neighbours are correct. */
1777 for (TileIndex t = 0; t < map_size; t++) {
1778 if (!IsTileFlat(t)) continue;
1779
1780 if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
1781 if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
1782 }
1783 }
1784
1785 if (IsSavegameVersionBefore(87)) {
1786 for (TileIndex t = 0; t < map_size; t++) {
1787 /* skip oil rigs at borders! */
1788 if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
1789 (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
1790 /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
1791 * This conversion has to be done before buoys with invalid owner are removed. */
1792 SetWaterClass(t, WATER_CLASS_SEA);
1793 }
1794
1795 if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
1796 Owner o = GetTileOwner(t);
1797 if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
1798 Backup<CompanyByte> cur_company(_current_company, o, FILE_LINE);
1799 ChangeTileOwner(t, o, INVALID_OWNER);
1800 cur_company.Restore();
1801 }
1802 if (IsBuoyTile(t)) {
1803 /* reset buoy owner to OWNER_NONE in the station struct
1804 * (even if it is owned by active company) */
1805 Waypoint::GetByTile(t)->owner = OWNER_NONE;
1806 }
1807 } else if (IsTileType(t, MP_ROAD)) {
1808 /* works for all RoadTileType */
1809 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
1810 /* update even non-existing road types to update tile owner too */
1811 Owner o = GetRoadOwner(t, rt);
1812 if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rt, OWNER_NONE);
1813 }
1814 if (IsLevelCrossing(t)) {
1815 if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
1816 }
1817 } else if (IsPlainRailTile(t)) {
1818 if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
1819 }
1820 }
1821
1822 /* Convert old PF settings to new */
1823 if (_settings_game.pf.yapf.rail_use_yapf || IsSavegameVersionBefore(28)) {
1824 _settings_game.pf.pathfinder_for_trains = VPF_YAPF;
1825 } else {
1826 _settings_game.pf.pathfinder_for_trains = VPF_NPF;
1827 }
1828
1829 if (_settings_game.pf.yapf.road_use_yapf || IsSavegameVersionBefore(28)) {
1830 _settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
1831 } else {
1832 _settings_game.pf.pathfinder_for_roadvehs = VPF_NPF;
1833 }
1834
1835 if (_settings_game.pf.yapf.ship_use_yapf) {
1836 _settings_game.pf.pathfinder_for_ships = VPF_YAPF;
1837 } else {
1838 _settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
1839 }
1840 }
1841
1842 if (IsSavegameVersionBefore(88)) {
1843 /* Profits are now with 8 bit fract */
1844 Vehicle *v;
1845 FOR_ALL_VEHICLES(v) {
1846 v->profit_this_year <<= 8;
1847 v->profit_last_year <<= 8;
1848 v->running_ticks = 0;
1849 }
1850 }
1851
1852 if (IsSavegameVersionBefore(91)) {
1853 /* Increase HouseAnimationFrame from 5 to 7 bits */
1854 for (TileIndex t = 0; t < map_size; t++) {
1855 if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
1856 SB(_me[t].m6, 2, 6, GB(_me[t].m6, 3, 5));
1857 SB(_m[t].m3, 5, 1, 0);
1858 }
1859 }
1860 }
1861
1862 if (IsSavegameVersionBefore(62)) {
1863 /* Remove all trams from savegames without tram support.
1864 * There would be trams without tram track under causing crashes sooner or later. */
1865 RoadVehicle *v;
1866 FOR_ALL_ROADVEHICLES(v) {
1867 if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
1868 ShowErrorMessage(STR_WARNING_LOADGAME_REMOVED_TRAMS, INVALID_STRING_ID, WL_CRITICAL);
1869 delete v;
1870 }
1871 }
1872 }
1873
1874 if (IsSavegameVersionBefore(99)) {
1875 for (TileIndex t = 0; t < map_size; t++) {
1876 /* Set newly introduced WaterClass of industry tiles */
1877 if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
1878 SetWaterClassDependingOnSurroundings(t, true);
1879 }
1880 if (IsTileType(t, MP_INDUSTRY)) {
1881 if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
1882 SetWaterClassDependingOnSurroundings(t, true);
1883 } else {
1884 SetWaterClass(t, WATER_CLASS_INVALID);
1885 }
1886 }
1887
1888 /* Replace "house construction year" with "house age" */
1889 if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
1890 _m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
1891 }
1892 }
1893 }
1894
1895 /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
1896 * format here, as an old layout wouldn't work properly anyway. To be safe, we
1897 * clear any possible PBS reservations as well. */
1898 if (IsSavegameVersionBefore(100)) {
1899 for (TileIndex t = 0; t < map_size; t++) {
1900 switch (GetTileType(t)) {
1901 case MP_RAILWAY:
1902 if (HasSignals(t)) {
1903 /* move the signal variant */
1904 SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1905 SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1906 ClrBit(_m[t].m2, 2);
1907 ClrBit(_m[t].m2, 6);
1908 }
1909
1910 /* Clear PBS reservation on track */
1911 if (IsRailDepot(t)) {
1912 SetDepotReservation(t, false);
1913 } else {
1914 SetTrackReservation(t, TRACK_BIT_NONE);
1915 }
1916 break;
1917
1918 case MP_ROAD: // Clear PBS reservation on crossing
1919 if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
1920 break;
1921
1922 case MP_STATION: // Clear PBS reservation on station
1923 if (HasStationRail(t)) SetRailStationReservation(t, false);
1924 break;
1925
1926 case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/bridges
1927 if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
1928 break;
1929
1930 default: break;
1931 }
1932 }
1933 }
1934
1935 /* Reserve all tracks trains are currently on. */
1936 if (IsSavegameVersionBefore(101)) {
1937 const Train *t;
1938 FOR_ALL_TRAINS(t) {
1939 if (t->First() == t) t->ReserveTrackUnderConsist();
1940 }
1941 }
1942
1943 if (IsSavegameVersionBefore(102)) {
1944 for (TileIndex t = 0; t < map_size; t++) {
1945 /* Now all crossings should be in correct state */
1946 if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
1947 }
1948 }
1949
1950 if (IsSavegameVersionBefore(103)) {
1951 /* Non-town-owned roads now store the closest town */
1952 UpdateNearestTownForRoadTiles(false);
1953
1954 /* signs with invalid owner left from older savegames */
1955 Sign *si;
1956 FOR_ALL_SIGNS(si) {
1957 if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
1958 }
1959
1960 /* Station can get named based on an industry type, but the current ones
1961 * are not, so mark them as if they are not named by an industry. */
1962 Station *st;
1963 FOR_ALL_STATIONS(st) {
1964 st->indtype = IT_INVALID;
1965 }
1966 }
1967
1968 if (IsSavegameVersionBefore(104)) {
1969 Aircraft *a;
1970 FOR_ALL_AIRCRAFT(a) {
1971 /* Set engine_type of shadow and rotor */
1972 if (!a->IsNormalAircraft()) {
1973 a->engine_type = a->First()->engine_type;
1974 }
1975 }
1976
1977 /* More companies ... */
1978 Company *c;
1979 FOR_ALL_COMPANIES(c) {
1980 if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
1981 }
1982
1983 Engine *e;
1984 FOR_ALL_ENGINES(e) {
1985 if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
1986 }
1987
1988 Town *t;
1989 FOR_ALL_TOWNS(t) {
1990 if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
1991 for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1992 }
1993 }
1994
1995 if (IsSavegameVersionBefore(112)) {
1996 for (TileIndex t = 0; t < map_size; t++) {
1997 /* Check for HQ bit being set, instead of using map accessor,
1998 * since we've already changed it code-wise */
1999 if (IsTileType(t, MP_OBJECT) && HasBit(_m[t].m5, 7)) {
2000 /* Move size and part identification of HQ out of the m5 attribute,
2001 * on new locations */
2002 _m[t].m3 = GB(_m[t].m5, 0, 5);
2003 _m[t].m5 = OBJECT_HQ;
2004 }
2005 }
2006 }
2007 if (IsSavegameVersionBefore(144)) {
2008 for (TileIndex t = 0; t < map_size; t++) {
2009 if (!IsTileType(t, MP_OBJECT)) continue;
2010
2011 /* Reordering/generalisation of the object bits. */
2012 ObjectType type = _m[t].m5;
2013 SB(_me[t].m6, 2, 4, type == OBJECT_HQ ? GB(_m[t].m3, 2, 3) : 0);
2014 _m[t].m3 = type == OBJECT_HQ ? GB(_m[t].m3, 1, 1) | GB(_m[t].m3, 0, 1) << 4 : 0;
2015
2016 /* Make sure those bits are clear as well! */
2017 _m[t].m4 = 0;
2018 _me[t].m7 = 0;
2019 }
2020 }
2021
2022 if (IsSavegameVersionBefore(147) && Object::GetNumItems() == 0) {
2023 /* Make real objects for object tiles. */
2024 for (TileIndex t = 0; t < map_size; t++) {
2025 if (!IsTileType(t, MP_OBJECT)) continue;
2026
2027 if (Town::GetNumItems() == 0) {
2028 /* No towns, so remove all objects! */
2029 DoClearSquare(t);
2030 } else {
2031 uint offset = _m[t].m3;
2032
2033 /* Also move the animation state. */
2034 _m[t].m3 = GB(_me[t].m6, 2, 4);
2035 SB(_me[t].m6, 2, 4, 0);
2036
2037 if (offset == 0) {
2038 /* No offset, so make the object. */
2039 ObjectType type = _m[t].m5;
2040 int size = type == OBJECT_HQ ? 2 : 1;
2041
2042 if (!Object::CanAllocateItem()) {
2043 /* Nice... you managed to place 64k lighthouses and
2044 * antennae on the map... boohoo. */
2045 SlError(STR_ERROR_TOO_MANY_OBJECTS);
2046 }
2047
2048 Object *o = new Object();
2049 o->location.tile = t;
2050 o->location.w = size;
2051 o->location.h = size;
2052 o->build_date = _date;
2053 o->town = type == OBJECT_STATUE ? Town::Get(_m[t].m2) : CalcClosestTownFromTile(t, UINT_MAX);
2054 _m[t].m2 = o->index;
2055 Object::IncTypeCount(type);
2056 } else {
2057 /* We're at an offset, so get the ID from our "root". */
2058 TileIndex northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
2059 assert(IsTileType(northern_tile, MP_OBJECT));
2060 _m[t].m2 = _m[northern_tile].m2;
2061 }
2062 }
2063 }
2064 }
2065
2066 if (IsSavegameVersionBefore(113)) {
2067 /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
2068 if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
2069 _settings_game.economy.allow_town_roads = false;
2070 _settings_game.economy.town_layout = TL_BETTER_ROADS;
2071 } else {
2072 _settings_game.economy.allow_town_roads = true;
2073 _settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
2074 }
2075
2076 /* Initialize layout of all towns. Older versions were using different
2077 * generator for random town layout, use it if needed. */
2078 Town *t;
2079 FOR_ALL_TOWNS(t) {
2080 if (_settings_game.economy.town_layout != TL_RANDOM) {
2081 t->layout = _settings_game.economy.town_layout;
2082 continue;
2083 }
2084
2085 /* Use old layout randomizer code */
2086 byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
2087 switch (layout) {
2088 default: break;
2089 case 5: layout = 1; break;
2090 case 0: layout = 2; break;
2091 }
2092 t->layout = layout - 1;
2093 }
2094 }
2095
2096 if (IsSavegameVersionBefore(114)) {
2097 /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
2098 * The conversion affects oil rigs and buoys too, but it doesn't matter as
2099 * they have st->owner == OWNER_NONE already. */
2100 Station *st;
2101 FOR_ALL_STATIONS(st) {
2102 if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
2103 }
2104 }
2105
2106 /* Trains could now stop in a specific location. */
2107 if (IsSavegameVersionBefore(117)) {
2108 Order *o;
2109 FOR_ALL_ORDERS(o) {
2110 if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
2111 }
2112 }
2113
2114 if (IsSavegameVersionBefore(120)) {
2115 extern VehicleDefaultSettings _old_vds;
2116 Company *c;
2117 FOR_ALL_COMPANIES(c) {
2118 c->settings.vehicle = _old_vds;
2119 }
2120 }
2121
2122 if (IsSavegameVersionBefore(121)) {
2123 /* Delete small ufos heading for non-existing vehicles */
2124 Vehicle *v;
2125 FOR_ALL_DISASTERVEHICLES(v) {
2126 if (v->subtype == 2 /* ST_SMALL_UFO */ && v->current_order.GetDestination() != 0) {
2127 const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
2128 if (u == NULL || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
2129 delete v;
2130 }
2131 }
2132 }
2133
2134 /* We didn't store cargo payment yet, so make them for vehicles that are
2135 * currently at a station and loading/unloading. If they don't get any
2136 * payment anymore they just removed in the next load/unload cycle.
2137 * However, some 0.7 versions might have cargo payment. For those we just
2138 * add cargopayment for the vehicles that don't have it.
2139 */
2140 Station *st;
2141 FOR_ALL_STATIONS(st) {
2142 std::list<Vehicle *>::iterator iter;
2143 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
2144 /* There are always as many CargoPayments as Vehicles. We need to make the
2145 * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
2146 assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
2147 assert(CargoPayment::CanAllocateItem());
2148 Vehicle *v = *iter;
2149 if (v->cargo_payment == NULL) v->cargo_payment = new CargoPayment(v);
2150 }
2151 }
2152 }
2153
2154 if (IsSavegameVersionBefore(122)) {
2155 /* Animated tiles would sometimes not be actually animated or
2156 * in case of old savegames duplicate. */
2157
2158 extern TileIndex *_animated_tile_list;
2159 extern uint _animated_tile_count;
2160
2161 for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
2162 /* Remove if tile is not animated */
2163 bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == NULL;
2164
2165 /* and remove if duplicate */
2166 for (uint j = 0; !remove && j < i; j++) {
2167 remove = _animated_tile_list[i] == _animated_tile_list[j];
2168 }
2169
2170 if (remove) {
2171 DeleteAnimatedTile(_animated_tile_list[i]);
2172 } else {
2173 i++;
2174 }
2175 }
2176 }
2177
2178 if (IsSavegameVersionBefore(124) && !IsSavegameVersionBefore(1)) {
2179 /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
2180 Waypoint *wp;
2181 FOR_ALL_WAYPOINTS(wp) {
2182 if (wp->facilities & FACIL_TRAIN) {
2183 wp->train_station.tile = wp->xy;
2184 wp->train_station.w = 1;
2185 wp->train_station.h = 1;
2186 } else {
2187 wp->train_station.tile = INVALID_TILE;
2188 wp->train_station.w = 0;
2189 wp->train_station.h = 0;
2190 }
2191 }
2192 }
2193
2194 if (IsSavegameVersionBefore(125)) {
2195 /* Convert old subsidies */
2196 Subsidy *s;
2197 FOR_ALL_SUBSIDIES(s) {
2198 if (s->remaining < 12) {
2199 /* Converting nonawarded subsidy */
2200 s->remaining = 12 - s->remaining; // convert "age" to "remaining"
2201 s->awarded = INVALID_COMPANY; // not awarded to anyone
2202 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2203 switch (cs->town_effect) {
2204 case TE_PASSENGERS:
2205 case TE_MAIL:
2206 /* Town -> Town */
2207 s->src_type = s->dst_type = ST_TOWN;
2208 if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2209 break;
2210 case TE_GOODS:
2211 case TE_FOOD:
2212 /* Industry -> Town */
2213 s->src_type = ST_INDUSTRY;
2214 s->dst_type = ST_TOWN;
2215 if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2216 break;
2217 default:
2218 /* Industry -> Industry */
2219 s->src_type = s->dst_type = ST_INDUSTRY;
2220 if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
2221 break;
2222 }
2223 } else {
2224 /* Do our best for awarded subsidies. The original source or destination industry
2225 * can't be determined anymore for awarded subsidies, so invalidate them.
2226 * Town -> Town subsidies are converted using simple heuristic */
2227 s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
2228 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2229 switch (cs->town_effect) {
2230 case TE_PASSENGERS:
2231 case TE_MAIL: {
2232 /* Town -> Town */
2233 const Station *ss = Station::GetIfValid(s->src);
2234 const Station *sd = Station::GetIfValid(s->dst);
2235 if (ss != NULL && sd != NULL && ss->owner == sd->owner &&
2236 Company::IsValidID(ss->owner)) {
2237 s->src_type = s->dst_type = ST_TOWN;
2238 s->src = ss->town->index;
2239 s->dst = sd->town->index;
2240 s->awarded = ss->owner;
2241 continue;
2242 }
2243 break;
2244 }
2245 default:
2246 break;
2247 }
2248 }
2249 /* Awarded non-town subsidy or invalid source/destination, invalidate */
2250 delete s;
2251 }
2252 }
2253
2254 if (IsSavegameVersionBefore(126)) {
2255 /* Recompute inflation based on old unround loan limit
2256 * Note: Max loan is 500000. With an inflation of 4% across 170 years
2257 * that results in a max loan of about 0.7 * 2^31.
2258 * So taking the 16 bit fractional part into account there are plenty of bits left
2259 * for unmodified savegames ...
2260 */
2261 uint64 aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
2262
2263 /* ... well, just clamp it then. */
2264 if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
2265
2266 /* Simulate the inflation, so we also get the payment inflation */
2267 while (_economy.inflation_prices < aimed_inflation) {
2268 if (AddInflation(false)) break;
2269 }
2270 }
2271
2272 if (IsSavegameVersionBefore(128)) {
2273 const Depot *d;
2274 FOR_ALL_DEPOTS(d) {
2275 _m[d->xy].m2 = d->index;
2276 if (IsTileType(d->xy, MP_WATER)) _m[GetOtherShipDepotTile(d->xy)].m2 = d->index;
2277 }
2278 }
2279
2280 /* The behaviour of force_proceed has been changed. Now
2281 * it counts signals instead of some random time out. */
2282 if (IsSavegameVersionBefore(131)) {
2283 Train *t;
2284 FOR_ALL_TRAINS(t) {
2285 if (t->force_proceed != TFP_NONE) {
2286 t->force_proceed = TFP_STUCK;
2287 }
2288 }
2289 }
2290
2291 /* The bits for the tree ground and tree density have
2292 * been swapped (m2 bits 7..6 and 5..4. */
2293 if (IsSavegameVersionBefore(135)) {
2294 for (TileIndex t = 0; t < map_size; t++) {
2295 if (IsTileType(t, MP_CLEAR)) {
2296 if (GetRawClearGround(t) == CLEAR_SNOW) {
2297 SetClearGroundDensity(t, CLEAR_GRASS, GetClearDensity(t));
2298 SetBit(_m[t].m3, 4);
2299 } else {
2300 ClrBit(_m[t].m3, 4);
2301 }
2302 }
2303 if (IsTileType(t, MP_TREES)) {
2304 uint density = GB(_m[t].m2, 6, 2);
2305 uint ground = GB(_m[t].m2, 4, 2);
2306 uint counter = GB(_m[t].m2, 0, 4);
2307 _m[t].m2 = ground << 6 | density << 4 | counter;
2308 }
2309 }
2310 }
2311
2312 /* Wait counter and load/unload ticks got split. */
2313 if (IsSavegameVersionBefore(136)) {
2314 Aircraft *a;
2315 FOR_ALL_AIRCRAFT(a) {
2316 a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
2317 }
2318
2319 Train *t;
2320 FOR_ALL_TRAINS(t) {
2321 t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
2322 }
2323 }
2324
2325 /* Airport tile animation uses animation frame instead of other graphics id */
2326 if (IsSavegameVersionBefore(137)) {
2327 struct AirportTileConversion {
2328 byte old_start;
2329 byte num_frames;
2330 };
2331 static const AirportTileConversion atc[] = {
2332 {31, 12}, // APT_RADAR_GRASS_FENCE_SW
2333 {50, 4}, // APT_GRASS_FENCE_NE_FLAG
2334 {62, 2}, // 1 unused tile
2335 {66, 12}, // APT_RADAR_FENCE_SW
2336 {78, 12}, // APT_RADAR_FENCE_NE
2337 {101, 10}, // 9 unused tiles
2338 {111, 8}, // 7 unused tiles
2339 {119, 15}, // 14 unused tiles (radar)
2340 {140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
2341 };
2342 for (TileIndex t = 0; t < map_size; t++) {
2343 if (IsAirportTile(t)) {
2344 StationGfx old_gfx = GetStationGfx(t);
2345 byte offset = 0;
2346 for (uint i = 0; i < lengthof(atc); i++) {
2347 if (old_gfx < atc[i].old_start) {
2348 SetStationGfx(t, old_gfx - offset);
2349 break;
2350 }
2351 if (old_gfx < atc[i].old_start + atc[i].num_frames) {
2352 SetAnimationFrame(t, old_gfx - atc[i].old_start);
2353 SetStationGfx(t, atc[i].old_start - offset);
2354 break;
2355 }
2356 offset += atc[i].num_frames - 1;
2357 }
2358 }
2359 }
2360 }
2361
2362 if (IsSavegameVersionBefore(140)) {
2363 Station *st;
2364 FOR_ALL_STATIONS(st) {
2365 if (st->airport.tile != INVALID_TILE) {
2366 st->airport.w = st->airport.GetSpec()->size_x;
2367 st->airport.h = st->airport.GetSpec()->size_y;
2368 }
2369 }
2370 }
2371
2372 if (IsSavegameVersionBefore(141)) {
2373 for (TileIndex t = 0; t < map_size; t++) {
2374 /* Reset tropic zone for VOID tiles, they shall not have any. */
2375 if (IsTileType(t, MP_VOID)) SetTropicZone(t, TROPICZONE_NORMAL);
2376 }
2377
2378 /* We need to properly number/name the depots.
2379 * The first step is making sure none of the depots uses the
2380 * 'default' names, after that we can assign the names. */
2381 Depot *d;
2382 FOR_ALL_DEPOTS(d) d->town_cn = UINT16_MAX;
2383
2384 FOR_ALL_DEPOTS(d) MakeDefaultName(d);
2385 }
2386
2387 if (IsSavegameVersionBefore(142)) {
2388 Depot *d;
2389 FOR_ALL_DEPOTS(d) d->build_date = _date;
2390 }
2391
2392 /* In old versions it was possible to remove an airport while a plane was
2393 * taking off or landing. This gives all kind of problems when building
2394 * another airport in the same station so we don't allow that anymore.
2395 * For old savegames with such aircraft we just throw them in the air and
2396 * treat the aircraft like they were flying already. */
2397 if (IsSavegameVersionBefore(146)) {
2398 Aircraft *v;
2399 FOR_ALL_AIRCRAFT(v) {
2400 if (!v->IsNormalAircraft()) continue;
2401 Station *st = GetTargetAirportIfValid(v);
2402 if (st == NULL && v->state != FLYING) {
2403 v->state = FLYING;
2404 UpdateAircraftCache(v);
2405 AircraftNextAirportPos_and_Order(v);
2406 /* get aircraft back on running altitude */
2407 if ((v->vehstatus & VS_CRASHED) == 0) {
2408 GetAircraftFlightLevelBounds(v, &v->z_pos, NULL);
2409 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
2410 }
2411 }
2412 }
2413 }
2414
2415 /* Move the animation frame to the same location (m7) for all objects. */
2416 if (IsSavegameVersionBefore(147)) {
2417 for (TileIndex t = 0; t < map_size; t++) {
2418 switch (GetTileType(t)) {
2419 case MP_HOUSE:
2420 if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
2421 uint per_proc = _me[t].m7;
2422 _me[t].m7 = GB(_me[t].m6, 2, 6) | (GB(_m[t].m3, 5, 1) << 6);
2423 SB(_m[t].m3, 5, 1, 0);
2424 SB(_me[t].m6, 2, 6, min(per_proc, 63));
2425 }
2426 break;
2427
2428 case MP_INDUSTRY: {
2429 uint rand = _me[t].m7;
2430 _me[t].m7 = _m[t].m3;
2431 _m[t].m3 = rand;
2432 break;
2433 }
2434
2435 case MP_OBJECT:
2436 _me[t].m7 = _m[t].m3;
2437 _m[t].m3 = 0;
2438 break;
2439
2440 default:
2441 /* For stations/airports it's already at m7 */
2442 break;
2443 }
2444 }
2445 }
2446
2447 /* Add (random) colour to all objects. */
2448 if (IsSavegameVersionBefore(148)) {
2449 Object *o;
2450 FOR_ALL_OBJECTS(o) {
2451 Owner owner = GetTileOwner(o->location.tile);
2452 o->colour = (owner == OWNER_NONE) ? Random() & 0xF : Company::Get(owner)->livery->colour1;
2453 }
2454 }
2455
2456 if (IsSavegameVersionBefore(149)) {
2457 for (TileIndex t = 0; t < map_size; t++) {
2458 if (!IsTileType(t, MP_STATION)) continue;
2459 if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && IsTileFlat(t))) {
2460 SetWaterClass(t, WATER_CLASS_INVALID);
2461 }
2462 }
2463
2464 /* Waypoints with custom name may have a non-unique town_cn,
2465 * renumber those. First set all affected waypoints to the
2466 * highest possible number to get them numbered in the
2467 * order they have in the pool. */
2468 Waypoint *wp;
2469 FOR_ALL_WAYPOINTS(wp) {
2470 if (wp->name != NULL) wp->town_cn = UINT16_MAX;
2471 }
2472
2473 FOR_ALL_WAYPOINTS(wp) {
2474 if (wp->name != NULL) MakeDefaultName(wp);
2475 }
2476 }
2477
2478 if (IsSavegameVersionBefore(152)) {
2479 _industry_builder.Reset(); // Initialize industry build data.
2480
2481 /* The moment vehicles go from hidden to visible changed. This means
2482 * that vehicles don't always get visible anymore causing things to
2483 * get messed up just after loading the savegame. This fixes that. */
2484 Vehicle *v;
2485 FOR_ALL_VEHICLES(v) {
2486 /* Not all vehicle types can be inside a tunnel. Furthermore,
2487 * testing IsTunnelTile() for invalid tiles causes a crash. */
2488 if (!v->IsGroundVehicle()) continue;
2489
2490 /* Is the vehicle in a tunnel? */
2491 if (!IsTunnelTile(v->tile)) continue;
2492
2493 /* Is the vehicle actually at a tunnel entrance/exit? */
2494 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
2495 if (!IsTunnelTile(vtile)) continue;
2496
2497 /* Are we actually in this tunnel? Or maybe a lower tunnel? */
2498 if (GetSlopePixelZ(v->x_pos, v->y_pos) != v->z_pos) continue;
2499
2500 /* What way are we going? */
2501 const DiagDirection dir = GetTunnelBridgeDirection(vtile);
2502 const DiagDirection vdir = DirToDiagDir(v->direction);
2503
2504 /* Have we passed the visibility "switch" state already? */
2505 byte pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
2506 byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2507 extern const byte _tunnel_visibility_frame[DIAGDIR_END];
2508
2509 /* Should the vehicle be hidden or not? */
2510 bool hidden;
2511 if (dir == vdir) { // Entering tunnel
2512 hidden = frame >= _tunnel_visibility_frame[dir];
2513 v->tile = vtile;
2514 } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
2515 hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
2516 /* v->tile changes at the moment when the vehicle leaves the tunnel. */
2517 v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
2518 } else {
2519 /* We could get here in two cases:
2520 * - for road vehicles, it is reversing at the end of the tunnel
2521 * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
2522 * Whatever case it is, do not change anything and use the old values.
2523 * Especially changing RV's state would break its reversing in the middle. */
2524 continue;
2525 }
2526
2527 if (hidden) {
2528 v->vehstatus |= VS_HIDDEN;
2529
2530 switch (v->type) {
2531 case VEH_TRAIN: Train::From(v)->track = TRACK_BIT_WORMHOLE; break;
2532 case VEH_ROAD: RoadVehicle::From(v)->state = RVSB_WORMHOLE; break;
2533 default: NOT_REACHED();
2534 }
2535 } else {
2536 v->vehstatus &= ~VS_HIDDEN;
2537
2538 switch (v->type) {
2539 case VEH_TRAIN: Train::From(v)->track = DiagDirToDiagTrackBits(vdir); break;
2540 case VEH_ROAD: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
2541 default: NOT_REACHED();
2542 }
2543 }
2544 }
2545 }
2546
2547 if (IsSavegameVersionBefore(153)) {
2548 RoadVehicle *rv;
2549 FOR_ALL_ROADVEHICLES(rv) {
2550 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
2551
2552 bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
2553 if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
2554 extern const byte _road_stop_stop_frame[];
2555 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)]);
2556 } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
2557 SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
2558 }
2559 }
2560 }
2561
2562 if (IsSavegameVersionBefore(156)) {
2563 /* The train's pathfinder lost flag got moved. */
2564 Train *t;
2565 FOR_ALL_TRAINS(t) {
2566 if (!HasBit(t->flags, 5)) continue;
2567
2568 ClrBit(t->flags, 5);
2569 SetBit(t->vehicle_flags, VF_PATHFINDER_LOST);
2570 }
2571
2572 /* Introduced terraform/clear limits. */
2573 Company *c;
2574 FOR_ALL_COMPANIES(c) {
2575 c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
2576 c->clear_limit = _settings_game.construction.clear_frame_burst << 16;
2577 }
2578 }
2579
2580 if (IsSavegameVersionBefore(158)) {
2581 Vehicle *v;
2582 FOR_ALL_VEHICLES(v) {
2583 switch (v->type) {
2584 case VEH_TRAIN: {
2585 Train *t = Train::From(v);
2586
2587 /* Clear old GOINGUP / GOINGDOWN flags.
2588 * It was changed in savegame version 139, but savegame
2589 * version 158 doesn't use these bits, so it doesn't hurt
2590 * to clear them unconditionally. */
2591 ClrBit(t->flags, 1);
2592 ClrBit(t->flags, 2);
2593
2594 /* Clear both bits first. */
2595 ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
2596 ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
2597
2598 /* Crashed vehicles can't be going up/down. */
2599 if (t->vehstatus & VS_CRASHED) break;
2600
2601 /* Only X/Y tracks can be sloped. */
2602 if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
2603
2604 t->gv_flags |= FixVehicleInclination(t, t->direction);
2605 break;
2606 }
2607 case VEH_ROAD: {
2608 RoadVehicle *rv = RoadVehicle::From(v);
2609 ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
2610 ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
2611
2612 /* Crashed vehicles can't be going up/down. */
2613 if (rv->vehstatus & VS_CRASHED) break;
2614
2615 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
2616
2617 TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, rv->compatible_roadtypes);
2618 TrackBits trackbits = TrackStatusToTrackBits(ts);
2619
2620 /* Only X/Y tracks can be sloped. */
2621 if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
2622
2623 Direction dir = rv->direction;
2624
2625 /* Test if we are reversing. */
2626 Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
2627 if (AxisToDirection(a) != dir &&
2628 AxisToDirection(a) != ReverseDir(dir)) {
2629 /* When reversing, the road vehicle is on the edge of the tile,
2630 * so it can be safely compared to the middle of the tile. */
2631 dir = INVALID_DIR;
2632 }
2633
2634 rv->gv_flags |= FixVehicleInclination(rv, dir);
2635 break;
2636 }
2637 case VEH_SHIP:
2638 break;
2639
2640 default:
2641 continue;
2642 }
2643
2644 if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2645 /* In old versions, z_pos was 1 unit lower on bridge heads.
2646 * However, this invalid state could be converted to new savegames
2647 * by loading and saving the game in a new version. */
2648 v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos);
2649 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
2650 if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
2651 v->direction != DiagDirToDir(dir)) {
2652 /* If the train has left the bridge, it shouldn't have
2653 * track == TRACK_BIT_WORMHOLE - this could happen
2654 * when the train was reversed while on the last "tick"
2655 * on the ramp before leaving the ramp to the bridge. */
2656 Train::From(v)->track = DiagDirToDiagTrackBits(dir);
2657 }
2658 }
2659
2660 /* If the vehicle is really above v->tile (not in a wormhole),
2661 * it should have set v->z_pos correctly. */
2662 assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos));
2663 }
2664
2665 /* Fill Vehicle::cur_real_order_index */
2666 FOR_ALL_VEHICLES(v) {
2667 if (!v->IsPrimaryVehicle()) continue;
2668
2669 /* Older versions are less strict with indices being in range and fix them on the fly */
2670 if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
2671
2672 v->cur_real_order_index = v->cur_implicit_order_index;
2673 v->UpdateRealOrderIndex();
2674 }
2675 }
2676
2677 if (IsSavegameVersionBefore(159)) {
2678 /* If the savegame is old (before version 100), then the value of 255
2679 * for these settings did not mean "disabled". As such everything
2680 * before then did reverse.
2681 * To simplify stuff we disable all turning around or we do not
2682 * disable anything at all. So, if some reversing was disabled we
2683 * will keep reversing disabled, otherwise it'll be turned on. */
2684 _settings_game.pf.reverse_at_signals = IsSavegameVersionBefore(100) || (_settings_game.pf.wait_oneway_signal != 255 && _settings_game.pf.wait_twoway_signal != 255 && _settings_game.pf.wait_for_pbs_path != 255);
2685
2686 Train *t;
2687 FOR_ALL_TRAINS(t) {
2688 _settings_game.vehicle.max_train_length = max<uint8>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
2689 }
2690 }
2691
2692 if (IsSavegameVersionBefore(160)) {
2693 /* Setting difficulty industry_density other than zero get bumped to +1
2694 * since a new option (minimal at position 1) has been added */
2695 if (_settings_game.difficulty.industry_density > 0) {
2696 _settings_game.difficulty.industry_density++;
2697 }
2698 }
2699
2700 if (IsSavegameVersionBefore(161)) {
2701 /* Before savegame version 161, persistent storages were not stored in a pool. */
2702
2703 if (!IsSavegameVersionBefore(76)) {
2704 Industry *ind;
2705 FOR_ALL_INDUSTRIES(ind) {
2706 assert(ind->psa != NULL);
2707
2708 /* Check if the old storage was empty. */
2709 bool is_empty = true;
2710 for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
2711 if (ind->psa->GetValue(i) != 0) {
2712 is_empty = false;
2713 break;
2714 }
2715 }
2716
2717 if (!is_empty) {
2718 ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
2719 } else {
2720 delete ind->psa;
2721 ind->psa = NULL;
2722 }
2723 }
2724 }
2725
2726 if (!IsSavegameVersionBefore(145)) {
2727 Station *st;
2728 FOR_ALL_STATIONS(st) {
2729 if (!(st->facilities & FACIL_AIRPORT)) continue;
2730 assert(st->airport.psa != NULL);
2731
2732 /* Check if the old storage was empty. */
2733 bool is_empty = true;
2734 for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
2735 if (st->airport.psa->GetValue(i) != 0) {
2736 is_empty = false;
2737 break;
2738 }
2739 }
2740
2741 if (!is_empty) {
2742 st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
2743 } else {
2744 delete st->airport.psa;
2745 st->airport.psa = NULL;
2746
2747 }
2748 }
2749 }
2750 }
2751
2752 /* This triggers only when old snow_lines were copied into the snow_line_height. */
2753 if (IsSavegameVersionBefore(164) && _settings_game.game_creation.snow_line_height >= MIN_SNOWLINE_HEIGHT * TILE_HEIGHT) {
2754 _settings_game.game_creation.snow_line_height /= TILE_HEIGHT;
2755 }
2756
2757 if (IsSavegameVersionBefore(164) && !IsSavegameVersionBefore(32)) {
2758 /* We store 4 fences in the field tiles instead of only SE and SW. */
2759 for (TileIndex t = 0; t < map_size; t++) {
2760 if (!IsTileType(t, MP_CLEAR) && !IsTileType(t, MP_TREES)) continue;
2761 if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) continue;
2762 uint fence = GB(_m[t].m4, 5, 3);
2763 if (fence != 0 && IsTileType(TILE_ADDXY(t, 1, 0), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 1, 0), CLEAR_FIELDS)) {
2764 SetFence(TILE_ADDXY(t, 1, 0), DIAGDIR_NE, fence);
2765 }
2766 fence = GB(_m[t].m4, 2, 3);
2767 if (fence != 0 && IsTileType(TILE_ADDXY(t, 0, 1), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 0, 1), CLEAR_FIELDS)) {
2768 SetFence(TILE_ADDXY(t, 0, 1), DIAGDIR_NW, fence);
2769 }
2770 SB(_m[t].m4, 2, 3, 0);
2771 SB(_m[t].m4, 5, 3, 0);
2772 }
2773 }
2774
2775 /* The center of train vehicles was changed, fix up spacing. */
2776 if (IsSavegameVersionBefore(164)) FixupTrainLengths();
2777
2778 if (IsSavegameVersionBefore(165)) {
2779 Town *t;
2780
2781 FOR_ALL_TOWNS(t) {
2782 /* Set the default cargo requirement for town growth */
2783 switch (_settings_game.game_creation.landscape) {
2784 case LT_ARCTIC:
2785 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
2786 break;
2787
2788 case LT_TROPIC:
2789 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
2790 if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
2791 break;
2792 }
2793 }
2794 }
2795
2796 if (IsSavegameVersionBefore(165)) {
2797 /* Adjust zoom level to account for new levels */
2798 _saved_scrollpos_zoom = _saved_scrollpos_zoom + ZOOM_LVL_SHIFT;
2799 _saved_scrollpos_x *= ZOOM_LVL_BASE;
2800 _saved_scrollpos_y *= ZOOM_LVL_BASE;
2801 }
2802
2803 /* When any NewGRF has been changed the availability of some vehicles might
2804 * have been changed too. e->company_avail must be set to 0 in that case
2805 * which is done by StartupEngines(). */
2806 if (gcf_res != GLC_ALL_GOOD) StartupEngines();
2807
2808 if (IsSavegameVersionBefore(166)) {
2809 /* Update cargo acceptance map of towns. */
2810 for (TileIndex t = 0; t < map_size; t++) {
2811 if (!IsTileType(t, MP_HOUSE)) continue;
2812 Town::Get(GetTownIndex(t))->cargo_accepted.Add(t);
2813 }
2814
2815 Town *town;
2816 FOR_ALL_TOWNS(town) {
2817 UpdateTownCargoes(town);
2818 }
2819 }
2820
2821 /* The road owner of standard road stops was not properly accounted for. */
2822 if (IsSavegameVersionBefore(172)) {
2823 for (TileIndex t = 0; t < map_size; t++) {
2824 if (!IsStandardRoadStopTile(t)) continue;
2825 Owner o = GetTileOwner(t);
2826 SetRoadOwner(t, ROADTYPE_ROAD, o);
2827 SetRoadOwner(t, ROADTYPE_TRAM, o);
2828 }
2829 }
2830
2831 if (IsSavegameVersionBefore(175)) {
2832 /* Introduced tree planting limit. */
2833 Company *c;
2834 FOR_ALL_COMPANIES(c) c->tree_limit = _settings_game.construction.tree_frame_burst << 16;
2835 }
2836
2837 if (IsSavegameVersionBefore(177)) {
2838 /* Fix too high inflation rates */
2839 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
2840 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
2841
2842 /* We have to convert the quarters of bankruptcy into months of bankruptcy */
2843 FOR_ALL_COMPANIES(c) {
2844 c->months_of_bankruptcy = 3 * c->months_of_bankruptcy;
2845 }
2846 }
2847
2848 if (IsSavegameVersionBefore(178)) {
2849 extern uint8 _old_diff_level;
2850 /* Initialise script settings profile */
2851 _settings_game.script.settings_profile = IsInsideMM(_old_diff_level, SP_BEGIN, SP_END) ? _old_diff_level : (uint)SP_MEDIUM;
2852 }
2853
2854 if (IsSavegameVersionBefore(182)) {
2855 Aircraft *v;
2856 /* Aircraft acceleration variable was bonkers */
2857 FOR_ALL_AIRCRAFT(v) {
2858 if (v->subtype <= AIR_AIRCRAFT) {
2859 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
2860 v->acceleration = avi->acceleration;
2861 }
2862 }
2863
2864 /* Blocked tiles could be reserved due to a bug, which causes
2865 * other places to assert upon e.g. station reconstruction. */
2866 for (TileIndex t = 0; t < map_size; t++) {
2867 if (HasStationTileRail(t) && IsStationTileBlocked(t)) {
2868 SetRailStationReservation(t, false);
2869 }
2870 }
2871 }
2872
2873 if (IsSavegameVersionBefore(184)) {
2874 /* The global units configuration is split up in multiple configurations. */
2875 extern uint8 _old_units;
2876 _settings_game.locale.units_velocity = Clamp(_old_units, 0, 2);
2877 _settings_game.locale.units_power = Clamp(_old_units, 0, 2);
2878 _settings_game.locale.units_weight = Clamp(_old_units, 1, 2);
2879 _settings_game.locale.units_volume = Clamp(_old_units, 1, 2);
2880 _settings_game.locale.units_force = 2;
2881 _settings_game.locale.units_height = Clamp(_old_units, 0, 2);
2882 }
2883
2884 if (IsSavegameVersionBefore(186)) {
2885 /* Move ObjectType from map to pool */
2886 for (TileIndex t = 0; t < map_size; t++) {
2887 if (IsTileType(t, MP_OBJECT)) {
2888 Object *o = Object::Get(_m[t].m2);
2889 o->type = _m[t].m5;
2890 _m[t].m5 = 0; // zero upper bits of (now bigger) ObjectID
2891 }
2892 }
2893 }
2894
2895 if (IsSavegameVersionBefore(188)) {
2896 /* Fix articulated road vehicles.
2897 * Some curves were shorter than other curves.
2898 * Now they have the same length, but that means that trailing articulated parts will
2899 * take longer to go through the curve than the parts in front which already left the courve.
2900 * So, make articulated parts catch up. */
2901 RoadVehicle *v;
2902 bool roadside = _settings_game.vehicle.road_side == 1;
2903 SmallVector<uint, 16> skip_frames;
2904 FOR_ALL_ROADVEHICLES(v) {
2905 if (!v->IsFrontEngine()) continue;
2906 skip_frames.Clear();
2907 TileIndex prev_tile = v->tile;
2908 uint prev_tile_skip = 0;
2909 uint cur_skip = 0;
2910 for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
2911 if (u->tile != prev_tile) {
2912 prev_tile_skip = cur_skip;
2913 prev_tile = u->tile;
2914 } else {
2915 cur_skip = prev_tile_skip;
2916 }
2917
2918 uint *this_skip = skip_frames.Append();
2919 *this_skip = prev_tile_skip;
2920
2921 /* The following 3 curves now take longer than before */
2922 switch (u->state) {
2923 case 2:
2924 cur_skip++;
2925 if (u->frame <= (roadside ? 9 : 5)) *this_skip = cur_skip;
2926 break;
2927
2928 case 4:
2929 cur_skip++;
2930 if (u->frame <= (roadside ? 5 : 9)) *this_skip = cur_skip;
2931 break;
2932
2933 case 5:
2934 cur_skip++;
2935 if (u->frame <= (roadside ? 4 : 2)) *this_skip = cur_skip;
2936 break;
2937
2938 default:
2939 break;
2940 }
2941 }
2942 while (cur_skip > skip_frames[0]) {
2943 RoadVehicle *u = v;
2944 RoadVehicle *prev = NULL;
2945 for (uint *it = skip_frames.Begin(); it != skip_frames.End(); ++it, prev = u, u = u->Next()) {
2946 extern bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev);
2947 if (*it >= cur_skip) IndividualRoadVehicleController(u, prev);
2948 }
2949 cur_skip--;
2950 }
2951 }
2952 }
2953
2954 /*
2955 * Only keep order-backups for network clients (and when replaying).
2956 * If we are a network server or not networking, then we just loaded a previously
2957 * saved-by-server savegame. There are no clients with a backup, so clear it.
2958 * Furthermore before savegame version 192 the actual content was always corrupt.
2959 */
2960 if (!_networking || _network_server || IsSavegameVersionBefore(192)) {
2961 #ifndef DEBUG_DUMP_COMMANDS
2962 /* Note: We cannot use CleanPool since that skips part of the destructor
2963 * and then leaks un-reachable Orders in the order pool. */
2964 OrderBackup *ob;
2965 FOR_ALL_ORDER_BACKUPS(ob) {
2966 delete ob;
2967 }
2968 #endif
2969 }
2970
2971
2972 /* Station acceptance is some kind of cache */
2973 if (IsSavegameVersionBefore(127)) {
2974 Station *st;
2975 FOR_ALL_STATIONS(st) UpdateStationAcceptance(st, false);
2976 }
2977
2978 /* Road stops is 'only' updating some caches */
2979 AfterLoadRoadStops();
2980 AfterLoadLabelMaps();
2981 AfterLoadCompanyStats();
2982 AfterLoadStoryBook();
2983
2984 GamelogPrintDebug(1);
2985
2986 InitializeWindowsAndCaches();
2987 /* Restore the signals */
2988 ResetSignalHandlers();
2989
2990 AfterLoadLinkGraphs();
2991 return true;
2992 }
2993
3002 void ReloadNewGRFData()
3003 {
3004 /* reload grf data */
3005 GfxLoadSprites();
3006 LoadStringWidthTable();
3007 RecomputePrices();
3008 /* reload vehicles */
3009 ResetVehicleHash();
3010 AfterLoadVehicles(false);
3011 StartupEngines();
3012 GroupStatistics::UpdateAfterLoad();
3013 /* update station graphics */
3014 AfterLoadStations();
3015 /* Update company statistics. */
3016 AfterLoadCompanyStats();
3017 /* Check and update house and town values */
3018 UpdateHousesAndTowns();
3019 /* Delete news referring to no longer existing entities */
3020 DeleteInvalidEngineNews();
3021 /* Update livery selection windows */
3022 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i);
3023 /* Update company infrastructure counts. */
3024 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
3025 /* redraw the whole screen */
3026 MarkWholeScreenDirty();
3027 CheckTrainsLengths();
3028 }