OpenTTD
afterload.cpp
Go to the documentation of this file.
1 /* $Id: afterload.cpp 27893 2017-08-13 18:38:42Z 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) {
85  return;
86  } else {
87  SlErrorCorrupt("Invalid water class for dry tile");
88  }
89  }
90 
91  /* Mark tile dirty in all cases */
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 */
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) {
137  return;
138  }
139 
140  if (has_river && !has_canal) {
142  } else if (has_canal || !has_water) {
144  } else {
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  FALLTHROUGH;
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) {
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 {
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 
221 {
225 }
226 
237 {
238  /* Initialize windows */
241 
242  /* Update coordinates of the signs. */
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 */
253  }
254  }
255 
256  /* Count number of objects per type */
257  Object *o;
258  FOR_ALL_OBJECTS(o) {
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 
288 
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. */
296 
298  ShowNewGRFError();
300 
301  /* Rebuild the smallmap list of owners. */
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 
339 {
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 
353 
360 {
362 }
363 
370 static void CDECL HandleSavegameLoadCrash(int signum)
371 {
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 
433 {
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 &&
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) */
466  return;
467  }
468 
469  /* if it's not a crossing, make it clean land */
470  MakeClear(t, CLEAR_GRASS, 0);
471 }
472 
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) ||
519 }
520 
527 {
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 
537 
539  GamelogTestMode();
540 
542 
543  if (IsSavegameVersionBefore(119)) {
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 */
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. */
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)) {
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) {
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;
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)) {
664  }
665  }
666  }
667 
668  /* convert road side to my format. */
670 
671  /* Check if all NewGRFs are present, we are very strict in MP mode */
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 */
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. */
696 
697  /* Update current year
698  * must be done before loading sprites as some newgrfs check it */
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  */
720  if (IsSavegameVersionBefore(133)) {
722  }
725  if (IsSavegameVersionBefore(139)) {
728  }
730  if (IsSavegameVersionBefore(159)) {
734  }
736  if (IsSavegameVersionBefore(183)) {
741  }
742 
743  /* Load the sprites */
744  GfxLoadSprites();
746 
747  /* Copy temporary data to Engine pool */
749 
750  /* Connect front and rear engines of multiheaded trains and converts
751  * subtype to the new format */
753 
754  /* Connect front and rear engines of multiheaded trains */
756 
757  /* Fix the CargoPackets *and* fix the caches of CargoLists.
758  * If this isn't done before Stations and especially Vehicles are
759  * running their AfterLoad we might get in trouble. In the case of
760  * vehicles we could give the wrong (cached) count of items in a
761  * vehicle which causes different results when getting their caches
762  * filled; and that could eventually lead to desyncs. */
764 
765  /* Oilrig was moved from id 15 to 9. We have to do this conversion
766  * here as AfterLoadVehicles can check it indirectly via the newgrf
767  * code. */
768  if (IsSavegameVersionBefore(139)) {
769  Station *st;
770  FOR_ALL_STATIONS(st) {
771  if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
772  st->airport.type = AT_OILRIG;
773  }
774  }
775  }
776 
777  /* Update all vehicles */
778  AfterLoadVehicles(true);
779 
780  /* Make sure there is an AI attached to an AI company */
781  {
782  Company *c;
783  FOR_ALL_COMPANIES(c) {
784  if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
785  }
786  }
787 
788  /* make sure there is a town in the game */
789  if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
790  SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
791  /* Restore the signals */
793  return false;
794  }
795 
796  /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
797  * This problem appears in savegame version 21 too, see r3455. But after loading the
798  * savegame and saving again, the buggy map array could be converted to new savegame
799  * version. It didn't show up before r12070. */
800  if (IsSavegameVersionBefore(87)) UpdateVoidTiles();
801 
802  /* If Load Scenario / New (Scenario) Game is used,
803  * a company does not exist yet. So create one here.
804  * 1 exception: network-games. Those can have 0 companies
805  * But this exception is not true for non-dedicated network servers! */
807  DoStartupNewCompany(false);
810  }
811 
812  /* Fix the cache for cargo payments. */
813  CargoPayment *cp;
815  cp->front->cargo_payment = cp;
817  }
818 
819  if (IsSavegameVersionBefore(72)) {
820  /* Locks in very old savegames had OWNER_WATER as owner */
821  for (TileIndex t = 0; t < MapSize(); t++) {
822  switch (GetTileType(t)) {
823  default: break;
824 
825  case MP_WATER:
827  break;
828 
829  case MP_STATION: {
830  if (HasBit(_me[t].m6, 3)) SetBit(_me[t].m6, 2);
831  StationGfx gfx = GetStationGfx(t);
832  StationType st;
833  if ( IsInsideMM(gfx, 0, 8)) { // Rail station
834  st = STATION_RAIL;
835  SetStationGfx(t, gfx - 0);
836  } else if (IsInsideMM(gfx, 8, 67)) { // Airport
837  st = STATION_AIRPORT;
838  SetStationGfx(t, gfx - 8);
839  } else if (IsInsideMM(gfx, 67, 71)) { // Truck
840  st = STATION_TRUCK;
841  SetStationGfx(t, gfx - 67);
842  } else if (IsInsideMM(gfx, 71, 75)) { // Bus
843  st = STATION_BUS;
844  SetStationGfx(t, gfx - 71);
845  } else if (gfx == 75) { // Oil rig
846  st = STATION_OILRIG;
847  SetStationGfx(t, gfx - 75);
848  } else if (IsInsideMM(gfx, 76, 82)) { // Dock
849  st = STATION_DOCK;
850  SetStationGfx(t, gfx - 76);
851  } else if (gfx == 82) { // Buoy
852  st = STATION_BUOY;
853  SetStationGfx(t, gfx - 82);
854  } else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
855  st = STATION_AIRPORT;
856  SetStationGfx(t, gfx - 83 + 67 - 8);
857  } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
858  st = STATION_TRUCK;
860  } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
861  st = STATION_BUS;
863  } else {
864  /* Restore the signals */
866  return false;
867  }
868  SB(_me[t].m6, 3, 3, st);
869  break;
870  }
871  }
872  }
873  }
874 
875  for (TileIndex t = 0; t < map_size; t++) {
876  switch (GetTileType(t)) {
877  case MP_STATION: {
879 
880  /* Set up station spread */
881  bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
882 
883  /* Waypoints don't have road stops/oil rigs in the old format */
884  if (!Station::IsExpected(bst)) break;
885  Station *st = Station::From(bst);
886 
887  switch (GetStationType(t)) {
888  case STATION_TRUCK:
889  case STATION_BUS:
890  if (IsSavegameVersionBefore(6)) {
891  /* Before version 5 you could not have more than 250 stations.
892  * Version 6 adds large maps, so you could only place 253*253
893  * road stops on a map (no freeform edges) = 64009. So, yes
894  * someone could in theory create such a full map to trigger
895  * this assertion, it's safe to assume that's only something
896  * theoretical and does not happen in normal games. */
897  assert(RoadStop::CanAllocateItem());
898 
899  /* From this version on there can be multiple road stops of the
900  * same type per station. Convert the existing stops to the new
901  * internal data structure. */
902  RoadStop *rs = new RoadStop(t);
903 
904  RoadStop **head =
905  IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
906  *head = rs;
907  }
908  break;
909 
910  case STATION_OILRIG: {
911  /* Very old savegames sometimes have phantom oil rigs, i.e.
912  * an oil rig which got shut down, but not completely removed from
913  * the map
914  */
915  TileIndex t1 = TILE_ADDXY(t, 0, 1);
916  if (IsTileType(t1, MP_INDUSTRY) &&
917  GetIndustryGfx(t1) == GFX_OILRIG_1) {
918  /* The internal encoding of oil rigs was changed twice.
919  * It was 3 (till 2.2) and later 5 (till 5.1).
920  * Setting it unconditionally does not hurt.
921  */
923  } else {
924  DeleteOilRig(t);
925  }
926  break;
927  }
928 
929  default: break;
930  }
931  break;
932  }
933 
934  default: break;
935  }
936  }
937 
938  /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
939  * This has to be called after the oilrig airport_type update above ^^^ ! */
941 
942  /* In version 6.1 we put the town index in the map-array. To do this, we need
943  * to use m2 (16bit big), so we need to clean m2, and that is where this is
944  * all about ;) */
945  if (IsSavegameVersionBefore(6, 1)) {
946  for (TileIndex t = 0; t < map_size; t++) {
947  switch (GetTileType(t)) {
948  case MP_HOUSE:
949  _m[t].m4 = _m[t].m2;
951  break;
952 
953  case MP_ROAD:
954  _m[t].m4 |= (_m[t].m2 << 4);
955  if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
957  } else {
958  SetTownIndex(t, 0);
959  }
960  break;
961 
962  default: break;
963  }
964  }
965  }
966 
967  /* Force the freeform edges to false for old savegames. */
968  if (IsSavegameVersionBefore(111)) {
970  }
971 
972  /* From version 9.0, we update the max passengers of a town (was sometimes negative
973  * before that. */
974  if (IsSavegameVersionBefore(9)) {
975  Town *t;
976  FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
977  }
978 
979  /* From version 16.0, we included autorenew on engines, which are now saved, but
980  * of course, we do need to initialize them for older savegames. */
981  if (IsSavegameVersionBefore(16)) {
982  Company *c;
983  FOR_ALL_COMPANIES(c) {
984  c->engine_renew_list = NULL;
985  c->settings.engine_renew = false;
987  c->settings.engine_renew_money = 100000;
988  }
989 
990  /* When loading a game, _local_company is not yet set to the correct value.
991  * However, in a dedicated server we are a spectator, so nothing needs to
992  * happen. In case we are not a dedicated server, the local company always
993  * becomes company 0, unless we are in the scenario editor where all the
994  * companies are 'invalid'.
995  */
997  if (!_network_dedicated && c != NULL) {
999  }
1000  }
1001 
1002  if (IsSavegameVersionBefore(48)) {
1003  for (TileIndex t = 0; t < map_size; t++) {
1004  switch (GetTileType(t)) {
1005  case MP_RAILWAY:
1006  if (IsPlainRail(t)) {
1007  /* Swap ground type and signal type for plain rail tiles, so the
1008  * ground type uses the same bits as for depots and waypoints. */
1009  uint tmp = GB(_m[t].m4, 0, 4);
1010  SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
1011  SB(_m[t].m2, 0, 4, tmp);
1012  } else if (HasBit(_m[t].m5, 2)) {
1013  /* Split waypoint and depot rail type and remove the subtype. */
1014  ClrBit(_m[t].m5, 2);
1015  ClrBit(_m[t].m5, 6);
1016  }
1017  break;
1018 
1019  case MP_ROAD:
1020  /* Swap m3 and m4, so the track type for rail crossings is the
1021  * same as for normal rail. */
1022  Swap(_m[t].m3, _m[t].m4);
1023  break;
1024 
1025  default: break;
1026  }
1027  }
1028  }
1029 
1030  if (IsSavegameVersionBefore(61)) {
1031  /* Added the RoadType */
1032  bool old_bridge = IsSavegameVersionBefore(42);
1033  for (TileIndex t = 0; t < map_size; t++) {
1034  switch (GetTileType(t)) {
1035  case MP_ROAD:
1036  SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
1037  switch (GetRoadTileType(t)) {
1038  default: SlErrorCorrupt("Invalid road tile type");
1039  case ROAD_TILE_NORMAL:
1040  SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
1041  SB(_m[t].m4, 4, 4, 0);
1042  SB(_me[t].m6, 2, 4, 0);
1043  break;
1044  case ROAD_TILE_CROSSING:
1045  SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
1046  break;
1047  case ROAD_TILE_DEPOT: break;
1048  }
1050  break;
1051 
1052  case MP_STATION:
1054  break;
1055 
1056  case MP_TUNNELBRIDGE:
1057  /* Middle part of "old" bridges */
1058  if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
1059  if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1061  }
1062  break;
1063 
1064  default: break;
1065  }
1066  }
1067  }
1068 
1069  if (IsSavegameVersionBefore(114)) {
1070  bool fix_roadtypes = !IsSavegameVersionBefore(61);
1071  bool old_bridge = IsSavegameVersionBefore(42);
1072 
1073  for (TileIndex t = 0; t < map_size; t++) {
1074  switch (GetTileType(t)) {
1075  case MP_ROAD:
1076  if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
1077  SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
1078  switch (GetRoadTileType(t)) {
1079  default: SlErrorCorrupt("Invalid road tile type");
1080  case ROAD_TILE_NORMAL:
1081  SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
1082  SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
1083  SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4)); // tram bits
1084  SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
1085  SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4)); // road bits
1086  break;
1087 
1088  case ROAD_TILE_CROSSING:
1089  SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
1090  SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
1091  SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
1092  SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1)); // road axis
1093  SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1)); // crossing state
1094  break;
1095 
1096  case ROAD_TILE_DEPOT:
1097  break;
1098  }
1099  if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1100  const Town *town = CalcClosestTownFromTile(t);
1101  if (town != NULL) SetTownIndex(t, town->index);
1102  }
1103  _m[t].m4 = 0;
1104  break;
1105 
1106  case MP_STATION:
1107  if (!IsRoadStop(t)) break;
1108 
1109  if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
1110  SB(_me[t].m7, 0, 5, HasBit(_me[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
1111  SB(_m[t].m3, 4, 4, _m[t].m1);
1112  _m[t].m4 = 0;
1113  break;
1114 
1115  case MP_TUNNELBRIDGE:
1116  if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
1117  if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1118  if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
1119 
1120  Owner o = GetTileOwner(t);
1121  SB(_me[t].m7, 0, 5, o); // road owner
1122  SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
1123  }
1124  SB(_me[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
1125  SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
1126 
1127  _m[t].m2 = 0;
1128  _m[t].m4 = 0;
1129  break;
1130 
1131  default: break;
1132  }
1133  }
1134  }
1135 
1136  if (IsSavegameVersionBefore(42)) {
1137  Vehicle *v;
1138 
1139  for (TileIndex t = 0; t < map_size; t++) {
1141  if (IsBridgeTile(t)) {
1142  if (HasBit(_m[t].m5, 6)) { // middle part
1143  Axis axis = (Axis)GB(_m[t].m5, 0, 1);
1144 
1145  if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
1146  if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
1147  MakeRailNormal(
1148  t,
1149  GetTileOwner(t),
1150  axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
1151  GetRailType(t)
1152  );
1153  } else {
1154  TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
1155 
1157  t,
1158  axis == AXIS_X ? ROAD_Y : ROAD_X,
1160  town,
1162  );
1163  }
1164  } else {
1165  if (GB(_m[t].m5, 3, 2) == 0) {
1166  MakeClear(t, CLEAR_GRASS, 3);
1167  } else {
1168  if (!IsTileFlat(t)) {
1169  MakeShore(t);
1170  } else {
1171  if (GetTileOwner(t) == OWNER_WATER) {
1172  MakeSea(t);
1173  } else {
1174  MakeCanal(t, GetTileOwner(t), Random());
1175  }
1176  }
1177  }
1178  }
1179  SetBridgeMiddle(t, axis);
1180  } else { // ramp
1181  Axis axis = (Axis)GB(_m[t].m5, 0, 1);
1182  uint north_south = GB(_m[t].m5, 5, 1);
1183  DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
1184  TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
1185 
1186  _m[t].m5 = 1 << 7 | type << 2 | dir;
1187  }
1188  }
1189  }
1190 
1191  FOR_ALL_VEHICLES(v) {
1192  if (!v->IsGroundVehicle()) continue;
1193  if (IsBridgeTile(v->tile)) {
1195 
1196  if (dir != DirToDiagDir(v->direction)) continue;
1197  switch (dir) {
1198  default: SlErrorCorrupt("Invalid vehicle direction");
1199  case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
1200  case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
1201  case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
1202  case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
1203  }
1204  } else if (v->z_pos > GetSlopePixelZ(v->x_pos, v->y_pos)) {
1205  v->tile = GetNorthernBridgeEnd(v->tile);
1206  } else {
1207  continue;
1208  }
1209  if (v->type == VEH_TRAIN) {
1210  Train::From(v)->track = TRACK_BIT_WORMHOLE;
1211  } else {
1213  }
1214  }
1215  }
1216 
1217  /* Elrails got added in rev 24 */
1218  if (IsSavegameVersionBefore(24)) {
1219  RailType min_rail = RAILTYPE_ELECTRIC;
1220 
1221  Train *v;
1222  FOR_ALL_TRAINS(v) {
1223  RailType rt = RailVehInfo(v->engine_type)->railtype;
1224 
1225  v->railtype = rt;
1226  if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
1227  }
1228 
1229  /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
1230  for (TileIndex t = 0; t < map_size; t++) {
1231  switch (GetTileType(t)) {
1232  case MP_RAILWAY:
1233  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1234  break;
1235 
1236  case MP_ROAD:
1237  if (IsLevelCrossing(t)) {
1238  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1239  }
1240  break;
1241 
1242  case MP_STATION:
1243  if (HasStationRail(t)) {
1244  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1245  }
1246  break;
1247 
1248  case MP_TUNNELBRIDGE:
1250  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1251  }
1252  break;
1253 
1254  default:
1255  break;
1256  }
1257  }
1258 
1259  FOR_ALL_TRAINS(v) {
1260  if (v->IsFrontEngine() || v->IsFreeWagon()) v->ConsistChanged(CCF_TRACK);
1261  }
1262 
1263  }
1264 
1265  /* In version 16.1 of the savegame a company can decide if trains, which get
1266  * replaced, shall keep their old length. In all prior versions, just default
1267  * to false */
1268  if (IsSavegameVersionBefore(16, 1)) {
1269  Company *c;
1270  FOR_ALL_COMPANIES(c) c->settings.renew_keep_length = false;
1271  }
1272 
1273  if (IsSavegameVersionBefore(123)) {
1274  /* Waypoints became subclasses of stations ... */
1276  /* ... and buoys were moved to waypoints. */
1278  }
1279 
1280  /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
1281  * room for PBS. Now in version 21 move it back :P. */
1283  for (TileIndex t = 0; t < map_size; t++) {
1284  switch (GetTileType(t)) {
1285  case MP_RAILWAY:
1286  if (HasSignals(t)) {
1287  /* Original signal type/variant was stored in m4 but since saveload
1288  * version 48 they are in m2. The bits has been already moved to m2
1289  * (see the code somewhere above) so don't use m4, use m2 instead. */
1290 
1291  /* convert PBS signals to combo-signals */
1292  if (HasBit(_m[t].m2, 2)) SB(_m[t].m2, 0, 2, SIGTYPE_COMBO);
1293 
1294  /* move the signal variant back */
1295  SB(_m[t].m2, 2, 1, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1296  ClrBit(_m[t].m2, 3);
1297  }
1298 
1299  /* Clear PBS reservation on track */
1300  if (!IsRailDepotTile(t)) {
1301  SB(_m[t].m4, 4, 4, 0);
1302  } else {
1303  ClrBit(_m[t].m3, 6);
1304  }
1305  break;
1306 
1307  case MP_STATION: // Clear PBS reservation on station
1308  ClrBit(_m[t].m3, 6);
1309  break;
1310 
1311  default: break;
1312  }
1313  }
1314  }
1315 
1316  if (IsSavegameVersionBefore(25)) {
1317  RoadVehicle *rv;
1318  FOR_ALL_ROADVEHICLES(rv) {
1319  rv->vehstatus &= ~0x40;
1320  }
1321  }
1322 
1323  if (IsSavegameVersionBefore(26)) {
1324  Station *st;
1325  FOR_ALL_STATIONS(st) {
1326  st->last_vehicle_type = VEH_INVALID;
1327  }
1328  }
1329 
1331 
1332  if (IsSavegameVersionBefore(34)) {
1333  Company *c;
1334  FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
1335  }
1336 
1337  Company *c;
1338  FOR_ALL_COMPANIES(c) {
1341  }
1342 
1343  if (!IsSavegameVersionBefore(27)) AfterLoadStations();
1344 
1345  /* Time starts at 0 instead of 1920.
1346  * Account for this in older games by adding an offset */
1347  if (IsSavegameVersionBefore(31)) {
1348  Station *st;
1349  Waypoint *wp;
1350  Engine *e;
1351  Industry *i;
1352  Vehicle *v;
1353 
1356 
1357  FOR_ALL_STATIONS(st) st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1359  FOR_ALL_ENGINES(e) e->intro_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1360  FOR_ALL_COMPANIES(c) c->inaugurated_year += ORIGINAL_BASE_YEAR;
1361  FOR_ALL_INDUSTRIES(i) i->last_prod_year += ORIGINAL_BASE_YEAR;
1362 
1363  FOR_ALL_VEHICLES(v) {
1366  }
1367  }
1368 
1369  /* From 32 on we save the industry who made the farmland.
1370  * To give this prettiness to old savegames, we remove all farmfields and
1371  * plant new ones. */
1372  if (IsSavegameVersionBefore(32)) {
1373  Industry *i;
1374 
1375  for (TileIndex t = 0; t < map_size; t++) {
1376  if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
1377  /* remove fields */
1378  MakeClear(t, CLEAR_GRASS, 3);
1379  }
1380  }
1381 
1382  FOR_ALL_INDUSTRIES(i) {
1383  uint j;
1384 
1386  for (j = 0; j != 50; j++) PlantRandomFarmField(i);
1387  }
1388  }
1389  }
1390 
1391  /* Setting no refit flags to all orders in savegames from before refit in orders were added */
1392  if (IsSavegameVersionBefore(36)) {
1393  Order *order;
1394  Vehicle *v;
1395 
1396  FOR_ALL_ORDERS(order) {
1397  order->SetRefit(CT_NO_REFIT);
1398  }
1399 
1400  FOR_ALL_VEHICLES(v) {
1402  }
1403  }
1404 
1405  /* from version 38 we have optional elrails, since we cannot know the
1406  * preference of a user, let elrails enabled; it can be disabled manually */
1408  /* do the same as when elrails were enabled/disabled manually just now */
1411 
1412  /* From version 53, the map array was changed for house tiles to allow
1413  * space for newhouses grf features. A new byte, m7, was also added. */
1414  if (IsSavegameVersionBefore(53)) {
1415  for (TileIndex t = 0; t < map_size; t++) {
1416  if (IsTileType(t, MP_HOUSE)) {
1417  if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
1418  /* Move the construction stage from m3[7..6] to m5[5..4].
1419  * The construction counter does not have to move. */
1420  SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
1421  SB(_m[t].m3, 6, 2, 0);
1422 
1423  /* The "house is completed" bit is now in m6[2]. */
1424  SetHouseCompleted(t, false);
1425  } else {
1426  /* The "lift has destination" bit has been moved from
1427  * m5[7] to m7[0]. */
1428  SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
1429  ClrBit(_m[t].m5, 7);
1430 
1431  /* The "lift is moving" bit has been removed, as it does
1432  * the same job as the "lift has destination" bit. */
1433  ClrBit(_m[t].m1, 7);
1434 
1435  /* The position of the lift goes from m1[7..0] to m6[7..2],
1436  * making m1 totally free, now. The lift position does not
1437  * have to be a full byte since the maximum value is 36. */
1438  SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
1439 
1440  _m[t].m1 = 0;
1441  _m[t].m3 = 0;
1442  SetHouseCompleted(t, true);
1443  }
1444  }
1445  }
1446  }
1447 
1448  /* Check and update house and town values */
1450 
1451  if (IsSavegameVersionBefore(43)) {
1452  for (TileIndex t = 0; t < map_size; t++) {
1453  if (IsTileType(t, MP_INDUSTRY)) {
1454  switch (GetIndustryGfx(t)) {
1455  case GFX_POWERPLANT_SPARKS:
1456  _m[t].m3 = GB(_m[t].m1, 2, 5);
1457  break;
1458 
1459  case GFX_OILWELL_ANIMATED_1:
1460  case GFX_OILWELL_ANIMATED_2:
1461  case GFX_OILWELL_ANIMATED_3:
1462  _m[t].m3 = GB(_m[t].m1, 0, 2);
1463  break;
1464 
1465  case GFX_COAL_MINE_TOWER_ANIMATED:
1466  case GFX_COPPER_MINE_TOWER_ANIMATED:
1467  case GFX_GOLD_MINE_TOWER_ANIMATED:
1468  _m[t].m3 = _m[t].m1;
1469  break;
1470 
1471  default: // No animation states to change
1472  break;
1473  }
1474  }
1475  }
1476  }
1477 
1478  if (IsSavegameVersionBefore(45)) {
1479  Vehicle *v;
1480  /* Originally just the fact that some cargo had been paid for was
1481  * stored to stop people cheating and cashing in several times. This
1482  * wasn't enough though as it was cleared when the vehicle started
1483  * loading again, even if it didn't actually load anything, so now the
1484  * amount that has been paid is stored. */
1485  FOR_ALL_VEHICLES(v) {
1486  ClrBit(v->vehicle_flags, 2);
1487  }
1488  }
1489 
1490  /* Buoys do now store the owner of the previous water tile, which can never
1491  * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
1492  if (IsSavegameVersionBefore(46)) {
1493  Waypoint *wp;
1494  FOR_ALL_WAYPOINTS(wp) {
1495  if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
1496  }
1497  }
1498 
1499  if (IsSavegameVersionBefore(50)) {
1500  Aircraft *v;
1501  /* Aircraft units changed from 8 mph to 1 km-ish/h */
1502  FOR_ALL_AIRCRAFT(v) {
1503  if (v->subtype <= AIR_AIRCRAFT) {
1504  const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
1505  v->cur_speed *= 128;
1506  v->cur_speed /= 10;
1507  v->acceleration = avi->acceleration;
1508  }
1509  }
1510  }
1511 
1512  if (IsSavegameVersionBefore(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
1513 
1514  if (IsSavegameVersionBefore(52)) {
1515  for (TileIndex t = 0; t < map_size; t++) {
1516  if (IsTileType(t, MP_OBJECT) && _m[t].m5 == OBJECT_STATUE) {
1518  }
1519  }
1520  }
1521 
1522  /* A setting containing the proportion of towns that grow twice as
1523  * fast was added in version 54. From version 56 this is now saved in the
1524  * town as cities can be built specifically in the scenario editor. */
1525  if (IsSavegameVersionBefore(56)) {
1526  Town *t;
1527 
1528  FOR_ALL_TOWNS(t) {
1530  t->larger_town = true;
1531  }
1532  }
1533  }
1534 
1535  if (IsSavegameVersionBefore(57)) {
1536  Vehicle *v;
1537  /* Added a FIFO queue of vehicles loading at stations */
1538  FOR_ALL_VEHICLES(v) {
1539  if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) && // for all locs
1540  !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
1541  v->current_order.IsType(OT_LOADING)) { // loading
1542  Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
1543 
1544  /* The loading finished flag is *only* set when actually completely
1545  * finished. Because the vehicle is loading, it is not finished. */
1547  }
1548  }
1549  } else if (IsSavegameVersionBefore(59)) {
1550  /* For some reason non-loading vehicles could be in the station's loading vehicle list */
1551 
1552  Station *st;
1553  FOR_ALL_STATIONS(st) {
1554  std::list<Vehicle *>::iterator iter;
1555  for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
1556  Vehicle *v = *iter;
1557  iter++;
1558  if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
1559  }
1560  }
1561  }
1562 
1563  if (IsSavegameVersionBefore(58)) {
1564  /* Setting difficulty industry_density other than zero get bumped to +1
1565  * since a new option (very low at position 1) has been added */
1568  }
1569 
1570  /* Same goes for number of towns, although no test is needed, just an increment */
1572  }
1573 
1574  if (IsSavegameVersionBefore(64)) {
1575  /* Since now we allow different signal types and variants on a single tile.
1576  * Move signal states to m4 to make room and clone the signal type/variant. */
1577  for (TileIndex t = 0; t < map_size; t++) {
1578  if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
1579  /* move signal states */
1580  SetSignalStates(t, GB(_m[t].m2, 4, 4));
1581  SB(_m[t].m2, 4, 4, 0);
1582  /* clone signal type and variant */
1583  SB(_m[t].m2, 4, 3, GB(_m[t].m2, 0, 3));
1584  }
1585  }
1586  }
1587 
1588  if (IsSavegameVersionBefore(69)) {
1589  /* In some old savegames a bit was cleared when it should not be cleared */
1590  RoadVehicle *rv;
1591  FOR_ALL_ROADVEHICLES(rv) {
1592  if (rv->state == 250 || rv->state == 251) {
1593  SetBit(rv->state, 2);
1594  }
1595  }
1596  }
1597 
1598  if (IsSavegameVersionBefore(70)) {
1599  /* Added variables to support newindustries */
1600  Industry *i;
1601  FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
1602  }
1603 
1604  /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
1605  Replace the owner for those by OWNER_NONE. */
1606  if (IsSavegameVersionBefore(82)) {
1607  for (TileIndex t = 0; t < map_size; t++) {
1608  if (IsTileType(t, MP_WATER) &&
1610  GetTileOwner(t) == OWNER_WATER &&
1611  TileHeight(t) != 0) {
1613  }
1614  }
1615  }
1616 
1617  /*
1618  * Add the 'previous' owner to the ship depots so we can reset it with
1619  * the correct values when it gets destroyed. This prevents that
1620  * someone can remove canals owned by somebody else and it prevents
1621  * making floods using the removal of ship depots.
1622  */
1623  if (IsSavegameVersionBefore(83)) {
1624  for (TileIndex t = 0; t < map_size; t++) {
1625  if (IsShipDepotTile(t)) {
1626  _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
1627  }
1628  }
1629  }
1630 
1631  if (IsSavegameVersionBefore(74)) {
1632  Station *st;
1633  FOR_ALL_STATIONS(st) {
1634  for (CargoID c = 0; c < NUM_CARGO; c++) {
1635  st->goods[c].last_speed = 0;
1636  if (st->goods[c].cargo.AvailableCount() != 0) SetBit(st->goods[c].status, GoodsEntry::GES_RATING);
1637  }
1638  }
1639  }
1640 
1641  if (IsSavegameVersionBefore(78)) {
1642  Industry *i;
1643  uint j;
1644  FOR_ALL_INDUSTRIES(i) {
1645  const IndustrySpec *indsp = GetIndustrySpec(i->type);
1646  for (j = 0; j < lengthof(i->produced_cargo); j++) {
1647  i->produced_cargo[j] = indsp->produced_cargo[j];
1648  }
1649  for (j = 0; j < lengthof(i->accepts_cargo); j++) {
1650  i->accepts_cargo[j] = indsp->accepts_cargo[j];
1651  }
1652  }
1653  }
1654 
1655  /* Before version 81, the density of grass was always stored as zero, and
1656  * grassy trees were always drawn fully grassy. Furthermore, trees on rough
1657  * land used to have zero density, now they have full density. Therefore,
1658  * make all grassy/rough land trees have a density of 3. */
1659  if (IsSavegameVersionBefore(81)) {
1660  for (TileIndex t = 0; t < map_size; t++) {
1661  if (GetTileType(t) == MP_TREES) {
1662  TreeGround groundType = (TreeGround)GB(_m[t].m2, 4, 2);
1663  if (groundType != TREE_GROUND_SNOW_DESERT) SB(_m[t].m2, 6, 2, 3);
1664  }
1665  }
1666  }
1667 
1668 
1669  if (IsSavegameVersionBefore(93)) {
1670  /* Rework of orders. */
1671  Order *order;
1672  FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
1673 
1674  Vehicle *v;
1675  FOR_ALL_VEHICLES(v) {
1676  if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && v->orders.list->GetFirstOrder()->IsType(OT_NOTHING)) {
1677  v->orders.list->FreeChain();
1678  v->orders.list = NULL;
1679  }
1680 
1682  if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
1683  FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
1684  }
1685  }
1686  } else if (IsSavegameVersionBefore(94)) {
1687  /* Unload and transfer are now mutual exclusive. */
1688  Order *order;
1689  FOR_ALL_ORDERS(order) {
1690  if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1691  order->SetUnloadType(OUFB_TRANSFER);
1692  order->SetLoadType(OLFB_NO_LOAD);
1693  }
1694  }
1695 
1696  Vehicle *v;
1697  FOR_ALL_VEHICLES(v) {
1701  }
1702  }
1703  }
1704 
1705  if (IsSavegameVersionBefore(84)) {
1706  /* Set all share owners to INVALID_COMPANY for
1707  * 1) all inactive companies
1708  * (when inactive companies were stored in the savegame - TTD, TTDP and some
1709  * *really* old revisions of OTTD; else it is already set in InitializeCompanies())
1710  * 2) shares that are owned by inactive companies or self
1711  * (caused by cheating clients in earlier revisions) */
1712  FOR_ALL_COMPANIES(c) {
1713  for (uint i = 0; i < 4; i++) {
1714  CompanyID company = c->share_owners[i];
1715  if (company == INVALID_COMPANY) continue;
1716  if (!Company::IsValidID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
1717  }
1718  }
1719  }
1720 
1721  /* The water class was moved/unified. */
1722  if (IsSavegameVersionBefore(146)) {
1723  for (TileIndex t = 0; t < map_size; t++) {
1724  switch (GetTileType(t)) {
1725  case MP_STATION:
1726  switch (GetStationType(t)) {
1727  case STATION_OILRIG:
1728  case STATION_DOCK:
1729  case STATION_BUOY:
1730  SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
1731  SB(_m[t].m3, 0, 2, 0);
1732  break;
1733 
1734  default:
1736  break;
1737  }
1738  break;
1739 
1740  case MP_WATER:
1741  SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
1742  SB(_m[t].m3, 0, 2, 0);
1743  break;
1744 
1745  case MP_OBJECT:
1747  break;
1748 
1749  default:
1750  /* No water class. */
1751  break;
1752  }
1753  }
1754  }
1755 
1756  if (IsSavegameVersionBefore(86)) {
1757  for (TileIndex t = 0; t < map_size; t++) {
1758  /* Move river flag and update canals to use water class */
1759  if (IsTileType(t, MP_WATER)) {
1760  if (GetWaterClass(t) != WATER_CLASS_RIVER) {
1761  if (IsWater(t)) {
1762  Owner o = GetTileOwner(t);
1763  if (o == OWNER_WATER) {
1764  MakeSea(t);
1765  } else {
1766  MakeCanal(t, o, Random());
1767  }
1768  } else if (IsShipDepot(t)) {
1769  Owner o = (Owner)_m[t].m4; // Original water owner
1771  }
1772  }
1773  }
1774  }
1775 
1776  /* Update locks, depots, docks and buoys to have a water class based
1777  * on its neighbouring tiles. Done after river and canal updates to
1778  * ensure neighbours are correct. */
1779  for (TileIndex t = 0; t < map_size; t++) {
1780  if (!IsTileFlat(t)) continue;
1781 
1783  if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
1784  }
1785  }
1786 
1787  if (IsSavegameVersionBefore(87)) {
1788  for (TileIndex t = 0; t < map_size; t++) {
1789  /* skip oil rigs at borders! */
1790  if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
1791  (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
1792  /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
1793  * This conversion has to be done before buoys with invalid owner are removed. */
1795  }
1796 
1797  if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
1798  Owner o = GetTileOwner(t);
1799  if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
1800  Backup<CompanyByte> cur_company(_current_company, o, FILE_LINE);
1802  cur_company.Restore();
1803  }
1804  if (IsBuoyTile(t)) {
1805  /* reset buoy owner to OWNER_NONE in the station struct
1806  * (even if it is owned by active company) */
1808  }
1809  } else if (IsTileType(t, MP_ROAD)) {
1810  /* works for all RoadTileType */
1811  for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
1812  /* update even non-existing road types to update tile owner too */
1813  Owner o = GetRoadOwner(t, rt);
1814  if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rt, OWNER_NONE);
1815  }
1816  if (IsLevelCrossing(t)) {
1818  }
1819  } else if (IsPlainRailTile(t)) {
1821  }
1822  }
1823 
1824  /* Convert old PF settings to new */
1827  } else {
1829  }
1830 
1833  } else {
1835  }
1836 
1839  } else {
1841  }
1842  }
1843 
1844  if (IsSavegameVersionBefore(88)) {
1845  /* Profits are now with 8 bit fract */
1846  Vehicle *v;
1847  FOR_ALL_VEHICLES(v) {
1848  v->profit_this_year <<= 8;
1849  v->profit_last_year <<= 8;
1850  v->running_ticks = 0;
1851  }
1852  }
1853 
1854  if (IsSavegameVersionBefore(91)) {
1855  /* Increase HouseAnimationFrame from 5 to 7 bits */
1856  for (TileIndex t = 0; t < map_size; t++) {
1857  if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
1858  SB(_me[t].m6, 2, 6, GB(_me[t].m6, 3, 5));
1859  SB(_m[t].m3, 5, 1, 0);
1860  }
1861  }
1862  }
1863 
1864  if (IsSavegameVersionBefore(62)) {
1865  /* Remove all trams from savegames without tram support.
1866  * There would be trams without tram track under causing crashes sooner or later. */
1867  RoadVehicle *v;
1868  FOR_ALL_ROADVEHICLES(v) {
1869  if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
1870  ShowErrorMessage(STR_WARNING_LOADGAME_REMOVED_TRAMS, INVALID_STRING_ID, WL_CRITICAL);
1871  delete v;
1872  }
1873  }
1874  }
1875 
1876  if (IsSavegameVersionBefore(99)) {
1877  for (TileIndex t = 0; t < map_size; t++) {
1878  /* Set newly introduced WaterClass of industry tiles */
1879  if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
1881  }
1882  if (IsTileType(t, MP_INDUSTRY)) {
1883  if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
1885  } else {
1887  }
1888  }
1889 
1890  /* Replace "house construction year" with "house age" */
1891  if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
1892  _m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
1893  }
1894  }
1895  }
1896 
1897  /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
1898  * format here, as an old layout wouldn't work properly anyway. To be safe, we
1899  * clear any possible PBS reservations as well. */
1900  if (IsSavegameVersionBefore(100)) {
1901  for (TileIndex t = 0; t < map_size; t++) {
1902  switch (GetTileType(t)) {
1903  case MP_RAILWAY:
1904  if (HasSignals(t)) {
1905  /* move the signal variant */
1906  SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1907  SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1908  ClrBit(_m[t].m2, 2);
1909  ClrBit(_m[t].m2, 6);
1910  }
1911 
1912  /* Clear PBS reservation on track */
1913  if (IsRailDepot(t)) {
1914  SetDepotReservation(t, false);
1915  } else {
1917  }
1918  break;
1919 
1920  case MP_ROAD: // Clear PBS reservation on crossing
1921  if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
1922  break;
1923 
1924  case MP_STATION: // Clear PBS reservation on station
1925  if (HasStationRail(t)) SetRailStationReservation(t, false);
1926  break;
1927 
1928  case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/bridges
1930  break;
1931 
1932  default: break;
1933  }
1934  }
1935  }
1936 
1937  /* Reserve all tracks trains are currently on. */
1938  if (IsSavegameVersionBefore(101)) {
1939  const Train *t;
1940  FOR_ALL_TRAINS(t) {
1941  if (t->First() == t) t->ReserveTrackUnderConsist();
1942  }
1943  }
1944 
1945  if (IsSavegameVersionBefore(102)) {
1946  for (TileIndex t = 0; t < map_size; t++) {
1947  /* Now all crossings should be in correct state */
1948  if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
1949  }
1950  }
1951 
1952  if (IsSavegameVersionBefore(103)) {
1953  /* Non-town-owned roads now store the closest town */
1955 
1956  /* signs with invalid owner left from older savegames */
1957  Sign *si;
1958  FOR_ALL_SIGNS(si) {
1959  if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
1960  }
1961 
1962  /* Station can get named based on an industry type, but the current ones
1963  * are not, so mark them as if they are not named by an industry. */
1964  Station *st;
1965  FOR_ALL_STATIONS(st) {
1966  st->indtype = IT_INVALID;
1967  }
1968  }
1969 
1970  if (IsSavegameVersionBefore(104)) {
1971  Aircraft *a;
1972  FOR_ALL_AIRCRAFT(a) {
1973  /* Set engine_type of shadow and rotor */
1974  if (!a->IsNormalAircraft()) {
1975  a->engine_type = a->First()->engine_type;
1976  }
1977  }
1978 
1979  /* More companies ... */
1980  Company *c;
1981  FOR_ALL_COMPANIES(c) {
1982  if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
1983  }
1984 
1985  Engine *e;
1986  FOR_ALL_ENGINES(e) {
1987  if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
1988  }
1989 
1990  Town *t;
1991  FOR_ALL_TOWNS(t) {
1992  if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
1993  for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1994  }
1995  }
1996 
1997  if (IsSavegameVersionBefore(112)) {
1998  for (TileIndex t = 0; t < map_size; t++) {
1999  /* Check for HQ bit being set, instead of using map accessor,
2000  * since we've already changed it code-wise */
2001  if (IsTileType(t, MP_OBJECT) && HasBit(_m[t].m5, 7)) {
2002  /* Move size and part identification of HQ out of the m5 attribute,
2003  * on new locations */
2004  _m[t].m3 = GB(_m[t].m5, 0, 5);
2005  _m[t].m5 = OBJECT_HQ;
2006  }
2007  }
2008  }
2009  if (IsSavegameVersionBefore(144)) {
2010  for (TileIndex t = 0; t < map_size; t++) {
2011  if (!IsTileType(t, MP_OBJECT)) continue;
2012 
2013  /* Reordering/generalisation of the object bits. */
2014  ObjectType type = _m[t].m5;
2015  SB(_me[t].m6, 2, 4, type == OBJECT_HQ ? GB(_m[t].m3, 2, 3) : 0);
2016  _m[t].m3 = type == OBJECT_HQ ? GB(_m[t].m3, 1, 1) | GB(_m[t].m3, 0, 1) << 4 : 0;
2017 
2018  /* Make sure those bits are clear as well! */
2019  _m[t].m4 = 0;
2020  _me[t].m7 = 0;
2021  }
2022  }
2023 
2024  if (IsSavegameVersionBefore(147) && Object::GetNumItems() == 0) {
2025  /* Make real objects for object tiles. */
2026  for (TileIndex t = 0; t < map_size; t++) {
2027  if (!IsTileType(t, MP_OBJECT)) continue;
2028 
2029  if (Town::GetNumItems() == 0) {
2030  /* No towns, so remove all objects! */
2031  DoClearSquare(t);
2032  } else {
2033  uint offset = _m[t].m3;
2034 
2035  /* Also move the animation state. */
2036  _m[t].m3 = GB(_me[t].m6, 2, 4);
2037  SB(_me[t].m6, 2, 4, 0);
2038 
2039  if (offset == 0) {
2040  /* No offset, so make the object. */
2041  ObjectType type = _m[t].m5;
2042  int size = type == OBJECT_HQ ? 2 : 1;
2043 
2044  if (!Object::CanAllocateItem()) {
2045  /* Nice... you managed to place 64k lighthouses and
2046  * antennae on the map... boohoo. */
2047  SlError(STR_ERROR_TOO_MANY_OBJECTS);
2048  }
2049 
2050  Object *o = new Object();
2051  o->location.tile = t;
2052  o->location.w = size;
2053  o->location.h = size;
2054  o->build_date = _date;
2055  o->town = type == OBJECT_STATUE ? Town::Get(_m[t].m2) : CalcClosestTownFromTile(t, UINT_MAX);
2056  _m[t].m2 = o->index;
2057  Object::IncTypeCount(type);
2058  } else {
2059  /* We're at an offset, so get the ID from our "root". */
2060  TileIndex northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
2061  assert(IsTileType(northern_tile, MP_OBJECT));
2062  _m[t].m2 = _m[northern_tile].m2;
2063  }
2064  }
2065  }
2066  }
2067 
2068  if (IsSavegameVersionBefore(113)) {
2069  /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
2070  if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
2073  } else {
2076  }
2077 
2078  /* Initialize layout of all towns. Older versions were using different
2079  * generator for random town layout, use it if needed. */
2080  Town *t;
2081  FOR_ALL_TOWNS(t) {
2084  continue;
2085  }
2086 
2087  /* Use old layout randomizer code */
2088  byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
2089  switch (layout) {
2090  default: break;
2091  case 5: layout = 1; break;
2092  case 0: layout = 2; break;
2093  }
2094  t->layout = layout - 1;
2095  }
2096  }
2097 
2098  if (IsSavegameVersionBefore(114)) {
2099  /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
2100  * The conversion affects oil rigs and buoys too, but it doesn't matter as
2101  * they have st->owner == OWNER_NONE already. */
2102  Station *st;
2103  FOR_ALL_STATIONS(st) {
2104  if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
2105  }
2106  }
2107 
2108  /* Trains could now stop in a specific location. */
2109  if (IsSavegameVersionBefore(117)) {
2110  Order *o;
2111  FOR_ALL_ORDERS(o) {
2112  if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
2113  }
2114  }
2115 
2116  if (IsSavegameVersionBefore(120)) {
2118  Company *c;
2119  FOR_ALL_COMPANIES(c) {
2120  c->settings.vehicle = _old_vds;
2121  }
2122  }
2123 
2124  if (IsSavegameVersionBefore(121)) {
2125  /* Delete small ufos heading for non-existing vehicles */
2126  Vehicle *v;
2128  if (v->subtype == 2 /* ST_SMALL_UFO */ && v->current_order.GetDestination() != 0) {
2129  const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
2130  if (u == NULL || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
2131  delete v;
2132  }
2133  }
2134  }
2135 
2136  /* We didn't store cargo payment yet, so make them for vehicles that are
2137  * currently at a station and loading/unloading. If they don't get any
2138  * payment anymore they just removed in the next load/unload cycle.
2139  * However, some 0.7 versions might have cargo payment. For those we just
2140  * add cargopayment for the vehicles that don't have it.
2141  */
2142  Station *st;
2143  FOR_ALL_STATIONS(st) {
2144  std::list<Vehicle *>::iterator iter;
2145  for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
2146  /* There are always as many CargoPayments as Vehicles. We need to make the
2147  * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
2150  Vehicle *v = *iter;
2151  if (v->cargo_payment == NULL) v->cargo_payment = new CargoPayment(v);
2152  }
2153  }
2154  }
2155 
2156  if (IsSavegameVersionBefore(122)) {
2157  /* Animated tiles would sometimes not be actually animated or
2158  * in case of old savegames duplicate. */
2159 
2161  extern uint _animated_tile_count;
2162 
2163  for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
2164  /* Remove if tile is not animated */
2165  bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == NULL;
2166 
2167  /* and remove if duplicate */
2168  for (uint j = 0; !remove && j < i; j++) {
2169  remove = _animated_tile_list[i] == _animated_tile_list[j];
2170  }
2171 
2172  if (remove) {
2173  DeleteAnimatedTile(_animated_tile_list[i]);
2174  } else {
2175  i++;
2176  }
2177  }
2178  }
2179 
2181  /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
2182  Waypoint *wp;
2183  FOR_ALL_WAYPOINTS(wp) {
2184  if (wp->facilities & FACIL_TRAIN) {
2185  wp->train_station.tile = wp->xy;
2186  wp->train_station.w = 1;
2187  wp->train_station.h = 1;
2188  } else {
2190  wp->train_station.w = 0;
2191  wp->train_station.h = 0;
2192  }
2193  }
2194  }
2195 
2196  if (IsSavegameVersionBefore(125)) {
2197  /* Convert old subsidies */
2198  Subsidy *s;
2199  FOR_ALL_SUBSIDIES(s) {
2200  if (s->remaining < 12) {
2201  /* Converting nonawarded subsidy */
2202  s->remaining = 12 - s->remaining; // convert "age" to "remaining"
2203  s->awarded = INVALID_COMPANY; // not awarded to anyone
2204  const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2205  switch (cs->town_effect) {
2206  case TE_PASSENGERS:
2207  case TE_MAIL:
2208  /* Town -> Town */
2209  s->src_type = s->dst_type = ST_TOWN;
2210  if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2211  break;
2212  case TE_GOODS:
2213  case TE_FOOD:
2214  /* Industry -> Town */
2215  s->src_type = ST_INDUSTRY;
2216  s->dst_type = ST_TOWN;
2217  if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2218  break;
2219  default:
2220  /* Industry -> Industry */
2221  s->src_type = s->dst_type = ST_INDUSTRY;
2222  if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
2223  break;
2224  }
2225  } else {
2226  /* Do our best for awarded subsidies. The original source or destination industry
2227  * can't be determined anymore for awarded subsidies, so invalidate them.
2228  * Town -> Town subsidies are converted using simple heuristic */
2229  s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
2230  const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2231  switch (cs->town_effect) {
2232  case TE_PASSENGERS:
2233  case TE_MAIL: {
2234  /* Town -> Town */
2235  const Station *ss = Station::GetIfValid(s->src);
2236  const Station *sd = Station::GetIfValid(s->dst);
2237  if (ss != NULL && sd != NULL && ss->owner == sd->owner &&
2238  Company::IsValidID(ss->owner)) {
2239  s->src_type = s->dst_type = ST_TOWN;
2240  s->src = ss->town->index;
2241  s->dst = sd->town->index;
2242  s->awarded = ss->owner;
2243  continue;
2244  }
2245  break;
2246  }
2247  default:
2248  break;
2249  }
2250  }
2251  /* Awarded non-town subsidy or invalid source/destination, invalidate */
2252  delete s;
2253  }
2254  }
2255 
2256  if (IsSavegameVersionBefore(126)) {
2257  /* Recompute inflation based on old unround loan limit
2258  * Note: Max loan is 500000. With an inflation of 4% across 170 years
2259  * that results in a max loan of about 0.7 * 2^31.
2260  * So taking the 16 bit fractional part into account there are plenty of bits left
2261  * for unmodified savegames ...
2262  */
2263  uint64 aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
2264 
2265  /* ... well, just clamp it then. */
2266  if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
2267 
2268  /* Simulate the inflation, so we also get the payment inflation */
2269  while (_economy.inflation_prices < aimed_inflation) {
2270  if (AddInflation(false)) break;
2271  }
2272  }
2273 
2274  if (IsSavegameVersionBefore(128)) {
2275  const Depot *d;
2276  FOR_ALL_DEPOTS(d) {
2277  _m[d->xy].m2 = d->index;
2278  if (IsTileType(d->xy, MP_WATER)) _m[GetOtherShipDepotTile(d->xy)].m2 = d->index;
2279  }
2280  }
2281 
2282  /* The behaviour of force_proceed has been changed. Now
2283  * it counts signals instead of some random time out. */
2284  if (IsSavegameVersionBefore(131)) {
2285  Train *t;
2286  FOR_ALL_TRAINS(t) {
2287  if (t->force_proceed != TFP_NONE) {
2288  t->force_proceed = TFP_STUCK;
2289  }
2290  }
2291  }
2292 
2293  /* The bits for the tree ground and tree density have
2294  * been swapped (m2 bits 7..6 and 5..4. */
2295  if (IsSavegameVersionBefore(135)) {
2296  for (TileIndex t = 0; t < map_size; t++) {
2297  if (IsTileType(t, MP_CLEAR)) {
2298  if (GetRawClearGround(t) == CLEAR_SNOW) {
2300  SetBit(_m[t].m3, 4);
2301  } else {
2302  ClrBit(_m[t].m3, 4);
2303  }
2304  }
2305  if (IsTileType(t, MP_TREES)) {
2306  uint density = GB(_m[t].m2, 6, 2);
2307  uint ground = GB(_m[t].m2, 4, 2);
2308  uint counter = GB(_m[t].m2, 0, 4);
2309  _m[t].m2 = ground << 6 | density << 4 | counter;
2310  }
2311  }
2312  }
2313 
2314  /* Wait counter and load/unload ticks got split. */
2315  if (IsSavegameVersionBefore(136)) {
2316  Aircraft *a;
2317  FOR_ALL_AIRCRAFT(a) {
2318  a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
2319  }
2320 
2321  Train *t;
2322  FOR_ALL_TRAINS(t) {
2323  t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
2324  }
2325  }
2326 
2327  /* Airport tile animation uses animation frame instead of other graphics id */
2328  if (IsSavegameVersionBefore(137)) {
2329  struct AirportTileConversion {
2330  byte old_start;
2331  byte num_frames;
2332  };
2333  static const AirportTileConversion atc[] = {
2334  {31, 12}, // APT_RADAR_GRASS_FENCE_SW
2335  {50, 4}, // APT_GRASS_FENCE_NE_FLAG
2336  {62, 2}, // 1 unused tile
2337  {66, 12}, // APT_RADAR_FENCE_SW
2338  {78, 12}, // APT_RADAR_FENCE_NE
2339  {101, 10}, // 9 unused tiles
2340  {111, 8}, // 7 unused tiles
2341  {119, 15}, // 14 unused tiles (radar)
2342  {140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
2343  };
2344  for (TileIndex t = 0; t < map_size; t++) {
2345  if (IsAirportTile(t)) {
2346  StationGfx old_gfx = GetStationGfx(t);
2347  byte offset = 0;
2348  for (uint i = 0; i < lengthof(atc); i++) {
2349  if (old_gfx < atc[i].old_start) {
2350  SetStationGfx(t, old_gfx - offset);
2351  break;
2352  }
2353  if (old_gfx < atc[i].old_start + atc[i].num_frames) {
2354  SetAnimationFrame(t, old_gfx - atc[i].old_start);
2355  SetStationGfx(t, atc[i].old_start - offset);
2356  break;
2357  }
2358  offset += atc[i].num_frames - 1;
2359  }
2360  }
2361  }
2362  }
2363 
2364  if (IsSavegameVersionBefore(140)) {
2365  Station *st;
2366  FOR_ALL_STATIONS(st) {
2367  if (st->airport.tile != INVALID_TILE) {
2368  st->airport.w = st->airport.GetSpec()->size_x;
2369  st->airport.h = st->airport.GetSpec()->size_y;
2370  }
2371  }
2372  }
2373 
2374  if (IsSavegameVersionBefore(141)) {
2375  for (TileIndex t = 0; t < map_size; t++) {
2376  /* Reset tropic zone for VOID tiles, they shall not have any. */
2378  }
2379 
2380  /* We need to properly number/name the depots.
2381  * The first step is making sure none of the depots uses the
2382  * 'default' names, after that we can assign the names. */
2383  Depot *d;
2384  FOR_ALL_DEPOTS(d) d->town_cn = UINT16_MAX;
2385 
2386  FOR_ALL_DEPOTS(d) MakeDefaultName(d);
2387  }
2388 
2389  if (IsSavegameVersionBefore(142)) {
2390  Depot *d;
2391  FOR_ALL_DEPOTS(d) d->build_date = _date;
2392  }
2393 
2394  /* In old versions it was possible to remove an airport while a plane was
2395  * taking off or landing. This gives all kind of problems when building
2396  * another airport in the same station so we don't allow that anymore.
2397  * For old savegames with such aircraft we just throw them in the air and
2398  * treat the aircraft like they were flying already. */
2399  if (IsSavegameVersionBefore(146)) {
2400  Aircraft *v;
2401  FOR_ALL_AIRCRAFT(v) {
2402  if (!v->IsNormalAircraft()) continue;
2404  if (st == NULL && v->state != FLYING) {
2405  v->state = FLYING;
2408  /* get aircraft back on running altitude */
2409  if ((v->vehstatus & VS_CRASHED) == 0) {
2410  GetAircraftFlightLevelBounds(v, &v->z_pos, NULL);
2411  SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
2412  }
2413  }
2414  }
2415  }
2416 
2417  /* Move the animation frame to the same location (m7) for all objects. */
2418  if (IsSavegameVersionBefore(147)) {
2419  for (TileIndex t = 0; t < map_size; t++) {
2420  switch (GetTileType(t)) {
2421  case MP_HOUSE:
2422  if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
2423  uint per_proc = _me[t].m7;
2424  _me[t].m7 = GB(_me[t].m6, 2, 6) | (GB(_m[t].m3, 5, 1) << 6);
2425  SB(_m[t].m3, 5, 1, 0);
2426  SB(_me[t].m6, 2, 6, min(per_proc, 63));
2427  }
2428  break;
2429 
2430  case MP_INDUSTRY: {
2431  uint rand = _me[t].m7;
2432  _me[t].m7 = _m[t].m3;
2433  _m[t].m3 = rand;
2434  break;
2435  }
2436 
2437  case MP_OBJECT:
2438  _me[t].m7 = _m[t].m3;
2439  _m[t].m3 = 0;
2440  break;
2441 
2442  default:
2443  /* For stations/airports it's already at m7 */
2444  break;
2445  }
2446  }
2447  }
2448 
2449  /* Add (random) colour to all objects. */
2450  if (IsSavegameVersionBefore(148)) {
2451  Object *o;
2452  FOR_ALL_OBJECTS(o) {
2453  Owner owner = GetTileOwner(o->location.tile);
2454  o->colour = (owner == OWNER_NONE) ? Random() & 0xF : Company::Get(owner)->livery->colour1;
2455  }
2456  }
2457 
2458  if (IsSavegameVersionBefore(149)) {
2459  for (TileIndex t = 0; t < map_size; t++) {
2460  if (!IsTileType(t, MP_STATION)) continue;
2461  if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && IsTileFlat(t))) {
2463  }
2464  }
2465 
2466  /* Waypoints with custom name may have a non-unique town_cn,
2467  * renumber those. First set all affected waypoints to the
2468  * highest possible number to get them numbered in the
2469  * order they have in the pool. */
2470  Waypoint *wp;
2471  FOR_ALL_WAYPOINTS(wp) {
2472  if (wp->name != NULL) wp->town_cn = UINT16_MAX;
2473  }
2474 
2475  FOR_ALL_WAYPOINTS(wp) {
2476  if (wp->name != NULL) MakeDefaultName(wp);
2477  }
2478  }
2479 
2480  if (IsSavegameVersionBefore(152)) {
2481  _industry_builder.Reset(); // Initialize industry build data.
2482 
2483  /* The moment vehicles go from hidden to visible changed. This means
2484  * that vehicles don't always get visible anymore causing things to
2485  * get messed up just after loading the savegame. This fixes that. */
2486  Vehicle *v;
2487  FOR_ALL_VEHICLES(v) {
2488  /* Not all vehicle types can be inside a tunnel. Furthermore,
2489  * testing IsTunnelTile() for invalid tiles causes a crash. */
2490  if (!v->IsGroundVehicle()) continue;
2491 
2492  /* Is the vehicle in a tunnel? */
2493  if (!IsTunnelTile(v->tile)) continue;
2494 
2495  /* Is the vehicle actually at a tunnel entrance/exit? */
2496  TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
2497  if (!IsTunnelTile(vtile)) continue;
2498 
2499  /* Are we actually in this tunnel? Or maybe a lower tunnel? */
2500  if (GetSlopePixelZ(v->x_pos, v->y_pos) != v->z_pos) continue;
2501 
2502  /* What way are we going? */
2503  const DiagDirection dir = GetTunnelBridgeDirection(vtile);
2504  const DiagDirection vdir = DirToDiagDir(v->direction);
2505 
2506  /* Have we passed the visibility "switch" state already? */
2507  byte pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
2508  byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2509  extern const byte _tunnel_visibility_frame[DIAGDIR_END];
2510 
2511  /* Should the vehicle be hidden or not? */
2512  bool hidden;
2513  if (dir == vdir) { // Entering tunnel
2514  hidden = frame >= _tunnel_visibility_frame[dir];
2515  v->tile = vtile;
2516  } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
2517  hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
2518  /* v->tile changes at the moment when the vehicle leaves the tunnel. */
2519  v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
2520  } else {
2521  /* We could get here in two cases:
2522  * - for road vehicles, it is reversing at the end of the tunnel
2523  * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
2524  * Whatever case it is, do not change anything and use the old values.
2525  * Especially changing RV's state would break its reversing in the middle. */
2526  continue;
2527  }
2528 
2529  if (hidden) {
2530  v->vehstatus |= VS_HIDDEN;
2531 
2532  switch (v->type) {
2533  case VEH_TRAIN: Train::From(v)->track = TRACK_BIT_WORMHOLE; break;
2534  case VEH_ROAD: RoadVehicle::From(v)->state = RVSB_WORMHOLE; break;
2535  default: NOT_REACHED();
2536  }
2537  } else {
2538  v->vehstatus &= ~VS_HIDDEN;
2539 
2540  switch (v->type) {
2541  case VEH_TRAIN: Train::From(v)->track = DiagDirToDiagTrackBits(vdir); break;
2542  case VEH_ROAD: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
2543  default: NOT_REACHED();
2544  }
2545  }
2546  }
2547  }
2548 
2549  if (IsSavegameVersionBefore(153)) {
2550  RoadVehicle *rv;
2551  FOR_ALL_ROADVEHICLES(rv) {
2552  if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
2553 
2554  bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
2555  if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
2556  extern const byte _road_stop_stop_frame[];
2557  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)]);
2558  } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
2559  SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
2560  }
2561  }
2562  }
2563 
2564  if (IsSavegameVersionBefore(156)) {
2565  /* The train's pathfinder lost flag got moved. */
2566  Train *t;
2567  FOR_ALL_TRAINS(t) {
2568  if (!HasBit(t->flags, 5)) continue;
2569 
2570  ClrBit(t->flags, 5);
2572  }
2573 
2574  /* Introduced terraform/clear limits. */
2575  Company *c;
2576  FOR_ALL_COMPANIES(c) {
2579  }
2580  }
2581 
2582  if (IsSavegameVersionBefore(158)) {
2583  Vehicle *v;
2584  FOR_ALL_VEHICLES(v) {
2585  switch (v->type) {
2586  case VEH_TRAIN: {
2587  Train *t = Train::From(v);
2588 
2589  /* Clear old GOINGUP / GOINGDOWN flags.
2590  * It was changed in savegame version 139, but savegame
2591  * version 158 doesn't use these bits, so it doesn't hurt
2592  * to clear them unconditionally. */
2593  ClrBit(t->flags, 1);
2594  ClrBit(t->flags, 2);
2595 
2596  /* Clear both bits first. */
2599 
2600  /* Crashed vehicles can't be going up/down. */
2601  if (t->vehstatus & VS_CRASHED) break;
2602 
2603  /* Only X/Y tracks can be sloped. */
2604  if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
2605 
2607  break;
2608  }
2609  case VEH_ROAD: {
2610  RoadVehicle *rv = RoadVehicle::From(v);
2613 
2614  /* Crashed vehicles can't be going up/down. */
2615  if (rv->vehstatus & VS_CRASHED) break;
2616 
2617  if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
2618 
2619  TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, rv->compatible_roadtypes);
2620  TrackBits trackbits = TrackStatusToTrackBits(ts);
2621 
2622  /* Only X/Y tracks can be sloped. */
2623  if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
2624 
2625  Direction dir = rv->direction;
2626 
2627  /* Test if we are reversing. */
2628  Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
2629  if (AxisToDirection(a) != dir &&
2630  AxisToDirection(a) != ReverseDir(dir)) {
2631  /* When reversing, the road vehicle is on the edge of the tile,
2632  * so it can be safely compared to the middle of the tile. */
2633  dir = INVALID_DIR;
2634  }
2635 
2636  rv->gv_flags |= FixVehicleInclination(rv, dir);
2637  break;
2638  }
2639  case VEH_SHIP:
2640  break;
2641 
2642  default:
2643  continue;
2644  }
2645 
2646  if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2647  /* In old versions, z_pos was 1 unit lower on bridge heads.
2648  * However, this invalid state could be converted to new savegames
2649  * by loading and saving the game in a new version. */
2650  v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos);
2652  if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
2653  v->direction != DiagDirToDir(dir)) {
2654  /* If the train has left the bridge, it shouldn't have
2655  * track == TRACK_BIT_WORMHOLE - this could happen
2656  * when the train was reversed while on the last "tick"
2657  * on the ramp before leaving the ramp to the bridge. */
2658  Train::From(v)->track = DiagDirToDiagTrackBits(dir);
2659  }
2660  }
2661 
2662  /* If the vehicle is really above v->tile (not in a wormhole),
2663  * it should have set v->z_pos correctly. */
2664  assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos));
2665  }
2666 
2667  /* Fill Vehicle::cur_real_order_index */
2668  FOR_ALL_VEHICLES(v) {
2669  if (!v->IsPrimaryVehicle()) continue;
2670 
2671  /* Older versions are less strict with indices being in range and fix them on the fly */
2673 
2675  v->UpdateRealOrderIndex();
2676  }
2677  }
2678 
2679  if (IsSavegameVersionBefore(159)) {
2680  /* If the savegame is old (before version 100), then the value of 255
2681  * for these settings did not mean "disabled". As such everything
2682  * before then did reverse.
2683  * To simplify stuff we disable all turning around or we do not
2684  * disable anything at all. So, if some reversing was disabled we
2685  * will keep reversing disabled, otherwise it'll be turned on. */
2687 
2688  Train *t;
2689  FOR_ALL_TRAINS(t) {
2691  }
2692  }
2693 
2694  if (IsSavegameVersionBefore(160)) {
2695  /* Setting difficulty industry_density other than zero get bumped to +1
2696  * since a new option (minimal at position 1) has been added */
2699  }
2700  }
2701 
2702  if (IsSavegameVersionBefore(161)) {
2703  /* Before savegame version 161, persistent storages were not stored in a pool. */
2704 
2705  if (!IsSavegameVersionBefore(76)) {
2706  Industry *ind;
2707  FOR_ALL_INDUSTRIES(ind) {
2708  assert(ind->psa != NULL);
2709 
2710  /* Check if the old storage was empty. */
2711  bool is_empty = true;
2712  for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
2713  if (ind->psa->GetValue(i) != 0) {
2714  is_empty = false;
2715  break;
2716  }
2717  }
2718 
2719  if (!is_empty) {
2720  ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
2721  } else {
2722  delete ind->psa;
2723  ind->psa = NULL;
2724  }
2725  }
2726  }
2727 
2728  if (!IsSavegameVersionBefore(145)) {
2729  Station *st;
2730  FOR_ALL_STATIONS(st) {
2731  if (!(st->facilities & FACIL_AIRPORT)) continue;
2732  assert(st->airport.psa != NULL);
2733 
2734  /* Check if the old storage was empty. */
2735  bool is_empty = true;
2736  for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
2737  if (st->airport.psa->GetValue(i) != 0) {
2738  is_empty = false;
2739  break;
2740  }
2741  }
2742 
2743  if (!is_empty) {
2744  st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
2745  } else {
2746  delete st->airport.psa;
2747  st->airport.psa = NULL;
2748 
2749  }
2750  }
2751  }
2752  }
2753 
2754  /* This triggers only when old snow_lines were copied into the snow_line_height. */
2757  }
2758 
2760  /* We store 4 fences in the field tiles instead of only SE and SW. */
2761  for (TileIndex t = 0; t < map_size; t++) {
2762  if (!IsTileType(t, MP_CLEAR) && !IsTileType(t, MP_TREES)) continue;
2763  if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) continue;
2764  uint fence = GB(_m[t].m4, 5, 3);
2765  if (fence != 0 && IsTileType(TILE_ADDXY(t, 1, 0), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 1, 0), CLEAR_FIELDS)) {
2766  SetFence(TILE_ADDXY(t, 1, 0), DIAGDIR_NE, fence);
2767  }
2768  fence = GB(_m[t].m4, 2, 3);
2769  if (fence != 0 && IsTileType(TILE_ADDXY(t, 0, 1), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 0, 1), CLEAR_FIELDS)) {
2770  SetFence(TILE_ADDXY(t, 0, 1), DIAGDIR_NW, fence);
2771  }
2772  SB(_m[t].m4, 2, 3, 0);
2773  SB(_m[t].m4, 5, 3, 0);
2774  }
2775  }
2776 
2777  /* The center of train vehicles was changed, fix up spacing. */
2779 
2780  if (IsSavegameVersionBefore(165)) {
2781  Town *t;
2782 
2783  FOR_ALL_TOWNS(t) {
2784  /* Set the default cargo requirement for town growth */
2786  case LT_ARCTIC:
2788  break;
2789 
2790  case LT_TROPIC:
2793  break;
2794  }
2795  }
2796  }
2797 
2798  if (IsSavegameVersionBefore(165)) {
2799  /* Adjust zoom level to account for new levels */
2800  _saved_scrollpos_zoom = _saved_scrollpos_zoom + ZOOM_LVL_SHIFT;
2801  _saved_scrollpos_x *= ZOOM_LVL_BASE;
2802  _saved_scrollpos_y *= ZOOM_LVL_BASE;
2803  }
2804 
2805  /* When any NewGRF has been changed the availability of some vehicles might
2806  * have been changed too. e->company_avail must be set to 0 in that case
2807  * which is done by StartupEngines(). */
2808  if (gcf_res != GLC_ALL_GOOD) StartupEngines();
2809 
2810  if (IsSavegameVersionBefore(166)) {
2811  /* Update cargo acceptance map of towns. */
2812  for (TileIndex t = 0; t < map_size; t++) {
2813  if (!IsTileType(t, MP_HOUSE)) continue;
2814  Town::Get(GetTownIndex(t))->cargo_accepted.Add(t);
2815  }
2816 
2817  Town *town;
2818  FOR_ALL_TOWNS(town) {
2819  UpdateTownCargoes(town);
2820  }
2821  }
2822 
2823  /* The road owner of standard road stops was not properly accounted for. */
2824  if (IsSavegameVersionBefore(172)) {
2825  for (TileIndex t = 0; t < map_size; t++) {
2826  if (!IsStandardRoadStopTile(t)) continue;
2827  Owner o = GetTileOwner(t);
2828  SetRoadOwner(t, ROADTYPE_ROAD, o);
2829  SetRoadOwner(t, ROADTYPE_TRAM, o);
2830  }
2831  }
2832 
2833  if (IsSavegameVersionBefore(175)) {
2834  /* Introduced tree planting limit. */
2835  Company *c;
2836  FOR_ALL_COMPANIES(c) c->tree_limit = _settings_game.construction.tree_frame_burst << 16;
2837  }
2838 
2839  if (IsSavegameVersionBefore(177)) {
2840  /* Fix too high inflation rates */
2841  if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
2843 
2844  /* We have to convert the quarters of bankruptcy into months of bankruptcy */
2845  FOR_ALL_COMPANIES(c) {
2847  }
2848  }
2849 
2850  if (IsSavegameVersionBefore(178)) {
2851  extern uint8 _old_diff_level;
2852  /* Initialise script settings profile */
2853  _settings_game.script.settings_profile = IsInsideMM(_old_diff_level, SP_BEGIN, SP_END) ? _old_diff_level : (uint)SP_MEDIUM;
2854  }
2855 
2856  if (IsSavegameVersionBefore(182)) {
2857  Aircraft *v;
2858  /* Aircraft acceleration variable was bonkers */
2859  FOR_ALL_AIRCRAFT(v) {
2860  if (v->subtype <= AIR_AIRCRAFT) {
2861  const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
2862  v->acceleration = avi->acceleration;
2863  }
2864  }
2865 
2866  /* Blocked tiles could be reserved due to a bug, which causes
2867  * other places to assert upon e.g. station reconstruction. */
2868  for (TileIndex t = 0; t < map_size; t++) {
2870  SetRailStationReservation(t, false);
2871  }
2872  }
2873  }
2874 
2875  if (IsSavegameVersionBefore(184)) {
2876  /* The global units configuration is split up in multiple configurations. */
2877  extern uint8 _old_units;
2878  _settings_game.locale.units_velocity = Clamp(_old_units, 0, 2);
2879  _settings_game.locale.units_power = Clamp(_old_units, 0, 2);
2880  _settings_game.locale.units_weight = Clamp(_old_units, 1, 2);
2881  _settings_game.locale.units_volume = Clamp(_old_units, 1, 2);
2883  _settings_game.locale.units_height = Clamp(_old_units, 0, 2);
2884  }
2885 
2886  if (IsSavegameVersionBefore(186)) {
2887  /* Move ObjectType from map to pool */
2888  for (TileIndex t = 0; t < map_size; t++) {
2889  if (IsTileType(t, MP_OBJECT)) {
2890  Object *o = Object::Get(_m[t].m2);
2891  o->type = _m[t].m5;
2892  _m[t].m5 = 0; // zero upper bits of (now bigger) ObjectID
2893  }
2894  }
2895  }
2896 
2897  if (IsSavegameVersionBefore(188)) {
2898  /* Fix articulated road vehicles.
2899  * Some curves were shorter than other curves.
2900  * Now they have the same length, but that means that trailing articulated parts will
2901  * take longer to go through the curve than the parts in front which already left the courve.
2902  * So, make articulated parts catch up. */
2903  RoadVehicle *v;
2904  bool roadside = _settings_game.vehicle.road_side == 1;
2905  SmallVector<uint, 16> skip_frames;
2906  FOR_ALL_ROADVEHICLES(v) {
2907  if (!v->IsFrontEngine()) continue;
2908  skip_frames.Clear();
2909  TileIndex prev_tile = v->tile;
2910  uint prev_tile_skip = 0;
2911  uint cur_skip = 0;
2912  for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
2913  if (u->tile != prev_tile) {
2914  prev_tile_skip = cur_skip;
2915  prev_tile = u->tile;
2916  } else {
2917  cur_skip = prev_tile_skip;
2918  }
2919 
2920  uint *this_skip = skip_frames.Append();
2921  *this_skip = prev_tile_skip;
2922 
2923  /* The following 3 curves now take longer than before */
2924  switch (u->state) {
2925  case 2:
2926  cur_skip++;
2927  if (u->frame <= (roadside ? 9 : 5)) *this_skip = cur_skip;
2928  break;
2929 
2930  case 4:
2931  cur_skip++;
2932  if (u->frame <= (roadside ? 5 : 9)) *this_skip = cur_skip;
2933  break;
2934 
2935  case 5:
2936  cur_skip++;
2937  if (u->frame <= (roadside ? 4 : 2)) *this_skip = cur_skip;
2938  break;
2939 
2940  default:
2941  break;
2942  }
2943  }
2944  while (cur_skip > skip_frames[0]) {
2945  RoadVehicle *u = v;
2946  RoadVehicle *prev = NULL;
2947  for (uint *it = skip_frames.Begin(); it != skip_frames.End(); ++it, prev = u, u = u->Next()) {
2948  extern bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev);
2949  if (*it >= cur_skip) IndividualRoadVehicleController(u, prev);
2950  }
2951  cur_skip--;
2952  }
2953  }
2954  }
2955 
2956  /*
2957  * Only keep order-backups for network clients (and when replaying).
2958  * If we are a network server or not networking, then we just loaded a previously
2959  * saved-by-server savegame. There are no clients with a backup, so clear it.
2960  * Furthermore before savegame version 192 the actual content was always corrupt.
2961  */
2963 #ifndef DEBUG_DUMP_COMMANDS
2964  /* Note: We cannot use CleanPool since that skips part of the destructor
2965  * and then leaks un-reachable Orders in the order pool. */
2966  OrderBackup *ob;
2967  FOR_ALL_ORDER_BACKUPS(ob) {
2968  delete ob;
2969  }
2970 #endif
2971  }
2972 
2973 
2974  /* Station acceptance is some kind of cache */
2975  if (IsSavegameVersionBefore(127)) {
2976  Station *st;
2977  FOR_ALL_STATIONS(st) UpdateStationAcceptance(st, false);
2978  }
2979 
2980  /* Road stops is 'only' updating some caches */
2982  AfterLoadLabelMaps();
2985 
2986  GamelogPrintDebug(1);
2987 
2989  /* Restore the signals */
2991 
2993  return true;
2994 }
2995 
3005 {
3006  /* reload grf data */
3007  GfxLoadSprites();
3009  RecomputePrices();
3010  /* reload vehicles */
3011  ResetVehicleHash();
3012  AfterLoadVehicles(false);
3013  StartupEngines();
3015  /* update station graphics */
3016  AfterLoadStations();
3017  /* Update company statistics. */
3019  /* Check and update house and town values */
3021  /* Delete news referring to no longer existing entities */
3023  /* Update livery selection windows */
3025  /* Update company infrastructure counts. */
3027  /* redraw the whole screen */
3030 }