OpenTTD Source 20241222-master-gc72542431a
afterload.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#include "../stdafx.h"
11#include "../void_map.h"
12#include "../signs_base.h"
13#include "../depot_base.h"
14#include "../fios.h"
15#include "../gamelog_internal.h"
16#include "../network/network.h"
17#include "../network/network_func.h"
18#include "../gfxinit.h"
19#include "../viewport_func.h"
20#include "../viewport_kdtree.h"
21#include "../industry.h"
22#include "../clear_map.h"
23#include "../vehicle_func.h"
24#include "../string_func.h"
25#include "../roadveh.h"
26#include "../roadveh_cmd.h"
27#include "../train.h"
28#include "../station_base.h"
29#include "../waypoint_base.h"
30#include "../roadstop_base.h"
31#include "../tunnelbridge_map.h"
32#include "../pathfinder/yapf/yapf_cache.h"
33#include "../elrail_func.h"
34#include "../signs_func.h"
35#include "../aircraft.h"
36#include "../object_map.h"
37#include "../object_base.h"
38#include "../tree_map.h"
39#include "../company_func.h"
40#include "../road_cmd.h"
41#include "../ai/ai.hpp"
42#include "../script/script_gui.h"
43#include "../game/game.hpp"
44#include "../town.h"
45#include "../economy_base.h"
46#include "../animated_tile_map.h"
47#include "../animated_tile_func.h"
48#include "../subsidy_base.h"
49#include "../subsidy_func.h"
50#include "../newgrf.h"
51#include "../newgrf_station.h"
52#include "../engine_func.h"
53#include "../rail_gui.h"
54#include "../core/backup_type.hpp"
55#include "../smallmap_gui.h"
56#include "../news_func.h"
57#include "../order_backup.h"
58#include "../error.h"
59#include "../disaster_vehicle.h"
60#include "../ship.h"
61#include "../water.h"
62#include "../timer/timer.h"
63#include "../timer/timer_game_calendar.h"
64#include "../timer/timer_game_economy.h"
65#include "../timer/timer_game_tick.h"
66
67#include "saveload_internal.h"
68
69#include <signal.h>
70
71#include "../safeguards.h"
72#include "window_func.h"
73
74extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
75
86void SetWaterClassDependingOnSurroundings(Tile t, bool include_invalid_water_class)
87{
88 /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
89 * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
90 if (!IsTileFlat(t)) {
91 if (include_invalid_water_class) {
93 return;
94 } else {
95 SlErrorCorrupt("Invalid water class for dry tile");
96 }
97 }
98
99 /* Mark tile dirty in all cases */
101
102 if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == Map::MaxX() - 1 || TileY(t) == Map::MaxY() - 1) {
103 /* tiles at map borders are always WATER_CLASS_SEA */
105 return;
106 }
107
108 bool has_water = false;
109 bool has_canal = false;
110 bool has_river = false;
111
112 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
113 Tile neighbour = TileAddByDiagDir(t, dir);
114 switch (GetTileType(neighbour)) {
115 case MP_WATER:
116 /* clear water and shipdepots have already a WaterClass associated */
117 if (IsCoast(neighbour)) {
118 has_water = true;
119 } else if (!IsLock(neighbour)) {
120 switch (GetWaterClass(neighbour)) {
121 case WATER_CLASS_SEA: has_water = true; break;
122 case WATER_CLASS_CANAL: has_canal = true; break;
123 case WATER_CLASS_RIVER: has_river = true; break;
124 default: SlErrorCorrupt("Invalid water class for tile");
125 }
126 }
127 break;
128
129 case MP_RAILWAY:
130 /* Shore or flooded halftile */
131 has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
132 break;
133
134 case MP_TREES:
135 /* trees on shore */
136 has_water |= (GB(neighbour.m2(), 4, 2) == TREE_GROUND_SHORE);
137 break;
138
139 default: break;
140 }
141 }
142
143 if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
145 return;
146 }
147
148 if (has_river && !has_canal) {
150 } else if (has_canal || !has_water) {
152 } else {
154 }
155}
156
157static void ConvertTownOwner()
158{
159 for (auto tile : Map::Iterate()) {
160 switch (GetTileType(tile)) {
161 case MP_ROAD:
162 if (GB(tile.m5(), 4, 2) == ROAD_TILE_CROSSING && HasBit(tile.m3(), 7)) {
163 tile.m3() = OWNER_TOWN;
164 }
165 [[fallthrough]];
166
167 case MP_TUNNELBRIDGE:
168 if (tile.m1() & 0x80) SetTileOwner(tile, OWNER_TOWN);
169 break;
170
171 default: break;
172 }
173 }
174}
175
176/* since savegame version 4.1, exclusive transport rights are stored at towns */
177static void UpdateExclusiveRights()
178{
179 for (Town *t : Town::Iterate()) {
180 t->exclusivity = INVALID_COMPANY;
181 }
182
183 /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
184 * could be implemented this way:
185 * 1.) Go through all stations
186 * Build an array town_blocked[ town_id ][ company_id ]
187 * that stores if at least one station in that town is blocked for a company
188 * 2.) Go through that array, if you find a town that is not blocked for
189 * one company, but for all others, then give it exclusivity.
190 */
191}
192
193static const uint8_t convert_currency[] = {
194 0, 1, 12, 8, 3,
195 10, 14, 19, 4, 5,
196 9, 11, 13, 6, 17,
197 16, 22, 21, 7, 15,
198 18, 2, 20,
199};
200
201/* since savegame version 4.2 the currencies are arranged differently */
202static void UpdateCurrencies()
203{
205}
206
207/* Up to revision 1413 the invisible tiles at the southern border have not been
208 * MP_VOID, even though they should have. This is fixed by this function
209 */
210static void UpdateVoidTiles()
211{
212 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, Map::MaxY()));
213 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(Map::MaxX(), y));
214}
215
216static inline RailType UpdateRailType(RailType rt, RailType min)
217{
218 return rt >= min ? (RailType)(rt + 1): rt;
219}
220
225{
229 UpdateAllTextEffectVirtCoords();
230 RebuildViewportKdtree();
231}
232
233void ClearAllCachedNames()
234{
235 ClearAllStationCachedNames();
237 ClearAllIndustryCachedNames();
238}
239
250{
251 /* Initialize windows */
254
255 /* Update coordinates of the signs. */
256 ClearAllCachedNames();
258 ResetViewportAfterLoadGame();
259
260 for (Company *c : Company::Iterate()) {
261 /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
262 * accordingly if it is not the case. No need to set it on companies that are not been used already,
263 * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
264 if (_file_to_saveload.abstract_ftype == FT_SCENARIO && c->inaugurated_year != EconomyTime::MIN_YEAR) {
265 c->inaugurated_year = TimerGameEconomy::year;
266 }
267 }
268
269 /* Count number of objects per type */
270 for (Object *o : Object::Iterate()) {
271 Object::IncTypeCount(o->type);
272 }
273
274 /* Identify owners of persistent storage arrays */
275 for (Industry *i : Industry::Iterate()) {
276 if (i->psa != nullptr) {
277 i->psa->feature = GSF_INDUSTRIES;
278 i->psa->tile = i->location.tile;
279 }
280 }
281 for (Station *s : Station::Iterate()) {
282 if (s->airport.psa != nullptr) {
283 s->airport.psa->feature = GSF_AIRPORTS;
284 s->airport.psa->tile = s->airport.tile;
285 }
286 }
287 for (Town *t : Town::Iterate()) {
288 for (auto &it : t->psa_list) {
289 it->feature = GSF_FAKE_TOWNS;
290 it->tile = t->xy;
291 }
292 }
293 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
294 if (rv->IsFrontEngine()) {
295 rv->CargoChanged();
296 }
297 }
298
300
302
304
305 /* Towns have a noise controlled number of airports system
306 * So each airport's noise value must be added to the town->noise_reached value
307 * Reset each town's noise_reached value to '0' before. */
309
312
313 /* Rebuild the smallmap list of owners. */
315}
316
317typedef void (CDECL *SignalHandlerPointer)(int);
318static SignalHandlerPointer _prev_segfault = nullptr;
319static SignalHandlerPointer _prev_abort = nullptr;
320static SignalHandlerPointer _prev_fpe = nullptr;
321
322static void CDECL HandleSavegameLoadCrash(int signum);
323
328static void SetSignalHandlers()
329{
330 _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
331 _prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
332 _prev_fpe = signal(SIGFPE, HandleSavegameLoadCrash);
333}
334
339{
340 signal(SIGSEGV, _prev_segfault);
341 signal(SIGABRT, _prev_abort);
342 signal(SIGFPE, _prev_fpe);
343}
344
347
357
364static void CDECL HandleSavegameLoadCrash(int signum)
365{
367
368 std::string message;
369 message.reserve(1024);
370 message += "Loading your savegame caused OpenTTD to crash.\n";
371
372 for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != nullptr; c = c->next) {
374 }
375
377 message +=
378 "This is most likely caused by a missing NewGRF or a NewGRF that\n"
379 "has been loaded as replacement for a missing NewGRF. OpenTTD\n"
380 "cannot easily determine whether a replacement NewGRF is of a newer\n"
381 "or older version.\n"
382 "It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
383 "This means that if the author makes incompatible NewGRFs with the\n"
384 "same GRF ID, OpenTTD cannot magically do the right thing. In most\n"
385 "cases, OpenTTD will load the savegame and not crash, but this is an\n"
386 "exception.\n"
387 "Please load the savegame with the appropriate NewGRFs installed.\n"
388 "The missing/compatible NewGRFs are:\n";
389
390 for (const GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
391 if (HasBit(c->flags, GCF_COMPATIBLE)) {
393 fmt::format_to(std::back_inserter(message), "NewGRF {:08X} (checksum {}) not found.\n Loaded NewGRF \"{}\" (checksum {}) with same GRF ID instead.\n",
394 BSWAP32(c->ident.grfid), FormatArrayAsHex(c->original_md5sum), c->filename, FormatArrayAsHex(replaced->md5sum));
395 }
396 if (c->status == GCS_NOT_FOUND) {
397 fmt::format_to(std::back_inserter(message), "NewGRF {:08X} ({}) not found; checksum {}.\n",
398 BSWAP32(c->ident.grfid), c->filename, FormatArrayAsHex(c->ident.md5sum));
399 }
400 }
401 } else {
402 message +=
403 "This is probably caused by a corruption in the savegame.\n"
404 "Please file a bug report and attach this savegame.\n";
405 }
406
407 ShowInfoI(message);
408
409 SignalHandlerPointer call = nullptr;
410 switch (signum) {
411 case SIGSEGV: call = _prev_segfault; break;
412 case SIGABRT: call = _prev_abort; break;
413 case SIGFPE: call = _prev_fpe; break;
414 default: NOT_REACHED();
415 }
416 if (call != nullptr) call(signum);
417}
418
425{
427
428 /* remove leftover rail piece from crossing (from very old savegames) */
429 Train *v = nullptr;
430 for (Train *w : Train::Iterate()) {
431 if (w->tile == TileIndex(t)) {
432 v = w;
433 break;
434 }
435 }
436
437 if (v != nullptr) {
438 /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
439 SetTileOwner(t, v->owner);
440 return;
441 }
442
443 /* try to find any connected rail */
444 for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
445 TileIndex tt = t + TileOffsByDiagDir(dd);
446 if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
450 return;
451 }
452 }
453
454 if (IsLevelCrossingTile(t)) {
455 /* else change the crossing to normal road (road vehicles won't care) */
456 Owner road = GetRoadOwner(t, RTT_ROAD);
457 Owner tram = GetRoadOwner(t, RTT_TRAM);
459 bool hasroad = HasBit(t.m7(), 6);
460 bool hastram = HasBit(t.m7(), 7);
461
462 /* MakeRoadNormal */
464 SetTileOwner(t, road);
465 t.m3() = (hasroad ? bits : 0);
466 t.m5() = (hastram ? bits : 0) | ROAD_TILE_NORMAL << 6;
467 SB(t.m6(), 2, 4, 0);
468 SetRoadOwner(t, RTT_TRAM, tram);
469 return;
470 }
471
472 /* if it's not a crossing, make it clean land */
473 MakeClear(t, CLEAR_GRASS, 0);
474}
475
483{
484 /* Compute place where this vehicle entered the tile */
485 int entry_x = v->x_pos;
486 int entry_y = v->y_pos;
487 switch (dir) {
488 case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
489 case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
490 case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
491 case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
492 case INVALID_DIR: break;
493 default: NOT_REACHED();
494 }
495 uint8_t entry_z = GetSlopePixelZ(entry_x, entry_y, true);
496
497 /* Compute middle of the tile. */
498 int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
499 int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
500 uint8_t middle_z = GetSlopePixelZ(middle_x, middle_y, true);
501
502 /* middle_z == entry_z, no height change. */
503 if (middle_z == entry_z) return 0;
504
505 /* middle_z < entry_z, we are going downwards. */
506 if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
507
508 /* middle_z > entry_z, we are going upwards. */
509 return 1U << GVF_GOINGUP_BIT;
510}
511
518{
519 for (Vehicle *v : Vehicle::Iterate()) {
520 if (v->IsGroundVehicle()) {
521 /*
522 * Either the vehicle is not actually on the given tile, i.e. it is
523 * in the wormhole of a bridge or a tunnel, or the Z-coordinate must
524 * be the same as when it would be recalculated right now.
525 */
526 assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos, true));
527 }
528 }
529}
530
537static inline bool MayHaveBridgeAbove(Tile t)
538{
539 return IsTileType(t, MP_CLEAR) || IsTileType(t, MP_RAILWAY) || IsTileType(t, MP_ROAD) ||
541}
542
546static void StartScripts()
547{
548 /* Script debug window requires AIs to be started before trying to start GameScript. */
549
550 /* Start the AIs. */
551 for (const Company *c : Company::Iterate()) {
552 if (Company::IsValidAiID(c->index)) AI::StartNew(c->index);
553 }
554
555 /* Start the GameScript. */
557
559}
560
567{
569
570 extern TileIndex _cur_tileloop_tile; // From landscape.cpp.
571 /* The LFSR used in RunTileLoop iteration cannot have a zeroed state, make it non-zeroed. */
572 if (_cur_tileloop_tile == 0) _cur_tileloop_tile = 1;
573
575
578
579 RebuildTownKdtree();
580 RebuildStationKdtree();
581 /* This needs to be done even before conversion, because some conversions will destroy objects
582 * that otherwise won't exist in the tree. */
583 RebuildViewportKdtree();
584
586
589 } else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
590 Debug(net, 0, "The loading savegame was paused due to an error state");
591 Debug(net, 0, " This savegame cannot be used for multiplayer");
592 /* Restore the signals */
594 return false;
595 } else if (!_networking || _network_server) {
596 /* If we are in singleplayer mode, i.e. not networking, and loading the
597 * savegame or we are loading the savegame as network server we do
598 * not want to be bothered by being paused because of the automatic
599 * reason of a network server, e.g. joining clients or too few
600 * active clients. Note that resetting these values for a network
601 * client are very bad because then the client is going to execute
602 * the game loop when the server is not, i.e. it desyncs. */
603 _pause_mode &= ~PMB_PAUSED_NETWORK;
604 }
605
606 /* In very old versions, size of train stations was stored differently.
607 * They had swapped width and height if station was built along the Y axis.
608 * TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
609 * Because the data stored by TTDPatch are unusable for rail stations > 7x7,
610 * recompute the width and height. Doing this unconditionally for all old
611 * savegames simplifies the code. */
613 for (Station *st : Station::Iterate()) {
614 st->train_station.w = st->train_station.h = 0;
615 }
616 for (auto t : Map::Iterate()) {
617 if (!IsTileType(t, MP_STATION)) continue;
618 if (t.m5() > 7) continue; // is it a rail station tile?
619 Station *st = Station::Get(t.m2());
620 assert(st->train_station.tile != 0);
621 int dx = TileX(t) - TileX(st->train_station.tile);
622 int dy = TileY(t) - TileY(st->train_station.tile);
623 assert(dx >= 0 && dy >= 0);
624 st->train_station.w = std::max<uint>(st->train_station.w, dx + 1);
625 st->train_station.h = std::max<uint>(st->train_station.h, dy + 1);
626 }
627 }
628
631
632 /* In old savegame versions, the heightlevel was coded in bits 0..3 of the type field */
633 for (auto t : Map::Iterate()) {
634 t.height() = GB(t.type(), 0, 4);
635 SB(t.type(), 0, 2, GB(t.m6(), 0, 2));
636 SB(t.m6(), 0, 2, 0);
637 if (MayHaveBridgeAbove(t)) {
638 SB(t.type(), 2, 2, GB(t.m6(), 6, 2));
639 SB(t.m6(), 6, 2, 0);
640 } else {
641 SB(t.type(), 2, 2, 0);
642 }
643 }
644 }
645
646 /* in version 2.1 of the savegame, town owner was unified. */
647 if (IsSavegameVersionBefore(SLV_2, 1)) ConvertTownOwner();
648
649 /* from version 4.1 of the savegame, exclusive rights are stored at towns */
650 if (IsSavegameVersionBefore(SLV_4, 1)) UpdateExclusiveRights();
651
652 /* from version 4.2 of the savegame, currencies are in a different order */
653 if (IsSavegameVersionBefore(SLV_4, 2)) UpdateCurrencies();
654
655 /* In old version there seems to be a problem that water is owned by
656 * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
657 * (4.3) version, so I just check when versions are older, and then
658 * walk through the whole map.. */
660 for (const auto t : Map::Iterate()) {
663 }
664 }
665 }
666
668 for (Company *c : Company::Iterate()) {
669 c->name = CopyFromOldName(c->name_1);
670 if (!c->name.empty()) c->name_1 = STR_SV_UNNAMED;
671 c->president_name = CopyFromOldName(c->president_name_1);
672 if (!c->president_name.empty()) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
673 }
674
675 for (Station *st : Station::Iterate()) {
676 st->name = CopyFromOldName(st->string_id);
677 /* generating new name would be too much work for little effect, use the station name fallback */
678 if (!st->name.empty()) st->string_id = STR_SV_STNAME_FALLBACK;
679 }
680
681 for (Town *t : Town::Iterate()) {
682 t->name = CopyFromOldName(t->townnametype);
683 if (!t->name.empty()) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
684 }
685 }
686
687 /* From this point the old names array is cleared. */
689
691 /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
692 for (Station *st : Station::Iterate()) {
693 if (st->airport.tile == 0) st->airport.tile = INVALID_TILE;
694 if (st->train_station.tile == 0) st->train_station.tile = INVALID_TILE;
695 }
696
697 /* the same applies to Company::location_of_HQ */
698 for (Company *c : Company::Iterate()) {
699 if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(SLV_4) && c->location_of_HQ == 0xFFFF)) {
700 c->location_of_HQ = INVALID_TILE;
701 }
702 }
703 }
704
705 /* convert road side to my format. */
707
708 /* Check if all NewGRFs are present, we are very strict in MP mode */
710 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
711 if (c->status == GCS_NOT_FOUND) {
712 _gamelog.GRFRemove(c->ident.grfid);
713 } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
714 _gamelog.GRFCompatible(&c->ident);
715 }
716 }
717
718 if (_networking && gcf_res != GLC_ALL_GOOD) {
719 SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
720 /* Restore the signals */
722 return false;
723 }
724
725 switch (gcf_res) {
726 case GLC_COMPATIBLE: ShowErrorMessage(STR_NEWGRF_COMPATIBLE_LOAD_WARNING, INVALID_STRING_ID, WL_CRITICAL); break;
727 case GLC_NOT_FOUND: ShowErrorMessage(STR_NEWGRF_DISABLED_WARNING, INVALID_STRING_ID, WL_CRITICAL); _pause_mode = PM_PAUSED_ERROR; break;
728 default: break;
729 }
730
731 /* The value of TimerGameCalendar::date_fract got divided, so make sure that old games are converted correctly. */
733
734 /* Update current year
735 * must be done before loading sprites as some newgrfs check it */
737
738 /* Only new games can use wallclock units. */
740
741 /* Update economy year. If we don't have a separate economy date saved, follow the calendar date. */
744 } else {
746 }
747
748 /*
749 * Force the old behaviour for compatibility reasons with old savegames. As new
750 * settings can only be loaded from new savegames loading old savegames with new
751 * versions of OpenTTD will normally initialize settings newer than the savegame
752 * version with "new game" defaults which the player can define to their liking.
753 * For some settings we override that to keep the behaviour the same as when the
754 * game was saved.
755 *
756 * Note that there is no non-stop in here. This is because the setting could have
757 * either value in TTDPatch. To convert it properly the user has to make sure the
758 * right value has been chosen in the settings. Otherwise we will be converting
759 * it incorrectly in half of the times without a means to correct that.
760 */
769 }
775 }
781 }
788 }
789
792 }
793
794 /* Convert linkgraph update settings from days to seconds. */
798 }
799
800 /* Load the sprites */
803
804 /* Copy temporary data to Engine pool */
806
807 /* Connect front and rear engines of multiheaded trains and converts
808 * subtype to the new format */
810
811 /* Connect front and rear engines of multiheaded trains */
813
814 /* Fix the CargoPackets *and* fix the caches of CargoLists.
815 * If this isn't done before Stations and especially Vehicles are
816 * running their AfterLoad we might get in trouble. In the case of
817 * vehicles we could give the wrong (cached) count of items in a
818 * vehicle which causes different results when getting their caches
819 * filled; and that could eventually lead to desyncs. */
821
822 /* Update all vehicles: Phase 1 */
824
825 /* make sure there is a town in the game */
826 if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
827 SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
828 /* Restore the signals */
830 return false;
831 }
832
833 /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
834 * This problem appears in savegame version 21 too, see r3455. But after loading the
835 * savegame and saving again, the buggy map array could be converted to new savegame
836 * version. It didn't show up before r12070. */
837 if (IsSavegameVersionBefore(SLV_87)) UpdateVoidTiles();
838
839 /* Fix the cache for cargo payments. */
840 for (CargoPayment *cp : CargoPayment::Iterate()) {
841 cp->front->cargo_payment = cp;
842 cp->current_station = cp->front->last_station_visited;
843 }
844
845
847 /* Prior to SLV_WATER_TILE_TYPE, the water tile type was stored differently from the enumeration. This has to be
848 * converted before SLV_72 and SLV_82 conversions which use GetWaterTileType. */
849 static constexpr uint8_t WBL_COAST_FLAG = 0;
850
851 for (auto t : Map::Iterate()) {
852 if (!IsTileType(t, MP_WATER)) continue;
853
854 switch (GB(t.m5(), 4, 4)) {
855 case 0x0: /* Previously WBL_TYPE_NORMAL, Clear water or coast. */
856 SetWaterTileType(t, HasBit(t.m5(), WBL_COAST_FLAG) ? WATER_TILE_COAST : WATER_TILE_CLEAR);
857 break;
858
859 case 0x1: SetWaterTileType(t, WATER_TILE_LOCK); break; /* Previously WBL_TYPE_LOCK */
860 case 0x8: SetWaterTileType(t, WATER_TILE_DEPOT); break; /* Previously WBL_TYPE_DEPOT */
861 default: SetWaterTileType(t, WATER_TILE_CLEAR); break; /* Shouldn't happen... */
862 }
863 }
864 }
865
867 /* Locks in very old savegames had OWNER_WATER as owner */
868 for (auto t : Map::Iterate()) {
869 switch (GetTileType(t)) {
870 default: break;
871
872 case MP_WATER:
874 break;
875
876 case MP_STATION: {
877 if (HasBit(t.m6(), 3)) SetBit(t.m6(), 2);
878 StationGfx gfx = GetStationGfx(t);
879 StationType st;
880 if ( IsInsideMM(gfx, 0, 8)) { // Rail station
881 st = STATION_RAIL;
882 SetStationGfx(t, gfx - 0);
883 } else if (IsInsideMM(gfx, 8, 67)) { // Airport
884 st = STATION_AIRPORT;
885 SetStationGfx(t, gfx - 8);
886 } else if (IsInsideMM(gfx, 67, 71)) { // Truck
887 st = STATION_TRUCK;
888 SetStationGfx(t, gfx - 67);
889 } else if (IsInsideMM(gfx, 71, 75)) { // Bus
890 st = STATION_BUS;
891 SetStationGfx(t, gfx - 71);
892 } else if (gfx == 75) { // Oil rig
893 st = STATION_OILRIG;
894 SetStationGfx(t, gfx - 75);
895 } else if (IsInsideMM(gfx, 76, 82)) { // Dock
896 st = STATION_DOCK;
897 SetStationGfx(t, gfx - 76);
898 } else if (gfx == 82) { // Buoy
899 st = STATION_BUOY;
900 SetStationGfx(t, gfx - 82);
901 } else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
902 st = STATION_AIRPORT;
903 SetStationGfx(t, gfx - 83 + 67 - 8);
904 } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
905 st = STATION_TRUCK;
907 } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
908 st = STATION_BUS;
910 } else {
911 /* Restore the signals */
913 return false;
914 }
915 SB(t.m6(), 3, 3, st);
916 break;
917 }
918 }
919 }
920 }
921
923 /* Expansion of station type field in m6 */
924 for (auto t : Map::Iterate()) {
925 if (IsTileType(t, MP_STATION)) {
926 ClrBit(t.m6(), 6);
927 }
928 }
929 }
930
931 for (const auto t : Map::Iterate()) {
932 switch (GetTileType(t)) {
933 case MP_STATION: {
935
936 /* Sanity check */
937 if (!IsBuoy(t) && bst->owner != GetTileOwner(t)) SlErrorCorrupt("Wrong owner for station tile");
938
939 /* Set up station spread */
940 bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
941
942 /* Waypoints don't have road stops/oil rigs in the old format */
943 if (!Station::IsExpected(bst)) break;
944 Station *st = Station::From(bst);
945
946 switch (GetStationType(t)) {
947 case STATION_TRUCK:
948 case STATION_BUS:
950 /* Before version 5 you could not have more than 250 stations.
951 * Version 6 adds large maps, so you could only place 253*253
952 * road stops on a map (no freeform edges) = 64009. So, yes
953 * someone could in theory create such a full map to trigger
954 * this assertion, it's safe to assume that's only something
955 * theoretical and does not happen in normal games. */
957
958 /* From this version on there can be multiple road stops of the
959 * same type per station. Convert the existing stops to the new
960 * internal data structure. */
961 RoadStop *rs = new RoadStop(t);
962
963 RoadStop **head =
964 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
965 *head = rs;
966 }
967 break;
968
969 case STATION_OILRIG: {
970 /* The internal encoding of oil rigs was changed twice.
971 * It was 3 (till 2.2) and later 5 (till 5.1).
972 * DeleteOilRig asserts on the correct type, and
973 * setting it unconditionally does not hurt.
974 */
975 Station::GetByTile(t)->airport.type = AT_OILRIG;
976
977 /* Very old savegames sometimes have phantom oil rigs, i.e.
978 * an oil rig which got shut down, but not completely removed from
979 * the map
980 */
981 TileIndex t1 = TileAddXY(t, 0, 1);
982 if (!IsTileType(t1, MP_INDUSTRY) || GetIndustryGfx(t1) != GFX_OILRIG_1) {
983 DeleteOilRig(t);
984 }
985 break;
986 }
987
988 default: break;
989 }
990 break;
991 }
992
993 default: break;
994 }
995 }
996
997 /* In version 6.1 we put the town index in the map-array. To do this, we need
998 * to use m2 (16bit big), so we need to clean m2, and that is where this is
999 * all about ;) */
1001 for (auto t : Map::Iterate()) {
1002 switch (GetTileType(t)) {
1003 case MP_HOUSE:
1004 t.m4() = t.m2();
1006 break;
1007
1008 case MP_ROAD:
1009 t.m4() |= (t.m2() << 4);
1010 if ((GB(t.m5(), 4, 2) == ROAD_TILE_CROSSING ? (Owner)t.m3() : GetTileOwner(t)) == OWNER_TOWN) {
1012 } else {
1013 SetTownIndex(t, 0);
1014 }
1015 break;
1016
1017 default: break;
1018 }
1019 }
1020 }
1021
1022 /* Force the freeform edges to false for old savegames. */
1025 }
1026
1027 /* From version 9.0, we update the max passengers of a town (was sometimes negative
1028 * before that. */
1030 for (Town *t : Town::Iterate()) UpdateTownMaxPass(t);
1031 }
1032
1033 /* From version 16.0, we included autorenew on engines, which are now saved, but
1034 * of course, we do need to initialize them for older savegames. */
1036 for (Company *c : Company::Iterate()) {
1037 c->engine_renew_list = nullptr;
1038 c->settings.engine_renew = false;
1039 c->settings.engine_renew_months = 6;
1040 c->settings.engine_renew_money = 100000;
1041 }
1042
1043 /* When loading a game, _local_company is not yet set to the correct value.
1044 * However, in a dedicated server we are a spectator, so nothing needs to
1045 * happen. In case we are not a dedicated server, the local company always
1046 * becomes the first available company, unless we are in the scenario editor
1047 * where all the companies are 'invalid'.
1048 */
1050 if (!_network_dedicated && c != nullptr) {
1052 }
1053 }
1054
1056 for (auto t : Map::Iterate()) {
1057 switch (GetTileType(t)) {
1058 case MP_RAILWAY:
1059 if (IsPlainRail(t)) {
1060 /* Swap ground type and signal type for plain rail tiles, so the
1061 * ground type uses the same bits as for depots and waypoints. */
1062 uint tmp = GB(t.m4(), 0, 4);
1063 SB(t.m4(), 0, 4, GB(t.m2(), 0, 4));
1064 SB(t.m2(), 0, 4, tmp);
1065 } else if (HasBit(t.m5(), 2)) {
1066 /* Split waypoint and depot rail type and remove the subtype. */
1067 ClrBit(t.m5(), 2);
1068 ClrBit(t.m5(), 6);
1069 }
1070 break;
1071
1072 case MP_ROAD:
1073 /* Swap m3 and m4, so the track type for rail crossings is the
1074 * same as for normal rail. */
1075 Swap(t.m3(), t.m4());
1076 break;
1077
1078 default: break;
1079 }
1080 }
1081 }
1082
1084 /* Added the RoadType */
1085 bool old_bridge = IsSavegameVersionBefore(SLV_42);
1086 for (auto t : Map::Iterate()) {
1087 switch (GetTileType(t)) {
1088 case MP_ROAD:
1089 SB(t.m5(), 6, 2, GB(t.m5(), 4, 2));
1090 switch (GetRoadTileType(t)) {
1091 default: SlErrorCorrupt("Invalid road tile type");
1092 case ROAD_TILE_NORMAL:
1093 SB(t.m4(), 0, 4, GB(t.m5(), 0, 4));
1094 SB(t.m4(), 4, 4, 0);
1095 SB(t.m6(), 2, 4, 0);
1096 break;
1097 case ROAD_TILE_CROSSING:
1098 SB(t.m4(), 5, 2, GB(t.m5(), 2, 2));
1099 break;
1100 case ROAD_TILE_DEPOT: break;
1101 }
1102 SB(t.m7(), 6, 2, 1); // Set pre-NRT road type bits for conversion later.
1103 break;
1104
1105 case MP_STATION:
1106 if (IsStationRoadStop(t)) SB(t.m7(), 6, 2, 1);
1107 break;
1108
1109 case MP_TUNNELBRIDGE:
1110 /* Middle part of "old" bridges */
1111 if (old_bridge && IsBridge(t) && HasBit(t.m5(), 6)) break;
1112 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(t.m5(), 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1113 SB(t.m7(), 6, 2, 1); // Set pre-NRT road type bits for conversion later.
1114 }
1115 break;
1116
1117 default: break;
1118 }
1119 }
1120 }
1121
1123 bool fix_roadtypes = !IsSavegameVersionBefore(SLV_61);
1124 bool old_bridge = IsSavegameVersionBefore(SLV_42);
1125
1126 for (auto t : Map::Iterate()) {
1127 switch (GetTileType(t)) {
1128 case MP_ROAD:
1129 if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m7(), 5, 3));
1130 SB(t.m7(), 5, 1, GB(t.m3(), 7, 1)); // snow/desert
1131 switch (GetRoadTileType(t)) {
1132 default: SlErrorCorrupt("Invalid road tile type");
1133 case ROAD_TILE_NORMAL:
1134 SB(t.m7(), 0, 4, GB(t.m3(), 0, 4)); // road works
1135 SB(t.m6(), 3, 3, GB(t.m3(), 4, 3)); // ground
1136 SB(t.m3(), 0, 4, GB(t.m4(), 4, 4)); // tram bits
1137 SB(t.m3(), 4, 4, GB(t.m5(), 0, 4)); // tram owner
1138 SB(t.m5(), 0, 4, GB(t.m4(), 0, 4)); // road bits
1139 break;
1140
1141 case ROAD_TILE_CROSSING:
1142 SB(t.m7(), 0, 5, GB(t.m4(), 0, 5)); // road owner
1143 SB(t.m6(), 3, 3, GB(t.m3(), 4, 3)); // ground
1144 SB(t.m3(), 4, 4, GB(t.m5(), 0, 4)); // tram owner
1145 SB(t.m5(), 0, 1, GB(t.m4(), 6, 1)); // road axis
1146 SB(t.m5(), 5, 1, GB(t.m4(), 5, 1)); // crossing state
1147 break;
1148
1149 case ROAD_TILE_DEPOT:
1150 break;
1151 }
1152 if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1153 const Town *town = CalcClosestTownFromTile(t);
1154 if (town != nullptr) SetTownIndex(t, town->index);
1155 }
1156 t.m4() = 0;
1157 break;
1158
1159 case MP_STATION:
1160 if (!IsStationRoadStop(t)) break;
1161
1162 if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m3(), 0, 3));
1163 SB(t.m7(), 0, 5, HasBit(t.m6(), 2) ? OWNER_TOWN : GetTileOwner(t));
1164 SB(t.m3(), 4, 4, t.m1());
1165 t.m4() = 0;
1166 break;
1167
1168 case MP_TUNNELBRIDGE:
1169 if (old_bridge && IsBridge(t) && HasBit(t.m5(), 6)) break;
1170 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(t.m5(), 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1171 if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m3(), 0, 3));
1172
1173 Owner o = GetTileOwner(t);
1174 SB(t.m7(), 0, 5, o); // road owner
1175 SB(t.m3(), 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
1176 }
1177 SB(t.m6(), 2, 4, GB(t.m2(), 4, 4)); // bridge type
1178 SB(t.m7(), 5, 1, GB(t.m4(), 7, 1)); // snow/desert
1179
1180 t.m2() = 0;
1181 t.m4() = 0;
1182 break;
1183
1184 default: break;
1185 }
1186 }
1187 }
1188
1189 /* Railtype moved from m3 to m8 in version SLV_EXTEND_RAILTYPES. */
1191 for (auto t : Map::Iterate()) {
1192 switch (GetTileType(t)) {
1193 case MP_RAILWAY:
1194 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1195 break;
1196
1197 case MP_ROAD:
1198 if (IsLevelCrossing(t)) {
1199 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1200 }
1201 break;
1202
1203 case MP_STATION:
1204 if (HasStationRail(t)) {
1205 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1206 }
1207 break;
1208
1209 case MP_TUNNELBRIDGE:
1211 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1212 }
1213 break;
1214
1215 default:
1216 break;
1217 }
1218 }
1219 }
1220
1222 for (auto t : Map::Iterate()) {
1224 if (IsBridgeTile(t)) {
1225 if (HasBit(t.m5(), 6)) { // middle part
1226 Axis axis = (Axis)GB(t.m5(), 0, 1);
1227
1228 if (HasBit(t.m5(), 5)) { // transport route under bridge?
1229 if (GB(t.m5(), 3, 2) == TRANSPORT_RAIL) {
1230 MakeRailNormal(
1231 t,
1232 GetTileOwner(t),
1233 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
1234 GetRailType(t)
1235 );
1236 } else {
1237 TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
1238
1239 /* MakeRoadNormal */
1240 SetTileType(t, MP_ROAD);
1241 t.m2() = town;
1242 t.m3() = 0;
1243 t.m5() = (axis == AXIS_X ? ROAD_Y : ROAD_X) | ROAD_TILE_NORMAL << 6;
1244 SB(t.m6(), 2, 4, 0);
1245 t.m7() = 1 << 6;
1246 SetRoadOwner(t, RTT_TRAM, OWNER_NONE);
1247 }
1248 } else {
1249 if (GB(t.m5(), 3, 2) == 0) {
1250 MakeClear(t, CLEAR_GRASS, 3);
1251 } else {
1252 if (!IsTileFlat(t)) {
1253 MakeShore(t);
1254 } else {
1255 if (GetTileOwner(t) == OWNER_WATER) {
1256 MakeSea(t);
1257 } else {
1258 MakeCanal(t, GetTileOwner(t), Random());
1259 }
1260 }
1261 }
1262 }
1263 SetBridgeMiddle(t, axis);
1264 } else { // ramp
1265 Axis axis = (Axis)GB(t.m5(), 0, 1);
1266 uint north_south = GB(t.m5(), 5, 1);
1267 DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
1268 TransportType type = (TransportType)GB(t.m5(), 1, 2);
1269
1270 t.m5() = 1 << 7 | type << 2 | dir;
1271 }
1272 }
1273 }
1274
1275 for (Vehicle *v : Vehicle::Iterate()) {
1276 if (!v->IsGroundVehicle()) continue;
1277 if (IsBridgeTile(v->tile)) {
1279
1280 if (dir != DirToDiagDir(v->direction)) continue;
1281 switch (dir) {
1282 default: SlErrorCorrupt("Invalid vehicle direction");
1283 case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
1284 case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
1285 case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
1286 case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
1287 }
1288 } else if (v->z_pos > GetTileMaxPixelZ(TileVirtXY(v->x_pos, v->y_pos))) {
1289 v->tile = GetNorthernBridgeEnd(v->tile);
1290 v->UpdatePosition();
1291 } else {
1292 continue;
1293 }
1294 if (v->type == VEH_TRAIN) {
1295 Train::From(v)->track = TRACK_BIT_WORMHOLE;
1296 } else {
1297 RoadVehicle::From(v)->state = RVSB_WORMHOLE;
1298 }
1299 }
1300 }
1301
1303 /* Add road subtypes */
1304 for (auto t : Map::Iterate()) {
1305 bool has_road = false;
1306 switch (GetTileType(t)) {
1307 case MP_ROAD:
1308 has_road = true;
1309 break;
1310 case MP_STATION:
1311 has_road = IsAnyRoadStop(t);
1312 break;
1313 case MP_TUNNELBRIDGE:
1315 break;
1316 default:
1317 break;
1318 }
1319
1320 if (has_road) {
1321 RoadType road_rt = HasBit(t.m7(), 6) ? ROADTYPE_ROAD : INVALID_ROADTYPE;
1322 RoadType tram_rt = HasBit(t.m7(), 7) ? ROADTYPE_TRAM : INVALID_ROADTYPE;
1323
1324 assert(road_rt != INVALID_ROADTYPE || tram_rt != INVALID_ROADTYPE);
1325 SetRoadTypes(t, road_rt, tram_rt);
1326 SB(t.m7(), 6, 2, 0); // Clear pre-NRT road type bits.
1327 }
1328 }
1329 }
1330
1331 /* Elrails got added in rev 24 */
1333 RailType min_rail = RAILTYPE_ELECTRIC;
1334
1335 for (Train *v : Train::Iterate()) {
1336 RailType rt = RailVehInfo(v->engine_type)->railtype;
1337
1338 v->railtype = rt;
1339 if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
1340 }
1341
1342 /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
1343 for (const auto t : Map::Iterate()) {
1344 switch (GetTileType(t)) {
1345 case MP_RAILWAY:
1346 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1347 break;
1348
1349 case MP_ROAD:
1350 if (IsLevelCrossing(t)) {
1351 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1352 }
1353 break;
1354
1355 case MP_STATION:
1356 if (HasStationRail(t)) {
1357 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1358 }
1359 break;
1360
1361 case MP_TUNNELBRIDGE:
1363 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1364 }
1365 break;
1366
1367 default:
1368 break;
1369 }
1370 }
1371 }
1372
1373 /* In version 16.1 of the savegame a company can decide if trains, which get
1374 * replaced, shall keep their old length. In all prior versions, just default
1375 * to false */
1377 for (Company *c : Company::Iterate()) c->settings.renew_keep_length = false;
1378 }
1379
1381 /* Waypoints became subclasses of stations ... */
1383 /* ... and buoys were moved to waypoints. */
1385 }
1386
1387 /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
1388 * room for PBS. Now in version 21 move it back :P. */
1390 for (auto t : Map::Iterate()) {
1391 switch (GetTileType(t)) {
1392 case MP_RAILWAY:
1393 if (HasSignals(t)) {
1394 /* Original signal type/variant was stored in m4 but since saveload
1395 * version 48 they are in m2. The bits has been already moved to m2
1396 * (see the code somewhere above) so don't use m4, use m2 instead. */
1397
1398 /* convert PBS signals to combo-signals */
1399 if (HasBit(t.m2(), 2)) SB(t.m2(), 0, 2, SIGTYPE_COMBO);
1400
1401 /* move the signal variant back */
1402 SB(t.m2(), 2, 1, HasBit(t.m2(), 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1403 ClrBit(t.m2(), 3);
1404 }
1405
1406 /* Clear PBS reservation on track */
1407 if (!IsRailDepotTile(t)) {
1408 SB(t.m4(), 4, 4, 0);
1409 } else {
1410 ClrBit(t.m3(), 6);
1411 }
1412 break;
1413
1414 case MP_STATION: // Clear PBS reservation on station
1415 ClrBit(t.m3(), 6);
1416 break;
1417
1418 default: break;
1419 }
1420 }
1421 }
1422
1424 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
1425 rv->vehstatus &= ~0x40;
1426 }
1427 }
1428
1430 for (Station *st : Station::Iterate()) {
1431 st->last_vehicle_type = VEH_INVALID;
1432 }
1433 }
1434
1436
1439 }
1440
1441 for (Company *c : Company::Iterate()) {
1442 c->avail_railtypes = GetCompanyRailTypes(c->index);
1443 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
1444 }
1445
1446 AfterLoadStations();
1447
1448 /* Time starts at 0 instead of 1920.
1449 * Account for this in older games by adding an offset */
1455
1459 for (Company *c : Company::Iterate()) c->inaugurated_year += EconomyTime::ORIGINAL_BASE_YEAR;
1460 for (Industry *i : Industry::Iterate()) i->last_prod_year += EconomyTime::ORIGINAL_BASE_YEAR;
1461
1462 for (Vehicle *v : Vehicle::Iterate()) {
1463 v->date_of_last_service += EconomyTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1464 v->build_year += CalendarTime::ORIGINAL_BASE_YEAR;
1465 }
1466 }
1467
1468 /* From 32 on we save the industry who made the farmland.
1469 * To give this prettiness to old savegames, we remove all farmfields and
1470 * plant new ones. */
1472 for (const auto t : Map::Iterate()) {
1474 /* remove fields */
1475 MakeClear(t, CLEAR_GRASS, 3);
1476 }
1477 }
1478
1479 for (Industry *i : Industry::Iterate()) {
1480 uint j;
1481
1483 for (j = 0; j != 50; j++) PlantRandomFarmField(i);
1484 }
1485 }
1486 }
1487
1488 /* Setting no refit flags to all orders in savegames from before refit in orders were added */
1490 for (Order *order : Order::Iterate()) {
1491 order->SetRefit(CARGO_NO_REFIT);
1492 }
1493
1494 for (Vehicle *v : Vehicle::Iterate()) {
1495 v->current_order.SetRefit(CARGO_NO_REFIT);
1496 }
1497 }
1498
1499 /* from version 38 we have optional elrails, since we cannot know the
1500 * preference of a user, let elrails enabled; it can be disabled manually */
1502 /* do the same as when elrails were enabled/disabled manually just now */
1503 UpdateDisableElrailSettingState(_settings_game.vehicle.disable_elrails, false);
1505
1506 /* From version 53, the map array was changed for house tiles to allow
1507 * space for newhouses grf features. A new byte, m7, was also added. */
1509 for (auto t : Map::Iterate()) {
1510 if (IsTileType(t, MP_HOUSE)) {
1511 if (GB(t.m3(), 6, 2) != TOWN_HOUSE_COMPLETED) {
1512 /* Move the construction stage from m3[7..6] to m5[5..4].
1513 * The construction counter does not have to move. */
1514 SB(t.m5(), 3, 2, GB(t.m3(), 6, 2));
1515 SB(t.m3(), 6, 2, 0);
1516
1517 /* The "house is completed" bit is now in m6[2]. */
1518 SetHouseCompleted(t, false);
1519 } else {
1520 /* The "lift has destination" bit has been moved from
1521 * m5[7] to m7[0]. */
1522 AssignBit(t.m7(), 0, HasBit(t.m5(), 7));
1523 ClrBit(t.m5(), 7);
1524
1525 /* The "lift is moving" bit has been removed, as it does
1526 * the same job as the "lift has destination" bit. */
1527 ClrBit(t.m1(), 7);
1528
1529 /* The position of the lift goes from m1[7..0] to m6[7..2],
1530 * making m1 totally free, now. The lift position does not
1531 * have to be a full byte since the maximum value is 36. */
1532 SetLiftPosition(t, GB(t.m1(), 0, 6 ));
1533
1534 t.m1() = 0;
1535 t.m3() = 0;
1536 SetHouseCompleted(t, true);
1537 }
1538 }
1539 }
1540 }
1541
1543 for (auto t : Map::Iterate()) {
1544 if (IsTileType(t, MP_HOUSE)) {
1545 /* House type is moved from m4 + m3[6] to m8. */
1546 SetHouseType(t, t.m4() | (GB(t.m3(), 6, 1) << 8));
1547 t.m4() = 0;
1548 ClrBit(t.m3(), 6);
1549 }
1550 }
1551 }
1552
1553 /* Check and update house and town values */
1555
1557 for (auto t : Map::Iterate()) {
1558 if (IsTileType(t, MP_INDUSTRY)) {
1559 switch (GetIndustryGfx(t)) {
1560 case GFX_POWERPLANT_SPARKS:
1561 t.m3() = GB(t.m1(), 2, 5);
1562 break;
1563
1564 case GFX_OILWELL_ANIMATED_1:
1565 case GFX_OILWELL_ANIMATED_2:
1566 case GFX_OILWELL_ANIMATED_3:
1567 t.m3() = GB(t.m1(), 0, 2);
1568 break;
1569
1570 case GFX_COAL_MINE_TOWER_ANIMATED:
1571 case GFX_COPPER_MINE_TOWER_ANIMATED:
1572 case GFX_GOLD_MINE_TOWER_ANIMATED:
1573 t.m3() = t.m1();
1574 break;
1575
1576 default: // No animation states to change
1577 break;
1578 }
1579 }
1580 }
1581 }
1582
1584 /* Originally just the fact that some cargo had been paid for was
1585 * stored to stop people cheating and cashing in several times. This
1586 * wasn't enough though as it was cleared when the vehicle started
1587 * loading again, even if it didn't actually load anything, so now the
1588 * amount that has been paid is stored. */
1589 for (Vehicle *v : Vehicle::Iterate()) {
1590 ClrBit(v->vehicle_flags, 2);
1591 }
1592 }
1593
1594 /* Buoys do now store the owner of the previous water tile, which can never
1595 * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
1597 for (Waypoint *wp : Waypoint::Iterate()) {
1598 if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
1599 }
1600 }
1601
1603 /* Aircraft units changed from 8 mph to 1 km-ish/h */
1604 for (Aircraft *v : Aircraft::Iterate()) {
1605 if (v->subtype <= AIR_AIRCRAFT) {
1606 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
1607 v->cur_speed *= 128;
1608 v->cur_speed /= 10;
1609 v->acceleration = avi->acceleration;
1610 }
1611 }
1612 }
1613
1615
1617 for (auto t : Map::Iterate()) {
1618 if (IsTileType(t, MP_OBJECT) && t.m5() == OBJECT_STATUE) {
1619 t.m2() = CalcClosestTownFromTile(t)->index;
1620 }
1621 }
1622 }
1623
1624 /* A setting containing the proportion of towns that grow twice as
1625 * fast was added in version 54. From version 56 this is now saved in the
1626 * town as cities can be built specifically in the scenario editor. */
1628 for (Town *t : Town::Iterate()) {
1629 if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
1630 t->larger_town = true;
1631 }
1632 }
1633 }
1634
1636 /* Added a FIFO queue of vehicles loading at stations */
1637 for (Vehicle *v : Vehicle::Iterate()) {
1638 if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) && // for all locs
1639 !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
1640 v->current_order.IsType(OT_LOADING)) { // loading
1641 Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
1642
1643 /* The loading finished flag is *only* set when actually completely
1644 * finished. Because the vehicle is loading, it is not finished. */
1645 ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
1646 }
1647 }
1648 } else if (IsSavegameVersionBefore(SLV_59)) {
1649 /* For some reason non-loading vehicles could be in the station's loading vehicle list */
1650
1651 for (Station *st : Station::Iterate()) {
1652 for (auto iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); /* nothing */) {
1653 Vehicle *v = *iter;
1654 if (!v->current_order.IsType(OT_LOADING)) {
1655 iter = st->loading_vehicles.erase(iter);
1656 } else {
1657 ++iter;
1658 }
1659 }
1660 }
1661 }
1662
1664 /* Setting difficulty industry_density other than zero get bumped to +1
1665 * since a new option (very low at position 1) has been added */
1668 }
1669
1670 /* Same goes for number of towns, although no test is needed, just an increment */
1672 }
1673
1675 /* Since now we allow different signal types and variants on a single tile.
1676 * Move signal states to m4 to make room and clone the signal type/variant. */
1677 for (auto t : Map::Iterate()) {
1678 if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
1679 /* move signal states */
1680 SetSignalStates(t, GB(t.m2(), 4, 4));
1681 SB(t.m2(), 4, 4, 0);
1682 /* clone signal type and variant */
1683 SB(t.m2(), 4, 3, GB(t.m2(), 0, 3));
1684 }
1685 }
1686 }
1687
1689 /* In some old savegames a bit was cleared when it should not be cleared */
1690 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
1691 if (rv->state == 250 || rv->state == 251) {
1692 SetBit(rv->state, 2);
1693 }
1694 }
1695 }
1696
1698 /* Added variables to support newindustries */
1699 for (Industry *i : Industry::Iterate()) i->founder = OWNER_NONE;
1700 }
1701
1702 /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
1703 Replace the owner for those by OWNER_NONE. */
1705 for (const auto t : Map::Iterate()) {
1706 if (IsTileType(t, MP_WATER) &&
1708 GetTileOwner(t) == OWNER_WATER &&
1709 TileHeight(t) != 0) {
1711 }
1712 }
1713 }
1714
1715 /*
1716 * Add the 'previous' owner to the ship depots so we can reset it with
1717 * the correct values when it gets destroyed. This prevents that
1718 * someone can remove canals owned by somebody else and it prevents
1719 * making floods using the removal of ship depots.
1720 */
1722 for (auto t : Map::Iterate()) {
1723 if (IsShipDepotTile(t)) {
1724 t.m4() = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
1725 }
1726 }
1727 }
1728
1730 for (Station *st : Station::Iterate()) {
1731 for (GoodsEntry &ge : st->goods) {
1732 ge.last_speed = 0;
1733 if (ge.cargo.AvailableCount() != 0) SetBit(ge.status, GoodsEntry::GES_RATING);
1734 }
1735 }
1736 }
1737
1738 /* At version 78, industry cargo types can be changed, and are stored with the industry. For older save versions
1739 * copy the IndustrySpec's cargo types over to the Industry. */
1741 for (Industry *i : Industry::Iterate()) {
1742 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1743 for (uint j = 0; j < std::size(i->produced); j++) {
1744 i->produced[j].cargo = indsp->produced_cargo[j];
1745 }
1746 for (uint j = 0; j < std::size(i->accepted); j++) {
1747 i->accepted[j].cargo = indsp->accepts_cargo[j];
1748 }
1749 }
1750 }
1751
1752 /* Industry cargo slots were fixed size before (and including) SLV_VEHICLE_ECONOMY_AGE (either 2/3 or 16/16),
1753 * after this they are dynamic. Trim excess slots. */
1755 for (Industry *i : Industry::Iterate()) {
1757 }
1758 }
1759
1760 /* Before version 81, the density of grass was always stored as zero, and
1761 * grassy trees were always drawn fully grassy. Furthermore, trees on rough
1762 * land used to have zero density, now they have full density. Therefore,
1763 * make all grassy/rough land trees have a density of 3. */
1765 for (auto t : Map::Iterate()) {
1766 if (GetTileType(t) == MP_TREES) {
1767 TreeGround groundType = (TreeGround)GB(t.m2(), 4, 2);
1768 if (groundType != TREE_GROUND_SNOW_DESERT) SB(t.m2(), 6, 2, 3);
1769 }
1770 }
1771 }
1772
1773
1775 /* Rework of orders. */
1776 for (Order *order : Order::Iterate()) order->ConvertFromOldSavegame();
1777
1778 for (Vehicle *v : Vehicle::Iterate()) {
1779 if (v->orders != nullptr && v->orders->GetFirstOrder() != nullptr && v->orders->GetFirstOrder()->IsType(OT_NOTHING)) {
1780 v->orders->FreeChain();
1781 v->orders = nullptr;
1782 }
1783
1784 v->current_order.ConvertFromOldSavegame();
1785 if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
1786 for (Order *order : v->Orders()) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
1787 }
1788 }
1789 } else if (IsSavegameVersionBefore(SLV_94)) {
1790 /* Unload and transfer are now mutual exclusive. */
1791 for (Order *order : Order::Iterate()) {
1792 if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1793 order->SetUnloadType(OUFB_TRANSFER);
1794 order->SetLoadType(OLFB_NO_LOAD);
1795 }
1796 }
1797
1798 for (Vehicle *v : Vehicle::Iterate()) {
1799 if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1800 v->current_order.SetUnloadType(OUFB_TRANSFER);
1801 v->current_order.SetLoadType(OLFB_NO_LOAD);
1802 }
1803 }
1805 /* OrderDepotActionFlags were moved, instead of starting at bit 4 they now start at bit 3. */
1806 for (Order *order : Order::Iterate()) {
1807 if (!order->IsType(OT_GOTO_DEPOT)) continue;
1808 order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() >> 1));
1809 }
1810
1811 for (Vehicle *v : Vehicle::Iterate()) {
1812 if (!v->current_order.IsType(OT_GOTO_DEPOT)) continue;
1813 v->current_order.SetDepotActionType((OrderDepotActionFlags)(v->current_order.GetDepotActionType() >> 1));
1814 }
1815 }
1816
1817 /* The water class was moved/unified. */
1819 for (auto t : Map::Iterate()) {
1820 switch (GetTileType(t)) {
1821 case MP_STATION:
1822 switch (GetStationType(t)) {
1823 case STATION_OILRIG:
1824 case STATION_DOCK:
1825 case STATION_BUOY:
1826 SetWaterClass(t, (WaterClass)GB(t.m3(), 0, 2));
1827 SB(t.m3(), 0, 2, 0);
1828 break;
1829
1830 default:
1832 break;
1833 }
1834 break;
1835
1836 case MP_WATER:
1837 SetWaterClass(t, (WaterClass)GB(t.m3(), 0, 2));
1838 SB(t.m3(), 0, 2, 0);
1839 break;
1840
1841 case MP_OBJECT:
1843 break;
1844
1845 default:
1846 /* No water class. */
1847 break;
1848 }
1849 }
1850 }
1851
1853 for (auto t : Map::Iterate()) {
1854 /* Move river flag and update canals to use water class */
1855 if (IsTileType(t, MP_WATER)) {
1856 if (GetWaterClass(t) != WATER_CLASS_RIVER) {
1857 if (IsWater(t)) {
1858 Owner o = GetTileOwner(t);
1859 if (o == OWNER_WATER) {
1860 MakeSea(t);
1861 } else {
1862 MakeCanal(t, o, Random());
1863 }
1864 } else if (IsShipDepot(t)) {
1865 Owner o = (Owner)t.m4(); // Original water owner
1867 }
1868 }
1869 }
1870 }
1871
1872 /* Update locks, depots, docks and buoys to have a water class based
1873 * on its neighbouring tiles. Done after river and canal updates to
1874 * ensure neighbours are correct. */
1875 for (const auto t : Map::Iterate()) {
1876 if (!IsTileFlat(t)) continue;
1877
1880 }
1881 }
1882
1884 for (const auto t : Map::Iterate()) {
1885 /* skip oil rigs at borders! */
1886 if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
1887 (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == Map::MaxX() - 1 || TileY(t) == Map::MaxY() - 1)) {
1888 /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
1889 * This conversion has to be done before buoys with invalid owner are removed. */
1891 }
1892
1894 Owner o = GetTileOwner(t);
1895 if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
1896 Backup<CompanyID> cur_company(_current_company, o);
1898 cur_company.Restore();
1899 }
1900 if (IsBuoyTile(t)) {
1901 /* reset buoy owner to OWNER_NONE in the station struct
1902 * (even if it is owned by active company) */
1904 }
1905 } else if (IsTileType(t, MP_ROAD)) {
1906 /* works for all RoadTileType */
1907 for (RoadTramType rtt : _roadtramtypes) {
1908 /* update even non-existing road types to update tile owner too */
1909 Owner o = GetRoadOwner(t, rtt);
1911 }
1912 if (IsLevelCrossing(t)) {
1914 }
1915 } else if (IsPlainRailTile(t)) {
1917 }
1918 }
1919 }
1920
1922 /* Profits are now with 8 bit fract */
1923 for (Vehicle *v : Vehicle::Iterate()) {
1924 v->profit_this_year <<= 8;
1925 v->profit_last_year <<= 8;
1926 v->running_ticks = 0;
1927 }
1928 }
1929
1931 /* Increase HouseAnimationFrame from 5 to 7 bits */
1932 for (auto t : Map::Iterate()) {
1934 SB(t.m6(), 2, 6, GB(t.m6(), 3, 5));
1935 SB(t.m3(), 5, 1, 0);
1936 }
1937 }
1938 }
1939
1941 GroupStatistics::UpdateAfterLoad(); // Ensure statistics pool is initialised before trying to delete vehicles
1942 /* Remove all trams from savegames without tram support.
1943 * There would be trams without tram track under causing crashes sooner or later. */
1944 for (RoadVehicle *v : RoadVehicle::Iterate()) {
1945 if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
1946 ShowErrorMessage(STR_WARNING_LOADGAME_REMOVED_TRAMS, INVALID_STRING_ID, WL_CRITICAL);
1947 delete v;
1948 }
1949 }
1950 }
1951
1953 for (auto t : Map::Iterate()) {
1954 /* Set newly introduced WaterClass of industry tiles */
1955 if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
1957 }
1958 if (IsTileType(t, MP_INDUSTRY)) {
1959 if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
1961 } else {
1963 }
1964 }
1965
1966 /* Replace "house construction year" with "house age" */
1967 if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
1968 t.m5() = ClampTo<uint8_t>(TimerGameCalendar::year - (t.m5() + CalendarTime::ORIGINAL_BASE_YEAR));
1969 }
1970 }
1971 }
1972
1973 /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
1974 * format here, as an old layout wouldn't work properly anyway. To be safe, we
1975 * clear any possible PBS reservations as well. */
1977 for (auto t : Map::Iterate()) {
1978 switch (GetTileType(t)) {
1979 case MP_RAILWAY:
1980 if (HasSignals(t)) {
1981 /* move the signal variant */
1982 SetSignalVariant(t, TRACK_UPPER, HasBit(t.m2(), 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1983 SetSignalVariant(t, TRACK_LOWER, HasBit(t.m2(), 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1984 ClrBit(t.m2(), 2);
1985 ClrBit(t.m2(), 6);
1986 }
1987
1988 /* Clear PBS reservation on track */
1989 if (IsRailDepot(t)) {
1990 SetDepotReservation(t, false);
1991 } else {
1993 }
1994 break;
1995
1996 case MP_ROAD: // Clear PBS reservation on crossing
1997 if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
1998 break;
1999
2000 case MP_STATION: // Clear PBS reservation on station
2001 if (HasStationRail(t)) SetRailStationReservation(t, false);
2002 break;
2003
2004 case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/bridges
2006 break;
2007
2008 default: break;
2009 }
2010 }
2011 }
2012
2013 /* Reserve all tracks trains are currently on. */
2015 for (const Train *t : Train::Iterate()) {
2016 if (t->First() == t) t->ReserveTrackUnderConsist();
2017 }
2018 }
2019
2021 /* Non-town-owned roads now store the closest town */
2023
2024 /* signs with invalid owner left from older savegames */
2025 for (Sign *si : Sign::Iterate()) {
2026 if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
2027 }
2028
2029 /* Station can get named based on an industry type, but the current ones
2030 * are not, so mark them as if they are not named by an industry. */
2031 for (Station *st : Station::Iterate()) {
2032 st->indtype = IT_INVALID;
2033 }
2034 }
2035
2037 for (Aircraft *a : Aircraft::Iterate()) {
2038 /* Set engine_type of shadow and rotor */
2039 if (!a->IsNormalAircraft()) {
2040 a->engine_type = a->First()->engine_type;
2041 }
2042 }
2043
2044 /* More companies ... */
2045 for (Company *c : Company::Iterate()) {
2046 if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = MAX_UVALUE(CompanyMask);
2047 }
2048
2049 for (Engine *e : Engine::Iterate()) {
2050 if (e->company_avail == 0xFF) e->company_avail = MAX_UVALUE(CompanyMask);
2051 }
2052
2053 for (Town *t : Town::Iterate()) {
2054 if (t->have_ratings == 0xFF) t->have_ratings = MAX_UVALUE(CompanyMask);
2055 for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
2056 }
2057 }
2058
2060 for (auto t : Map::Iterate()) {
2061 /* Check for HQ bit being set, instead of using map accessor,
2062 * since we've already changed it code-wise */
2063 if (IsTileType(t, MP_OBJECT) && HasBit(t.m5(), 7)) {
2064 /* Move size and part identification of HQ out of the m5 attribute,
2065 * on new locations */
2066 t.m3() = GB(t.m5(), 0, 5);
2067 t.m5() = OBJECT_HQ;
2068 }
2069 }
2070 }
2072 for (auto t : Map::Iterate()) {
2073 if (!IsTileType(t, MP_OBJECT)) continue;
2074
2075 /* Reordering/generalisation of the object bits. */
2076 ObjectType type = t.m5();
2077 SB(t.m6(), 2, 4, type == OBJECT_HQ ? GB(t.m3(), 2, 3) : 0);
2078 t.m3() = type == OBJECT_HQ ? GB(t.m3(), 1, 1) | GB(t.m3(), 0, 1) << 4 : 0;
2079
2080 /* Make sure those bits are clear as well! */
2081 t.m4() = 0;
2082 t.m7() = 0;
2083 }
2084 }
2085
2087 /* Make real objects for object tiles. */
2088 for (auto t : Map::Iterate()) {
2089 if (!IsTileType(t, MP_OBJECT)) continue;
2090
2091 if (Town::GetNumItems() == 0) {
2092 /* No towns, so remove all objects! */
2093 DoClearSquare(t);
2094 } else {
2095 uint offset = t.m3();
2096
2097 /* Also move the animation state. */
2098 t.m3() = GB(t.m6(), 2, 4);
2099 SB(t.m6(), 2, 4, 0);
2100
2101 if (offset == 0) {
2102 /* No offset, so make the object. */
2103 ObjectType type = t.m5();
2104 int size = type == OBJECT_HQ ? 2 : 1;
2105
2106 if (!Object::CanAllocateItem()) {
2107 /* Nice... you managed to place 64k lighthouses and
2108 * antennae on the map... boohoo. */
2109 SlError(STR_ERROR_TOO_MANY_OBJECTS);
2110 }
2111
2112 Object *o = new Object();
2113 o->location.tile = (TileIndex)t;
2114 o->location.w = size;
2115 o->location.h = size;
2117 o->town = type == OBJECT_STATUE ? Town::Get(t.m2()) : CalcClosestTownFromTile(t, UINT_MAX);
2118 t.m2() = o->index;
2120 } else {
2121 /* We're at an offset, so get the ID from our "root". */
2122 Tile northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
2123 assert(IsTileType(northern_tile, MP_OBJECT));
2124 t.m2() = northern_tile.m2();
2125 }
2126 }
2127 }
2128 }
2129
2131 /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
2132 if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
2135 } else {
2138 }
2139
2140 /* Initialize layout of all towns. Older versions were using different
2141 * generator for random town layout, use it if needed. */
2142 for (Town *t : Town::Iterate()) {
2145 continue;
2146 }
2147
2148 /* Use old layout randomizer code */
2149 uint8_t layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
2150 switch (layout) {
2151 default: break;
2152 case 5: layout = 1; break;
2153 case 0: layout = 2; break;
2154 }
2155 t->layout = static_cast<TownLayout>(layout - 1);
2156 }
2157 }
2158
2160 /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
2161 * The conversion affects oil rigs and buoys too, but it doesn't matter as
2162 * they have st->owner == OWNER_NONE already. */
2163 for (Station *st : Station::Iterate()) {
2164 if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
2165 }
2166 }
2167
2168 /* Trains could now stop in a specific location. */
2170 for (Order *o : Order::Iterate()) {
2171 if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
2172 }
2173 }
2174
2177 for (Company *c : Company::Iterate()) {
2178 c->settings.vehicle = _old_vds;
2179 }
2180 }
2181
2183 /* Delete small ufos heading for non-existing vehicles */
2185 if (v->subtype == 2 /* ST_SMALL_UFO */ && v->state != 0) {
2186 const Vehicle *u = Vehicle::GetIfValid(v->dest_tile.base());
2187 if (u == nullptr || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
2188 delete v;
2189 }
2190 }
2191 }
2192
2193 /* We didn't store cargo payment yet, so make them for vehicles that are
2194 * currently at a station and loading/unloading. If they don't get any
2195 * payment anymore they just removed in the next load/unload cycle.
2196 * However, some 0.7 versions might have cargo payment. For those we just
2197 * add cargopayment for the vehicles that don't have it.
2198 */
2199 for (Station *st : Station::Iterate()) {
2200 for (Vehicle *v : st->loading_vehicles) {
2201 /* There are always as many CargoPayments as Vehicles. We need to make the
2202 * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
2205 if (v->cargo_payment == nullptr) v->cargo_payment = new CargoPayment(v);
2206 }
2207 }
2208 }
2209
2211 /* Animated tiles would sometimes not be actually animated or
2212 * in case of old savegames duplicate. */
2213
2214 extern std::vector<TileIndex> _animated_tiles;
2215
2216 for (auto tile = _animated_tiles.begin(); tile < _animated_tiles.end(); /* Nothing */) {
2217 /* Remove if tile is not animated */
2218 bool remove = !MayAnimateTile(*tile);
2219
2220 /* and remove if duplicate */
2221 for (auto j = _animated_tiles.begin(); !remove && j < tile; j++) {
2222 remove = *tile == *j;
2223 }
2224
2225 if (remove) {
2226 tile = _animated_tiles.erase(tile);
2227 } else {
2228 tile++;
2229 }
2230 }
2231 }
2232
2234 for (auto t : Map::Iterate()) {
2235 if (!IsTileType(t, MP_WATER)) continue;
2236 SetNonFloodingWaterTile(t, false);
2237 }
2238 }
2239
2241 /* Animated tile state is stored in the map array, allowing
2242 * quicker addition and deletion of animated tiles. */
2243
2244 extern std::vector<TileIndex> _animated_tiles;
2245
2246 for (auto t : Map::Iterate()) {
2247 /* Ensure there is no spurious animated tile state. */
2249 }
2250
2251 /* Set animated flag for all valid animated tiles. */
2252 for (const TileIndex &tile : _animated_tiles) {
2254 }
2255 }
2256
2258 /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
2259 for (Waypoint *wp : Waypoint::Iterate()) {
2260 if (wp->facilities & FACIL_TRAIN) {
2261 wp->train_station.tile = wp->xy;
2262 wp->train_station.w = 1;
2263 wp->train_station.h = 1;
2264 } else {
2265 wp->train_station.tile = INVALID_TILE;
2266 wp->train_station.w = 0;
2267 wp->train_station.h = 0;
2268 }
2269 }
2270 }
2271
2273 /* Convert old subsidies */
2274 for (Subsidy *s : Subsidy::Iterate()) {
2275 if (s->remaining < 12) {
2276 /* Converting nonawarded subsidy */
2277 s->remaining = 12 - s->remaining; // convert "age" to "remaining"
2278 s->awarded = INVALID_COMPANY; // not awarded to anyone
2279 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2280 switch (cs->town_acceptance_effect) {
2281 case TAE_PASSENGERS:
2282 case TAE_MAIL:
2283 /* Town -> Town */
2284 s->src_type = s->dst_type = SourceType::Town;
2285 if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2286 break;
2287 case TAE_GOODS:
2288 case TAE_FOOD:
2289 /* Industry -> Town */
2290 s->src_type = SourceType::Industry;
2291 s->dst_type = SourceType::Town;
2292 if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2293 break;
2294 default:
2295 /* Industry -> Industry */
2296 s->src_type = s->dst_type = SourceType::Industry;
2297 if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
2298 break;
2299 }
2300 } else {
2301 /* Do our best for awarded subsidies. The original source or destination industry
2302 * can't be determined anymore for awarded subsidies, so invalidate them.
2303 * Town -> Town subsidies are converted using simple heuristic */
2304 s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
2305 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2306 switch (cs->town_acceptance_effect) {
2307 case TAE_PASSENGERS:
2308 case TAE_MAIL: {
2309 /* Town -> Town */
2310 const Station *ss = Station::GetIfValid(s->src);
2311 const Station *sd = Station::GetIfValid(s->dst);
2312 if (ss != nullptr && sd != nullptr && ss->owner == sd->owner &&
2314 s->src_type = s->dst_type = SourceType::Town;
2315 s->src = ss->town->index;
2316 s->dst = sd->town->index;
2317 s->awarded = ss->owner;
2318 continue;
2319 }
2320 break;
2321 }
2322 default:
2323 break;
2324 }
2325 }
2326 /* Awarded non-town subsidy or invalid source/destination, invalidate */
2327 delete s;
2328 }
2329 }
2330
2332 /* Recompute inflation based on old unround loan limit
2333 * Note: Max loan is 500000. With an inflation of 4% across 170 years
2334 * that results in a max loan of about 0.7 * 2^31.
2335 * So taking the 16 bit fractional part into account there are plenty of bits left
2336 * for unmodified savegames ...
2337 */
2338 uint64_t aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
2339
2340 /* ... well, just clamp it then. */
2341 if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
2342
2343 /* Simulate the inflation, so we also get the payment inflation */
2344 while (_economy.inflation_prices < aimed_inflation) {
2345 if (AddInflation(false)) break;
2346 }
2347 }
2348
2350 for (const Depot *d : Depot::Iterate()) {
2351 Tile tile = d->xy;
2352 /* At some point, invalid depots were saved into the game (possibly those removed in the past?)
2353 * Remove them here, so they don't cause issues further down the line */
2354 if (!IsDepotTile(tile)) {
2355 Debug(sl, 0, "Removing invalid depot {} at {}, {}", d->index, TileX(d->xy), TileY(d->xy));
2356 delete d;
2357 d = nullptr;
2358 continue;
2359 }
2360 tile.m2() = d->index;
2361 if (IsTileType(tile, MP_WATER)) Tile(GetOtherShipDepotTile(tile)).m2() = d->index;
2362 }
2363 }
2364
2365 /* The behaviour of force_proceed has been changed. Now
2366 * it counts signals instead of some random time out. */
2368 for (Train *t : Train::Iterate()) {
2369 if (t->force_proceed != TFP_NONE) {
2370 t->force_proceed = TFP_STUCK;
2371 }
2372 }
2373 }
2374
2375 /* The bits for the tree ground and tree density have
2376 * been swapped (m2 bits 7..6 and 5..4. */
2378 for (auto t : Map::Iterate()) {
2379 if (IsTileType(t, MP_CLEAR)) {
2380 if (GetRawClearGround(t) == CLEAR_SNOW) {
2382 SetBit(t.m3(), 4);
2383 } else {
2384 ClrBit(t.m3(), 4);
2385 }
2386 }
2387 if (IsTileType(t, MP_TREES)) {
2388 uint density = GB(t.m2(), 6, 2);
2389 uint ground = GB(t.m2(), 4, 2);
2390 t.m2() = ground << 6 | density << 4;
2391 }
2392 }
2393 }
2394
2395 /* Wait counter and load/unload ticks got split. */
2397 for (Aircraft *a : Aircraft::Iterate()) {
2398 a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
2399 }
2400
2401 for (Train *t : Train::Iterate()) {
2402 t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
2403 }
2404 }
2405
2406 /* Airport tile animation uses animation frame instead of other graphics id */
2408 struct AirportTileConversion {
2409 uint8_t old_start;
2410 uint8_t num_frames;
2411 };
2412 static const AirportTileConversion atcs[] = {
2413 {31, 12}, // APT_RADAR_GRASS_FENCE_SW
2414 {50, 4}, // APT_GRASS_FENCE_NE_FLAG
2415 {62, 2}, // 1 unused tile
2416 {66, 12}, // APT_RADAR_FENCE_SW
2417 {78, 12}, // APT_RADAR_FENCE_NE
2418 {101, 10}, // 9 unused tiles
2419 {111, 8}, // 7 unused tiles
2420 {119, 15}, // 14 unused tiles (radar)
2421 {140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
2422 };
2423 for (const auto t : Map::Iterate()) {
2424 if (IsAirportTile(t)) {
2425 StationGfx old_gfx = GetStationGfx(t);
2426 uint8_t offset = 0;
2427 for (const auto &atc : atcs) {
2428 if (old_gfx < atc.old_start) {
2429 SetStationGfx(t, old_gfx - offset);
2430 break;
2431 }
2432 if (old_gfx < atc.old_start + atc.num_frames) {
2433 SetAnimationFrame(t, old_gfx - atc.old_start);
2434 SetStationGfx(t, atc.old_start - offset);
2435 break;
2436 }
2437 offset += atc.num_frames - 1;
2438 }
2439 }
2440 }
2441 }
2442
2443 /* Oilrig was moved from id 15 to 9. */
2445 for (Station *st : Station::Iterate()) {
2446 if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
2447 st->airport.type = AT_OILRIG;
2448 }
2449 }
2450 }
2451
2453 for (Station *st : Station::Iterate()) {
2454 if (st->airport.tile != INVALID_TILE) {
2455 st->airport.w = st->airport.GetSpec()->size_x;
2456 st->airport.h = st->airport.GetSpec()->size_y;
2457 }
2458 }
2459 }
2460
2462 for (const auto t : Map::Iterate()) {
2463 /* Reset tropic zone for VOID tiles, they shall not have any. */
2465 }
2466
2467 /* We need to properly number/name the depots.
2468 * The first step is making sure none of the depots uses the
2469 * 'default' names, after that we can assign the names. */
2470 for (Depot *d : Depot::Iterate()) d->town_cn = UINT16_MAX;
2471
2472 for (Depot *d : Depot::Iterate()) MakeDefaultName(d);
2473 }
2474
2476 for (Depot *d : Depot::Iterate()) d->build_date = TimerGameCalendar::date;
2477 }
2478
2479 /* In old versions it was possible to remove an airport while a plane was
2480 * taking off or landing. This gives all kind of problems when building
2481 * another airport in the same station so we don't allow that anymore.
2482 * For old savegames with such aircraft we just throw them in the air and
2483 * treat the aircraft like they were flying already. */
2485 for (Aircraft *v : Aircraft::Iterate()) {
2486 if (!v->IsNormalAircraft()) continue;
2488 if (st == nullptr && v->state != FLYING) {
2489 v->state = FLYING;
2492 /* get aircraft back on running altitude */
2493 if ((v->vehstatus & VS_CRASHED) == 0) {
2494 GetAircraftFlightLevelBounds(v, &v->z_pos, nullptr);
2495 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
2496 }
2497 }
2498 }
2499 }
2500
2501 /* Move the animation frame to the same location (m7) for all objects. */
2503 for (auto t : Map::Iterate()) {
2504 switch (GetTileType(t)) {
2505 case MP_HOUSE:
2506 if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
2507 uint per_proc = t.m7();
2508 t.m7() = GB(t.m6(), 2, 6) | (GB(t.m3(), 5, 1) << 6);
2509 SB(t.m3(), 5, 1, 0);
2510 SB(t.m6(), 2, 6, std::min(per_proc, 63U));
2511 }
2512 break;
2513
2514 case MP_INDUSTRY: {
2515 uint rand = t.m7();
2516 t.m7() = t.m3();
2517 t.m3() = rand;
2518 break;
2519 }
2520
2521 case MP_OBJECT:
2522 t.m7() = t.m3();
2523 t.m3() = 0;
2524 break;
2525
2526 default:
2527 /* For stations/airports it's already at m7 */
2528 break;
2529 }
2530 }
2531 }
2532
2533 /* Add (random) colour to all objects. */
2535 for (Object *o : Object::Iterate()) {
2536 Owner owner = GetTileOwner(o->location.tile);
2537 o->colour = (owner == OWNER_NONE) ? static_cast<Colours>(GB(Random(), 0, 4)) : Company::Get(owner)->livery->colour1;
2538 }
2539 }
2540
2542 for (const auto t : Map::Iterate()) {
2543 if (!IsTileType(t, MP_STATION)) continue;
2544 if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && IsTileFlat(t))) {
2546 }
2547 }
2548
2549 /* Waypoints with custom name may have a non-unique town_cn,
2550 * renumber those. First set all affected waypoints to the
2551 * highest possible number to get them numbered in the
2552 * order they have in the pool. */
2553 for (Waypoint *wp : Waypoint::Iterate()) {
2554 if (!wp->name.empty()) wp->town_cn = UINT16_MAX;
2555 }
2556
2557 for (Waypoint *wp : Waypoint::Iterate()) {
2558 if (!wp->name.empty()) MakeDefaultName(wp);
2559 }
2560 }
2561
2563 _industry_builder.Reset(); // Initialize industry build data.
2564
2565 /* The moment vehicles go from hidden to visible changed. This means
2566 * that vehicles don't always get visible anymore causing things to
2567 * get messed up just after loading the savegame. This fixes that. */
2568 for (Vehicle *v : Vehicle::Iterate()) {
2569 /* Not all vehicle types can be inside a tunnel. Furthermore,
2570 * testing IsTunnelTile() for invalid tiles causes a crash. */
2571 if (!v->IsGroundVehicle()) continue;
2572
2573 /* Is the vehicle in a tunnel? */
2574 if (!IsTunnelTile(v->tile)) continue;
2575
2576 /* Is the vehicle actually at a tunnel entrance/exit? */
2577 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
2578 if (!IsTunnelTile(vtile)) continue;
2579
2580 /* Are we actually in this tunnel? Or maybe a lower tunnel? */
2581 if (GetSlopePixelZ(v->x_pos, v->y_pos, true) != v->z_pos) continue;
2582
2583 /* What way are we going? */
2584 const DiagDirection dir = GetTunnelBridgeDirection(vtile);
2585 const DiagDirection vdir = DirToDiagDir(v->direction);
2586
2587 /* Have we passed the visibility "switch" state already? */
2588 uint8_t pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
2589 uint8_t frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2590 extern const uint8_t _tunnel_visibility_frame[DIAGDIR_END];
2591
2592 /* Should the vehicle be hidden or not? */
2593 bool hidden;
2594 if (dir == vdir) { // Entering tunnel
2595 hidden = frame >= _tunnel_visibility_frame[dir];
2596 v->tile = vtile;
2597 } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
2598 hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
2599 /* v->tile changes at the moment when the vehicle leaves the tunnel. */
2600 v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
2601 } else {
2602 /* We could get here in two cases:
2603 * - for road vehicles, it is reversing at the end of the tunnel
2604 * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
2605 * Whatever case it is, do not change anything and use the old values.
2606 * Especially changing RV's state would break its reversing in the middle. */
2607 continue;
2608 }
2609
2610 if (hidden) {
2611 v->vehstatus |= VS_HIDDEN;
2612
2613 switch (v->type) {
2614 case VEH_TRAIN: Train::From(v)->track = TRACK_BIT_WORMHOLE; break;
2615 case VEH_ROAD: RoadVehicle::From(v)->state = RVSB_WORMHOLE; break;
2616 default: NOT_REACHED();
2617 }
2618 } else {
2619 v->vehstatus &= ~VS_HIDDEN;
2620
2621 switch (v->type) {
2622 case VEH_TRAIN: Train::From(v)->track = DiagDirToDiagTrackBits(vdir); break;
2623 case VEH_ROAD: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
2624 default: NOT_REACHED();
2625 }
2626 }
2627 }
2628 }
2629
2631 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
2632 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
2633
2634 bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
2635 if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
2636 extern const uint8_t _road_stop_stop_frame[];
2637 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)]);
2638 } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
2639 SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
2640 }
2641 }
2642 }
2643
2645 /* The train's pathfinder lost flag got moved. */
2646 for (Train *t : Train::Iterate()) {
2647 if (!HasBit(t->flags, 5)) continue;
2648
2649 ClrBit(t->flags, 5);
2650 SetBit(t->vehicle_flags, VF_PATHFINDER_LOST);
2651 }
2652
2653 /* Introduced terraform/clear limits. */
2654 for (Company *c : Company::Iterate()) {
2655 c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
2656 c->clear_limit = _settings_game.construction.clear_frame_burst << 16;
2657 }
2658 }
2659
2660
2662 /*
2663 * The logic of GetPartialPixelZ has been changed, so the resulting Zs on
2664 * the map are consistent. This requires that the Z position of some
2665 * vehicles is updated to reflect this new situation.
2666 *
2667 * This needs to be before SLV_158, because that performs asserts using
2668 * GetSlopePixelZ which internally uses GetPartialPixelZ.
2669 */
2670 for (Vehicle *v : Vehicle::Iterate()) {
2671 if (v->IsGroundVehicle() && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2672 /* Vehicle is on the ground, and not in a wormhole. */
2673 v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos, true);
2674 }
2675 }
2676 }
2677
2679 for (Vehicle *v : Vehicle::Iterate()) {
2680 switch (v->type) {
2681 case VEH_TRAIN: {
2682 Train *t = Train::From(v);
2683
2684 /* Clear old GOINGUP / GOINGDOWN flags.
2685 * It was changed in savegame version 139, but savegame
2686 * version 158 doesn't use these bits, so it doesn't hurt
2687 * to clear them unconditionally. */
2688 ClrBit(t->flags, 1);
2689 ClrBit(t->flags, 2);
2690
2691 /* Clear both bits first. */
2694
2695 /* Crashed vehicles can't be going up/down. */
2696 if (t->vehstatus & VS_CRASHED) break;
2697
2698 /* Only X/Y tracks can be sloped. */
2699 if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
2700
2702 break;
2703 }
2704 case VEH_ROAD: {
2708
2709 /* Crashed vehicles can't be going up/down. */
2710 if (rv->vehstatus & VS_CRASHED) break;
2711
2712 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
2713
2714 TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, GetRoadTramType(rv->roadtype));
2715 TrackBits trackbits = TrackStatusToTrackBits(ts);
2716
2717 /* Only X/Y tracks can be sloped. */
2718 if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
2719
2720 Direction dir = rv->direction;
2721
2722 /* Test if we are reversing. */
2723 Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
2724 if (AxisToDirection(a) != dir &&
2725 AxisToDirection(a) != ReverseDir(dir)) {
2726 /* When reversing, the road vehicle is on the edge of the tile,
2727 * so it can be safely compared to the middle of the tile. */
2728 dir = INVALID_DIR;
2729 }
2730
2731 rv->gv_flags |= FixVehicleInclination(rv, dir);
2732 break;
2733 }
2734 case VEH_SHIP:
2735 break;
2736
2737 default:
2738 continue;
2739 }
2740
2741 if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2742 /* In old versions, z_pos was 1 unit lower on bridge heads.
2743 * However, this invalid state could be converted to new savegames
2744 * by loading and saving the game in a new version. */
2745 v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos, true);
2747 if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
2748 v->direction != DiagDirToDir(dir)) {
2749 /* If the train has left the bridge, it shouldn't have
2750 * track == TRACK_BIT_WORMHOLE - this could happen
2751 * when the train was reversed while on the last "tick"
2752 * on the ramp before leaving the ramp to the bridge. */
2753 Train::From(v)->track = DiagDirToDiagTrackBits(dir);
2754 }
2755 }
2756
2757 /* If the vehicle is really above v->tile (not in a wormhole),
2758 * it should have set v->z_pos correctly. */
2759 assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos, true));
2760 }
2761
2762 /* Fill Vehicle::cur_real_order_index */
2763 for (Vehicle *v : Vehicle::Iterate()) {
2764 if (!v->IsPrimaryVehicle()) continue;
2765
2766 /* Older versions are less strict with indices being in range and fix them on the fly */
2767 if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
2768
2769 v->cur_real_order_index = v->cur_implicit_order_index;
2770 v->UpdateRealOrderIndex();
2771 }
2772 }
2773
2775 /* If the savegame is old (before version 100), then the value of 255
2776 * for these settings did not mean "disabled". As such everything
2777 * before then did reverse.
2778 * To simplify stuff we disable all turning around or we do not
2779 * disable anything at all. So, if some reversing was disabled we
2780 * will keep reversing disabled, otherwise it'll be turned on. */
2782
2783 for (Train *t : Train::Iterate()) {
2784 _settings_game.vehicle.max_train_length = std::max<uint8_t>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
2785 }
2786 }
2787
2789 /* Setting difficulty industry_density other than zero get bumped to +1
2790 * since a new option (minimal at position 1) has been added */
2793 }
2794 }
2795
2797 /* Before savegame version 161, persistent storages were not stored in a pool. */
2798
2800 for (Industry *ind : Industry::Iterate()) {
2801 assert(ind->psa != nullptr);
2802
2803 /* Check if the old storage was empty. */
2804 bool is_empty = true;
2805 for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
2806 if (ind->psa->GetValue(i) != 0) {
2807 is_empty = false;
2808 break;
2809 }
2810 }
2811
2812 if (!is_empty) {
2813 ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
2814 } else {
2815 delete ind->psa;
2816 ind->psa = nullptr;
2817 }
2818 }
2819 }
2820
2822 for (Station *st : Station::Iterate()) {
2823 if (!(st->facilities & FACIL_AIRPORT)) continue;
2824 assert(st->airport.psa != nullptr);
2825
2826 /* Check if the old storage was empty. */
2827 bool is_empty = true;
2828 for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
2829 if (st->airport.psa->GetValue(i) != 0) {
2830 is_empty = false;
2831 break;
2832 }
2833 }
2834
2835 if (!is_empty) {
2836 st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
2837 } else {
2838 delete st->airport.psa;
2839 st->airport.psa = nullptr;
2840
2841 }
2842 }
2843 }
2844 }
2845
2846 /* This triggers only when old snow_lines were copied into the snow_line_height. */
2849 }
2850
2852 /* We store 4 fences in the field tiles instead of only SE and SW. */
2853 for (auto t : Map::Iterate()) {
2854 if (!IsTileType(t, MP_CLEAR) && !IsTileType(t, MP_TREES)) continue;
2855 if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) continue;
2856 uint fence = GB(t.m4(), 5, 3);
2857 if (fence != 0 && IsTileType(TileAddXY(t, 1, 0), MP_CLEAR) && IsClearGround(TileAddXY(t, 1, 0), CLEAR_FIELDS)) {
2858 SetFence(TileAddXY(t, 1, 0), DIAGDIR_NE, fence);
2859 }
2860 fence = GB(t.m4(), 2, 3);
2861 if (fence != 0 && IsTileType(TileAddXY(t, 0, 1), MP_CLEAR) && IsClearGround(TileAddXY(t, 0, 1), CLEAR_FIELDS)) {
2862 SetFence(TileAddXY(t, 0, 1), DIAGDIR_NW, fence);
2863 }
2864 SB(t.m4(), 2, 3, 0);
2865 SB(t.m4(), 5, 3, 0);
2866 }
2867 }
2868
2870 for (Town *t : Town::Iterate()) {
2871 /* Set the default cargo requirement for town growth */
2873 case LT_ARCTIC:
2875 break;
2876
2877 case LT_TROPIC:
2880 break;
2881 }
2882 }
2883 }
2884
2886 /* Adjust zoom level to account for new levels */
2887 _saved_scrollpos_zoom = static_cast<ZoomLevel>(_saved_scrollpos_zoom + ZOOM_BASE_SHIFT);
2888 _saved_scrollpos_x *= ZOOM_BASE;
2889 _saved_scrollpos_y *= ZOOM_BASE;
2890 }
2891
2892 /* When any NewGRF has been changed the availability of some vehicles might
2893 * have been changed too. e->company_avail must be set to 0 in that case
2894 * which is done by StartupEngines(). */
2895 if (gcf_res != GLC_ALL_GOOD) StartupEngines();
2896
2897 /* The road owner of standard road stops was not properly accounted for. */
2899 for (const auto t : Map::Iterate()) {
2900 if (!IsBayRoadStopTile(t)) continue;
2901 Owner o = GetTileOwner(t);
2902 SetRoadOwner(t, RTT_ROAD, o);
2903 SetRoadOwner(t, RTT_TRAM, o);
2904 }
2905 }
2906
2908 /* Introduced tree planting limit. */
2909 for (Company *c : Company::Iterate()) c->tree_limit = _settings_game.construction.tree_frame_burst << 16;
2910 }
2911
2913 /* Fix too high inflation rates */
2916
2917 /* We have to convert the quarters of bankruptcy into months of bankruptcy */
2918 for (Company *c : Company::Iterate()) {
2919 c->months_of_bankruptcy = 3 * c->months_of_bankruptcy;
2920 }
2921 }
2922
2923 {
2924 /* Station blocked, wires and pylon flags need to be stored in the map. This is effectively cached data, so no
2925 * version check is necessary. This is done here as the SLV_182 check below needs the blocked status. */
2926 for (const auto t : Map::Iterate()) {
2927 if (HasStationTileRail(t)) SetRailStationTileFlags(t, GetStationSpec(t));
2928 }
2929 }
2930
2932 /* Aircraft acceleration variable was bonkers */
2933 for (Aircraft *v : Aircraft::Iterate()) {
2934 if (v->subtype <= AIR_AIRCRAFT) {
2935 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
2936 v->acceleration = avi->acceleration;
2937 }
2938 }
2939
2940 /* Blocked tiles could be reserved due to a bug, which causes
2941 * other places to assert upon e.g. station reconstruction. */
2942 for (const auto t : Map::Iterate()) {
2944 SetRailStationReservation(t, false);
2945 }
2946 }
2947 }
2948
2950 /* The global units configuration is split up in multiple configurations. */
2951 extern uint8_t _old_units;
2952 _settings_game.locale.units_velocity = Clamp(_old_units, 0, 2);
2953 _settings_game.locale.units_power = Clamp(_old_units, 0, 2);
2954 _settings_game.locale.units_weight = Clamp(_old_units, 1, 2);
2955 _settings_game.locale.units_volume = Clamp(_old_units, 1, 2);
2957 _settings_game.locale.units_height = Clamp(_old_units, 0, 2);
2958 }
2959
2961 /* Match nautical velocity with land velocity units. */
2963 }
2964
2966 /* Move ObjectType from map to pool */
2967 for (auto t : Map::Iterate()) {
2968 if (IsTileType(t, MP_OBJECT)) {
2969 Object *o = Object::Get(t.m2());
2970 o->type = t.m5();
2971 t.m5() = 0; // zero upper bits of (now bigger) ObjectID
2972 }
2973 }
2974 }
2975
2976 /* Beyond this point, tile types which can be accessed by vehicles must be in a valid state. */
2977
2978 /* Update all vehicles: Phase 2 */
2980
2981 /* The center of train vehicles was changed, fix up spacing. */
2983
2984 /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
2985 * This has to be called after all map array updates */
2987
2989 /* Fix articulated road vehicles.
2990 * Some curves were shorter than other curves.
2991 * Now they have the same length, but that means that trailing articulated parts will
2992 * take longer to go through the curve than the parts in front which already left the courve.
2993 * So, make articulated parts catch up. */
2994 bool roadside = _settings_game.vehicle.road_side == 1;
2995 std::vector<uint> skip_frames;
2996 for (RoadVehicle *v : RoadVehicle::Iterate()) {
2997 if (!v->IsFrontEngine()) continue;
2998 skip_frames.clear();
2999 TileIndex prev_tile = v->tile;
3000 uint prev_tile_skip = 0;
3001 uint cur_skip = 0;
3002 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
3003 if (u->tile != prev_tile) {
3004 prev_tile_skip = cur_skip;
3005 prev_tile = u->tile;
3006 } else {
3007 cur_skip = prev_tile_skip;
3008 }
3009
3010 uint &this_skip = skip_frames.emplace_back(prev_tile_skip);
3011
3012 /* The following 3 curves now take longer than before */
3013 switch (u->state) {
3014 case 2:
3015 cur_skip++;
3016 if (u->frame <= (roadside ? 9 : 5)) this_skip = cur_skip;
3017 break;
3018
3019 case 4:
3020 cur_skip++;
3021 if (u->frame <= (roadside ? 5 : 9)) this_skip = cur_skip;
3022 break;
3023
3024 case 5:
3025 cur_skip++;
3026 if (u->frame <= (roadside ? 4 : 2)) this_skip = cur_skip;
3027 break;
3028
3029 default:
3030 break;
3031 }
3032 }
3033 while (cur_skip > skip_frames[0]) {
3034 RoadVehicle *u = v;
3035 RoadVehicle *prev = nullptr;
3036 for (uint sf : skip_frames) {
3037 if (sf >= cur_skip) IndividualRoadVehicleController(u, prev);
3038
3039 prev = u;
3040 u = u->Next();
3041 }
3042 cur_skip--;
3043 }
3044 }
3045 }
3046
3048 for (Order *order : Order::Iterate()) {
3049 order->SetTravelTimetabled(order->GetTravelTime() > 0);
3050 order->SetWaitTimetabled(order->GetWaitTime() > 0);
3051 }
3052 for (OrderList *orderlist : OrderList::Iterate()) {
3053 orderlist->RecalculateTimetableDuration();
3054 }
3055 }
3056
3057 /*
3058 * Only keep order-backups for network clients (and when replaying).
3059 * If we are a network server or not networking, then we just loaded a previously
3060 * saved-by-server savegame. There are no clients with a backup, so clear it.
3061 * Furthermore before savegame version SLV_192 the actual content was always corrupt.
3062 */
3064#ifndef DEBUG_DUMP_COMMANDS
3065 /* Note: We cannot use CleanPool since that skips part of the destructor
3066 * and then leaks un-reachable Orders in the order pool. */
3067 for (OrderBackup *ob : OrderBackup::Iterate()) {
3068 delete ob;
3069 }
3070#endif
3071 }
3072
3074 /* Convert towns growth_rate and grow_counter to ticks */
3075 for (Town *t : Town::Iterate()) {
3076 /* 0x8000 = TOWN_GROWTH_RATE_CUSTOM previously */
3077 if (t->growth_rate & 0x8000) SetBit(t->flags, TOWN_CUSTOM_GROWTH);
3078 if (t->growth_rate != TOWN_GROWTH_RATE_NONE) {
3079 t->growth_rate = TownTicksToGameTicks(t->growth_rate & ~0x8000);
3080 }
3081 /* Add t->index % TOWN_GROWTH_TICKS to spread growth across ticks. */
3082 t->grow_counter = TownTicksToGameTicks(t->grow_counter) + t->index % Ticks::TOWN_GROWTH_TICKS;
3083 }
3084 }
3085
3087 /* Make sure added industry cargo slots are cleared */
3088 for (Industry *i : Industry::Iterate()) {
3089 /* Make sure last_cargo_accepted_at is copied to elements for every valid input cargo.
3090 * The loading routine should put the original singular value into the first array element. */
3091 for (auto &a : i->accepted) {
3092 if (IsValidCargoID(a.cargo)) {
3093 a.last_accepted = i->GetAccepted(0).last_accepted;
3094 } else {
3095 a.last_accepted = 0;
3096 }
3097 }
3098 }
3099 }
3100
3102 /* Move ships from lock slope to upper or lower position. */
3103 for (Ship *s : Ship::Iterate()) {
3104 /* Suitable tile? */
3105 if (!IsTileType(s->tile, MP_WATER) || !IsLock(s->tile) || GetLockPart(s->tile) != LOCK_PART_MIDDLE) continue;
3106
3107 /* We don't need to adjust position when at the tile centre */
3108 int x = s->x_pos & 0xF;
3109 int y = s->y_pos & 0xF;
3110 if (x == 8 && y == 8) continue;
3111
3112 /* Test if ship is on the second half of the tile */
3113 bool second_half;
3114 DiagDirection shipdiagdir = DirToDiagDir(s->direction);
3115 switch (shipdiagdir) {
3116 default: NOT_REACHED();
3117 case DIAGDIR_NE: second_half = x < 8; break;
3118 case DIAGDIR_NW: second_half = y < 8; break;
3119 case DIAGDIR_SW: second_half = x > 8; break;
3120 case DIAGDIR_SE: second_half = y > 8; break;
3121 }
3122
3123 DiagDirection slopediagdir = GetInclinedSlopeDirection(GetTileSlope(s->tile));
3124
3125 /* Heading up slope == passed half way */
3126 if ((shipdiagdir == slopediagdir) == second_half) {
3127 /* On top half of lock */
3128 s->z_pos = GetTileMaxZ(s->tile) * (int)TILE_HEIGHT;
3129 } else {
3130 /* On lower half of lock */
3131 s->z_pos = GetTileZ(s->tile) * (int)TILE_HEIGHT;
3132 }
3133 }
3134 }
3135
3137 /* Ensure the original cargo generation mode is used */
3139 }
3140
3142 /* Ensure the original neutral industry/station behaviour is used */
3144
3145 /* Link oil rigs to their industry and back. */
3146 for (Station *st : Station::Iterate()) {
3147 if (IsTileType(st->xy, MP_STATION) && IsOilRig(st->xy)) {
3148 /* Industry tile is always adjacent during construction by TileDiffXY(0, 1) */
3149 st->industry = Industry::GetByTile(st->xy + TileDiffXY(0, 1));
3150 st->industry->neutral_station = st;
3151 }
3152 }
3153 } else {
3154 /* Link neutral station back to industry, as this is not saved. */
3155 for (Industry *ind : Industry::Iterate()) if (ind->neutral_station != nullptr) ind->neutral_station->industry = ind;
3156 }
3157
3159 /* Update water class for trees. */
3160 for (const auto t : Map::Iterate()) {
3162 }
3163 }
3164
3165 /* Update structures for multitile docks */
3167 for (const auto t : Map::Iterate()) {
3168 /* Clear docking tile flag from relevant tiles as it
3169 * was not previously cleared. */
3171 SetDockingTile(t, false);
3172 }
3173 /* Add docks and oilrigs to Station::ship_station. */
3174 if (IsTileType(t, MP_STATION)) {
3175 if (IsDock(t) || IsOilRig(t)) Station::GetByTile(t)->ship_station.Add(t);
3176 }
3177 }
3178 }
3179
3181 /* Placing objects on docking tiles was not updating adjacent station's docking tiles. */
3182 for (Station *st : Station::Iterate()) {
3183 if (st->ship_station.tile != INVALID_TILE) UpdateStationDockingTiles(st);
3184 }
3185 }
3186
3188 /* Reset roadtype/streetcartype info for non-road bridges. */
3189 for (const auto t : Map::Iterate()) {
3192 }
3193 }
3194 }
3195
3196 /* Make sure all industries exclusive supplier/consumer set correctly. */
3198 for (Industry *i : Industry::Iterate()) {
3199 i->exclusive_supplier = INVALID_OWNER;
3200 i->exclusive_consumer = INVALID_OWNER;
3201 }
3202 }
3203
3205 /* Propagate wagon removal flag for compatibility */
3206 /* Temporary bitmask of company wagon removal setting */
3207 uint16_t wagon_removal = 0;
3208 for (const Company *c : Company::Iterate()) {
3209 if (c->settings.renew_keep_length) SetBit(wagon_removal, c->index);
3210 }
3211 for (Group *g : Group::Iterate()) {
3212 if (g->flags != 0) {
3213 /* Convert old replace_protection value to flag. */
3214 g->flags = 0;
3216 }
3217 if (HasBit(wagon_removal, g->owner)) SetBit(g->flags, GroupFlags::GF_REPLACE_WAGON_REMOVAL);
3218 }
3219 }
3220
3221 /* Use current order time to approximate last loading time */
3223 for (Vehicle *v : Vehicle::Iterate()) {
3224 v->last_loading_tick = std::max(TimerGameTick::counter, static_cast<uint64_t>(v->current_order_time)) - v->current_order_time;
3225 }
3226 }
3227
3228 /* Road stops is 'only' updating some caches, but they are needed for PF calls in SLV_MULTITRACK_LEVEL_CROSSINGS teleporting. */
3230
3231 /* Road vehicles stopped on multitrack level crossings need teleporting to a depot
3232 * to avoid crashing into the side of the train they're waiting for. */
3234 /* Teleport road vehicles to the nearest depot. */
3235 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
3236 /* Ignore trailers of articulated vehicles. */
3237 if (rv->IsArticulatedPart()) continue;
3238
3239 /* Ignore moving vehicles. */
3240 if (rv->cur_speed > 0) continue;
3241
3242 /* Ignore crashed vehicles. */
3243 if (rv->vehstatus & VS_CRASHED) continue;
3244
3245 /* Ignore vehicles not on level crossings. */
3246 TileIndex cur_tile = rv->tile;
3247 if (!IsLevelCrossingTile(cur_tile)) continue;
3248
3249 ClosestDepot closestDepot = rv->FindClosestDepot();
3250
3251 /* Try to find a depot with a distance limit of 512 tiles (Manhattan distance). */
3252 if (closestDepot.found && DistanceManhattan(rv->tile, closestDepot.location) < 512u) {
3253 /* Teleport all parts of articulated vehicles. */
3254 for (RoadVehicle *u = rv; u != nullptr; u = u->Next()) {
3255 u->tile = closestDepot.location;
3256 int x = TileX(closestDepot.location) * TILE_SIZE + TILE_SIZE / 2;
3257 int y = TileY(closestDepot.location) * TILE_SIZE + TILE_SIZE / 2;
3258 u->x_pos = x;
3259 u->y_pos = y;
3260 u->z_pos = GetSlopePixelZ(x, y, true);
3261
3262 u->vehstatus |= VS_HIDDEN;
3263 u->state = RVSB_IN_DEPOT;
3264 u->UpdatePosition();
3265 }
3266 RoadVehLeaveDepot(rv, false);
3267 }
3268 }
3269
3271 /* Reset unused tree counters to reduce the savegame size. */
3272 for (auto t : Map::Iterate()) {
3273 if (IsTileType(t, MP_TREES)) {
3274 SB(t.m2(), 0, 4, 0);
3275 }
3276 }
3277 }
3278
3279 /* Refresh all level crossings to bar adjacent crossing tiles, if needed. */
3280 for (const auto tile : Map::Iterate()) {
3281 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile, false);
3282 }
3283 }
3284
3285 /* Compute station catchment areas. This is needed here in case UpdateStationAcceptance is called below. */
3287
3288 /* Station acceptance is some kind of cache */
3290 for (Station *st : Station::Iterate()) UpdateStationAcceptance(st, false);
3291 }
3292
3295 }
3296
3298 /* For older savegames, we don't now the actual interval; so set it to the newgame value. */
3300
3301 /* We did load the "period" of the timer, but not the fired/elapsed. We can deduce that here. */
3303 _new_competitor_timeout.storage.elapsed = 0;
3304 _new_competitor_timeout.fired = _new_competitor_timeout.period.value == 0;
3305 }
3306
3308 /* Set service date provided to NewGRF. */
3309 for (Vehicle *v : Vehicle::Iterate()) {
3310 v->date_of_last_service_newgrf = v->date_of_last_service.base();
3311 }
3312 }
3313
3315 /* NewGRF acceleration information was added to ships. */
3316 for (Ship *s : Ship::Iterate()) {
3317 if (s->acceleration == 0) s->acceleration = ShipVehInfo(s->engine_type)->acceleration;
3318 }
3319 }
3320
3322 for (Company *c : Company::Iterate()) {
3323 c->max_loan = COMPANY_MAX_LOAN_DEFAULT;
3324 }
3325 }
3326
3328 ScriptObject::InitializeRandomizers();
3329 }
3330
3332 for (Company *c : Company::Iterate()) {
3333 c->inaugurated_year_calendar = _settings_game.game_creation.starting_year;
3334 }
3335 }
3336
3337 for (Company *c : Company::Iterate()) {
3339 }
3340
3341 /* Update free group numbers data for each company, required regardless of savegame version. */
3342 for (Group *g : Group::Iterate()) {
3343 Company *c = Company::Get(g->owner);
3345 /* Use the index as group number when converting old savegames. */
3346 g->number = c->freegroups.UseID(g->index);
3347 } else {
3348 c->freegroups.UseID(g->number);
3349 }
3350 }
3351
3355
3357
3359 /* Restore the signals */
3361
3363
3365
3366 /* Start the scripts. This MUST happen after everything else except
3367 * starting a new company. */
3368 StartScripts();
3369
3370 /* If Load Scenario / New (Scenario) Game is used,
3371 * a company does not exist yet. So create one here.
3372 * 1 exception: network-games. Those can have 0 companies
3373 * But this exception is not true for non-dedicated network servers! */
3375 CompanyID first_human_company = GetFirstPlayableCompanyID();
3376 if (!Company::IsValidID(first_human_company)) {
3377 Company *c = DoStartupNewCompany(false, first_human_company);
3379 }
3380 }
3381
3382 return true;
3383}
3384
3394{
3395 /* reload grf data */
3399 /* reload vehicles */
3400 ResetVehicleHash();
3406 /* update station graphics */
3407 AfterLoadStations();
3408 /* Update company statistics. */
3410 /* Check and update house and town values */
3412 /* Delete news referring to no longer existing entities */
3414 /* Update livery selection windows */
3416 /* Update company infrastructure counts. */
3419 /* redraw the whole screen */
3422}
static void SetSignalHandlers()
Replaces signal handlers of SIGSEGV and SIGABRT and stores pointers to original handlers in memory.
static uint FixVehicleInclination(Vehicle *v, Direction dir)
Fixes inclination of a vehicle.
static void InitializeWindowsAndCaches()
Initialization of the windows and several kinds of caches.
static void CheckGroundVehiclesAtCorrectZ()
Check whether the ground vehicles are at the correct Z-coordinate.
static bool _saveload_crash_with_missing_newgrfs
Was the saveload crash because of missing NewGRFs?
static void FixOwnerOfRailTrack(Tile t)
Tries to change owner of this rail tile to a valid owner.
static void CDECL HandleSavegameLoadCrash(int signum)
Signal handler used to give a user a more useful report for crashes during the savegame loading proce...
static bool MayHaveBridgeAbove(Tile t)
Checks for the possibility that a bridge may be on this tile These are in fact all the tile types on ...
Company * DoStartupNewCompany(bool is_ai, CompanyID company=INVALID_COMPANY)
Create a new company and sets all company variables default values.
void SetWaterClassDependingOnSurroundings(Tile t, bool include_invalid_water_class)
Makes a tile canal or water depending on the surroundings.
Definition afterload.cpp:86
static void StartScripts()
Start the scripts.
bool SaveloadCrashWithMissingNewGRFs()
Did loading the savegame cause a crash? If so, were NewGRFs missing?
void UpdateAllVirtCoords()
Update the viewport coordinates of all signs.
bool AfterLoadGame()
Perform a (large) amount of savegame conversion magic in order to load older savegames and to fill th...
void ReloadNewGRFData()
Reload all NewGRF files during a running game.
static void ResetSignalHandlers()
Resets signal handlers back to original handlers.
void GetAircraftFlightLevelBounds(const Vehicle *v, int *min, int *max)
Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular vehicle for normal flight si...
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
void SetAircraftPosition(Aircraft *v, int x, int y, int z)
Set aircraft position.
@ AIR_AIRCRAFT
an airplane
Definition aircraft.h:30
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
@ AT_OILRIG
Oilrig airport.
Definition airport.h:38
@ FLYING
Vehicle is flying in the air.
Definition airport.h:75
std::vector< TileIndex > _animated_tiles
The table/list with animated tiles.
@ Animated
Tile is animated.
@ None
Tile is not animated.
void SetAnimatedTileState(Tile t, AnimatedTileState state)
Set the animated state of a tile.
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
static uint32_t BSWAP32(uint32_t x)
Perform a 32 bits endianness bitswap on x.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
TileIndex GetNorthernBridgeEnd(TileIndex t)
Finds the northern end of a bridge starting at a middle tile.
void SetBridgeMiddle(Tile t, Axis a)
Set that there is a bridge over the given axis.
Definition bridge_map.h:114
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
Definition bridge_map.h:35
void ClearBridgeMiddle(Tile t)
Removes bridges from the given, that is bridges along the X and Y axis.
Definition bridge_map.h:103
bool IsBridge(Tile t)
Checks if this is a bridge, instead of a tunnel.
Definition bridge_map.h:24
void AfterLoadCompanyStats()
Rebuilding of company statistics after loading a savegame.
static const CargoID CARGO_NO_REFIT
Do not refit cargo of a vehicle (used in vehicle orders and auto-replace/auto-renew).
Definition cargo_type.h:78
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:107
@ Industry
Source/destination is an industry.
@ Town
Source/destination is a town.
@ TAE_GOODS
Cargo behaves goods/candy-like.
Definition cargotype.h:26
@ TAE_PASSENGERS
Cargo behaves passenger-like.
Definition cargotype.h:24
@ TAE_MAIL
Cargo behaves mail-like.
Definition cargotype.h:25
@ TAE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition cargotype.h:28
@ TAE_WATER
Cargo behaves water-like.
Definition cargotype.h:27
static void StartNew(CompanyID company)
Start a new AI company.
Definition ai_core.cpp:36
TStorage storage
The storage of the timer.
Definition timer.h:50
UnitID UseID(UnitID index)
Use a unit number.
Definition vehicle.cpp:1863
static void StartNew()
Start up a new GameScript.
Definition game_core.cpp:72
void TestRevision()
Finds out if current revision is different than last revision stored in the savegame.
Definition gamelog.cpp:425
void PrintDebug(int level)
Prints gamelog to debug output.
Definition gamelog.cpp:323
void GRFAddList(const GRFConfig *newg)
Logs adding of list of GRFs.
Definition gamelog.cpp:578
void GRFCompatible(const GRFIdentifier *newg)
Logs loading compatible GRF (the same ID, but different MD5 hash)
Definition gamelog.cpp:542
const GRFIdentifier * GetOverriddenIdentifier(const GRFConfig *c)
Try to find the overridden GRF identifier of the given GRF.
Definition gamelog.cpp:712
void GRFRemove(uint32_t grfid)
Logs removal of a GRF.
Definition gamelog.cpp:517
void Oldver()
Logs loading from savegame without gamelog.
Definition gamelog.cpp:399
void TestMode()
Finds last stored game mode or landscape.
Definition gamelog.cpp:446
uint32_t GetGRFID(uint16_t entity_id) const
Gives the GRFID of the file the entity belongs to.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static constexpr TimerGameTick::Ticks TOWN_GROWTH_TICKS
Cycle duration for towns trying to grow (this originates from the size of the town array in TTD).
Wrapper class to abstract away the way the tiles are stored.
Definition map_func.h:25
debug_inline uint16_t & m2()
Primarily used for indices to towns, industries and stations.
Definition map_func.h:125
debug_inline uint8_t & m7()
Primarily used for newgrf support.
Definition map_func.h:185
debug_inline uint8_t & m6()
General purpose.
Definition map_func.h:173
debug_inline uint8_t & m3()
General purpose.
Definition map_func.h:137
debug_inline uint8_t & m5()
General purpose.
Definition map_func.h:161
A timeout timer will fire once after the interval.
Definition timer.h:116
static void SetDate(Date date, DateFract fract)
Set the date.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static DateFract date_fract
Fractional part of the day.
static constexpr TimerGame< struct Calendar >::Year DEF_END_YEAR
The default scoring end year.
static constexpr TimerGame< struct Economy >::Year MIN_YEAR
The absolute minimum year in OTTD.
static constexpr int SECONDS_PER_DAY
approximate seconds per day, not for precise calculations
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
The date of the first day of the original base year.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static DateFract date_fract
Fractional part of the day.
static void SetDate(Date date, DateFract fract)
Set the date.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
ClearGround GetRawClearGround(Tile t)
Get the type of clear tile but never return CLEAR_SNOW.
Definition clear_map.h:47
bool IsClearGround(Tile t, ClearGround ct)
Set the type of clear tile.
Definition clear_map.h:71
@ CLEAR_GRASS
0-3
Definition clear_map.h:20
@ CLEAR_FIELDS
3
Definition clear_map.h:23
@ CLEAR_SNOW
0-3
Definition clear_map.h:24
void SetFence(Tile t, DiagDirection side, uint h)
Sets the type of fence (and whether there is one) for the given border.
Definition clear_map.h:240
void MakeClear(Tile t, ClearGround g, uint density)
Make a clear tile.
Definition clear_map.h:259
void SetClearGroundDensity(Tile t, ClearGround type, uint density)
Sets ground type and density in one go, also sets the counter to 0.
Definition clear_map.h:158
uint GetClearDensity(Tile t)
Get the density of a non-field clear tile.
Definition clear_map.h:83
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company's primary colour.
void UpdateCompanyLiveries(Company *c)
Update liveries for a company.
TimeoutTimer< TimerGameTick > _new_competitor_timeout({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, 0 }, []() { if(_game_mode==GM_MENU||!AI::CanStartNew()) return;if(_networking &&Company::GetNumItems() >=_settings_client.network.max_companies) return;uint8_t n=0;for(const Company *c :Company::Iterate()) { if(c->is_ai) n++;} if(n >=_settings_game.difficulty.max_no_competitors) return;Command< CMD_COMPANY_CTRL >::Post(CCA_NEW_AI, INVALID_COMPANY, CRR_NONE, INVALID_CLIENT_ID);})
Start a new competitor company if possible.
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
CompanyID _current_company
Company currently doing an action.
CompanyManagerFace ConvertFromOldCompanyManagerFace(uint32_t face)
Converts an old company manager's face format to the new company manager's face format.
Owner
Enum for all companies/owners.
@ INVALID_COMPANY
An invalid company.
@ INVALID_OWNER
An invalid owner.
@ COMPANY_FIRST
First company, same as owner.
@ OWNER_NONE
The tile has no ownership.
@ OWNER_WATER
The tile/execution is done by "water".
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
@ MAX_COMPANIES
Maximum number of companies.
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition debug.h:37
bool IsDepotTile(Tile tile)
Is the given tile a tile with a depot on it?
Definition depot_map.h:41
Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Direction ReverseDir(Direction d)
Return the reverse of a direction.
Direction AxisToDirection(Axis a)
Converts an Axis to a Direction.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
DiagDirection XYNSToDiagDir(Axis xy, uint ns)
Convert an axis and a flag for north/south into a DiagDirection.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Direction
Defines the 8 directions on the map.
@ DIR_SW
Southwest.
@ DIR_NW
Northwest.
@ INVALID_DIR
Flag for an invalid direction.
@ DIR_SE
Southeast.
@ DIR_NE
Northeast.
Axis
Allow incrementing of DiagDirDiff variables.
@ AXIS_X
The X axis.
@ AXIS_Y
The y axis.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_NE
Northeast, upper right on your monitor.
@ DIAGDIR_NW
Northwest.
@ DIAGDIR_SE
Southeast.
@ DIAGDIR_END
Used for iterations.
@ DIAGDIR_BEGIN
Used for iterations.
@ DIAGDIR_SW
Southwest.
void RecomputePrices()
Computes all prices, payments and maximum loan.
Definition economy.cpp:759
bool AddInflation(bool check_year)
Add monthly inflation.
Definition economy.cpp:721
static const uint64_t MAX_INFLATION
Maximum inflation (including fractional part) without causing overflows in int64_t price computations...
void StartupEngines()
Start/initialise all our engines.
Definition engine.cpp:799
void CopyTempEngineData()
Copy data from temporary engine array into the real engine pool.
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition error.h:27
@ FT_SCENARIO
old or new scenario
Definition fileio_type.h:19
Gamelog _gamelog
Gamelog instance.
Definition gamelog.cpp:31
PauseMode _pause_mode
The current pause mode.
Definition gfx.cpp:50
void LoadStringWidthTable(bool monospace)
Initialize _stringwidth_table cache.
Definition gfx.cpp:1210
void GfxLoadSprites()
Initialise and load all the sprites.
Definition gfxinit.cpp:323
@ GVF_GOINGDOWN_BIT
Vehicle is currently going downhill. (Cached track information for acceleration)
@ GVF_GOINGUP_BIT
Vehicle is currently going uphill. (Cached track information for acceleration)
@ GF_REPLACE_PROTECTION
If set to true, the global autoreplace has no effect on the group.
Definition group.h:66
@ GF_REPLACE_WAGON_REMOVAL
If set, autoreplace will perform wagon removal on vehicles in this group.
Definition group.h:67
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1529
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition house.h:26
static const uint8_t TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition house.h:23
IndustryBuildData _industry_builder
In-game manager of industries.
void TrimIndustryAcceptedProduced(Industry *ind)
Remove unused industry accepted/produced slots – entries after the last slot with valid cargo.
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
IndustryType GetIndustryType(Tile tile)
Retrieve the type for this industry.
IndustryGfx GetIndustryGfx(Tile t)
Get the industry graphics ID for the given industry tile.
@ INDUSTRYBEH_PLANT_ON_BUILT
Fields are planted around when built (all farms)
@ INDUSTRYBEH_BUILT_ONWATER
is built on water (oil rig)
void AfterLoadLabelMaps()
Perform rail type and road type conversion if necessary.
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
void AfterLoadLinkGraphs()
Spawn the threads for running link graph calculations.
@ DT_MANUAL
Manual distribution. No link graph calculations are run.
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
Definition main_gui.cpp:546
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:146
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
Definition map_func.h:467
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:373
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition map_func.h:608
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition map_func.h:389
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:425
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:415
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:567
static debug_inline TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:404
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr void Swap(T &a, T &b)
Type safe swap operation.
void GenerateSavegameId()
Generate an unique savegame ID.
Definition misc.cpp:87
bool _networking
are we in networking mode?
Definition network.cpp:65
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:68
bool _network_server
network-server is active
Definition network.cpp:66
@ GSF_FAKE_TOWNS
Fake town GrfSpecFeature for NewGRF debugging (parent scope)
Definition newgrf.h:91
void ShowNewGRFError()
Show the first NewGRF error we can find.
uint8_t StationGfx
Copy from station_map.h.
GRFConfig * _grfconfig
First item in list of current GRF set up.
GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
Check if all GRFs in the GRF config from a savegame can be loaded.
GRFListCompatibility
Status of post-gameload GRF compatibility check.
@ GLC_COMPATIBLE
Compatible (eg. the same ID, but different checksum) GRF found in at least one case.
@ GLC_ALL_GOOD
All GRF needed by game are present.
@ GLC_NOT_FOUND
At least one GRF couldn't be found (higher priority than GLC_COMPATIBLE)
@ GCF_COMPATIBLE
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches)
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
void DeleteInvalidEngineNews()
Remove engine announcements for invalid engines.
uint16_t ObjectType
Types of objects.
Definition object_type.h:14
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition object_type.h:18
static const ObjectType OBJECT_HQ
HeadQuarter of a player.
Definition object_type.h:20
@ PM_UNPAUSED
A normal unpaused game.
Definition openttd.h:69
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
Definition openttd.h:73
@ PM_PAUSED_NORMAL
A game normally paused.
Definition openttd.h:70
OrderDepotActionFlags
Actions that can be performed when the vehicle enters the depot.
Definition order_type.h:102
@ OLFB_NO_LOAD
Do not load anything.
Definition order_type.h:66
@ OSL_PLATFORM_FAR_END
Stop at the far end of the platform.
Definition order_type.h:86
@ OUFB_TRANSFER
Transfer all cargo onto the platform.
Definition order_type.h:55
@ OUFB_UNLOAD
Force unloading all cargo onto the platform, possibly not getting paid.
Definition order_type.h:54
@ ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
The vehicle will not stop at any stations it passes except the destination.
Definition order_type.h:74
RailTypes GetCompanyRailTypes(CompanyID company, bool introduces)
Get the rail types the given company can build.
Definition rail.cpp:251
void InitializeRailGUI()
Resets the rail GUI - sets default railtype to build and resets the signal GUI.
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition rail_map.h:115
static debug_inline bool IsRailDepotTile(Tile t)
Is this tile rail tile and a rail depot?
Definition rail_map.h:105
@ RAIL_GROUND_WATER
Grass with a fence and shore or water on the free halftile.
Definition rail_map.h:499
void SetTrackReservation(Tile t, TrackBits b)
Sets the reserved track bits of the tile.
Definition rail_map.h:209
static debug_inline bool IsRailDepot(Tile t)
Is this rail tile a rail depot?
Definition rail_map.h:95
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
Definition rail_map.h:270
static debug_inline bool IsPlainRail(Tile t)
Returns whether this is plain rails, with or without signals.
Definition rail_map.h:49
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition rail_map.h:72
static debug_inline bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition rail_map.h:60
void SetSignalStates(Tile tile, uint state)
Set the states of the signals (Along/AgainstTrackDir)
Definition rail_map.h:352
void SetRailType(Tile t, RailType r)
Sets the rail type of the given tile.
Definition rail_map.h:125
RailType
Enumeration for all possible railtypes.
Definition rail_type.h:27
@ RAILTYPE_ELECTRIC
Electric rails.
Definition rail_type.h:30
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition rail_type.h:29
RoadTypes GetCompanyRoadTypes(CompanyID company, bool introduces)
Get the road types the given company can build.
Definition road.cpp:199
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
void UpdateLevelCrossing(TileIndex tile, bool sound=true, bool force_bar=false)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition road_map.h:251
bool HasTownOwnedRoad(Tile t)
Checks if given tile has town owned road.
Definition road_map.h:280
static debug_inline bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
Definition road_map.h:106
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
Definition road_map.h:95
@ ROAD_TILE_NORMAL
Normal road.
Definition road_map.h:23
@ ROAD_TILE_DEPOT
Depot (one entrance)
Definition road_map.h:25
@ ROAD_TILE_CROSSING
Level crossing.
Definition road_map.h:24
void SetRoadTypes(Tile t, RoadType road_rt, RoadType tram_rt)
Set the present road types of a tile.
Definition road_map.h:619
RoadBits GetCrossingRoadBits(Tile tile)
Get the road bits of a level crossing.
Definition road_map.h:348
Owner GetRoadOwner(Tile t, RoadTramType rtt)
Get the owner of a specific road type.
Definition road_map.h:234
static debug_inline RoadTileType GetRoadTileType(Tile t)
Get the type of the road tile.
Definition road_map.h:52
void SetCrossingReservation(Tile t, bool b)
Set the reservation state of the rail crossing.
Definition road_map.h:393
bool IsLevelCrossing(Tile t)
Return whether a tile is a level crossing.
Definition road_map.h:85
RoadBits
Enumeration for the road parts on a tile.
Definition road_type.h:52
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
Definition road_type.h:59
@ ROAD_X
Full road along the x-axis (south-west + north-east)
Definition road_type.h:58
RoadTypes
The different roadtypes we support, but then a bitmask of them.
Definition road_type.h:38
RoadType
The different roadtypes we support.
Definition road_type.h:25
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition road_type.h:30
@ ROADTYPE_TRAM
Trams.
Definition road_type.h:28
@ ROADTYPE_ROAD
Basic road type.
Definition road_type.h:27
@ RVS_ENTERED_STOP
Only set when a vehicle has entered the stop.
Definition roadveh.h:43
@ RVSB_IN_ROAD_STOP
The vehicle is in a road stop.
Definition roadveh.h:49
@ RVS_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition roadveh.h:46
@ RVS_IN_ROAD_STOP
The vehicle is in a road stop.
Definition roadveh.h:45
@ RVSB_IN_DEPOT
The vehicle is in a depot.
Definition roadveh.h:38
@ RVSB_WORMHOLE
The vehicle is in a tunnel and/or bridge.
Definition roadveh.h:39
@ RVS_DRIVE_SIDE
Only used when retrieving move data.
Definition roadveh.h:44
const uint8_t _road_stop_stop_frame[]
Table of road stop stop frames, when to stop at a road stop.
void SlError(StringID string, const std::string &extra_msg)
Error handler.
Definition saveload.cpp:321
void SetSaveLoadError(StringID str)
Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friend...
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition saveload.cpp:351
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition saveload.cpp:60
bool IsSavegameVersionBefore(SaveLoadVersion major, uint8_t minor=0)
Checks whether the savegame is below major.
Definition saveload.h:1263
@ SLV_AI_START_DATE
309 PR#10653 Removal of individual AI start dates and added a generic one.
Definition saveload.h:350
@ SLV_190
190 26547 Separate order travel and wait times
Definition saveload.h:271
@ SLV_91
91 12347
Definition saveload.h:152
@ SLV_49
49 8969
Definition saveload.h:101
@ SLV_90
90 12293
Definition saveload.h:151
@ SLV_64
64 10006
Definition saveload.h:119
@ SLV_69
69 10319
Definition saveload.h:125
@ SLV_ECONOMY_MODE_TIMEKEEPING_UNITS
327 PR#11341 Mode to display economy measurements in wallclock units.
Definition saveload.h:372
@ SLV_172
172 23947
Definition saveload.h:249
@ SLV_182
182 25115 FS#5492, r25259, r25296 Goal status
Definition saveload.h:261
@ SLV_186
186 25833 Objects storage
Definition saveload.h:266
@ SLV_175
175 24136
Definition saveload.h:253
@ SLV_16
16.0 2817 16.1 3155
Definition saveload.h:60
@ SLV_87
87 12129
Definition saveload.h:147
@ SLV_SERVE_NEUTRAL_INDUSTRIES
210 PR#7234 Company stations can serve industries with attached neutral stations.
Definition saveload.h:296
@ SLV_147
147 20621
Definition saveload.h:219
@ SLV_188
188 26169 v1.4 FS#5831 Unify RV travel time
Definition saveload.h:268
@ SLV_61
61 9892
Definition saveload.h:116
@ SLV_84
84 11822
Definition saveload.h:143
@ SLV_25
25 4259
Definition saveload.h:73
@ SLV_15
15.0 2499
Definition saveload.h:59
@ SLV_198
198 PR#6763 Switch town growth rate and counter to actual game ticks
Definition saveload.h:281
@ SLV_36
36 6624
Definition saveload.h:86
@ SLV_26
26 4466
Definition saveload.h:74
@ SLV_96
96 13226
Definition saveload.h:158
@ SLV_EXTEND_RAILTYPES
200 PR#6805 Extend railtypes to 64, adding uint16_t to map array.
Definition saveload.h:284
@ SLV_17
17.0 3212 17.1 3218
Definition saveload.h:62
@ SLV_42
42 7573
Definition saveload.h:93
@ SLV_177
177 24619
Definition saveload.h:255
@ SLV_EXTEND_INDUSTRY_CARGO_SLOTS
202 PR#6867 Increase industry cargo slots to 16 in, 16 out
Definition saveload.h:286
@ SLV_103
103 14598
Definition saveload.h:166
@ SLV_100
100 13952
Definition saveload.h:163
@ SLV_GROUP_REPLACE_WAGON_REMOVAL
291 PR#7441 Per-group wagon removal flag.
Definition saveload.h:329
@ SLV_VELOCITY_NAUTICAL
305 PR#10594 Separation of land and nautical velocity (knots!)
Definition saveload.h:346
@ SLV_VEHICLE_ECONOMY_AGE
334 PR#12141 v14.0 Add vehicle age in economy year, for profit stats minimum age
Definition saveload.h:380
@ SLV_4
4.0 1 4.1 122 0.3.3, 0.3.4 4.2 1222 0.3.5 4.3 1417 4.4 1426
Definition saveload.h:37
@ SLV_TOWN_CARGOGEN
208 PR#6965 New algorithms for town building cargo generation.
Definition saveload.h:293
@ SLV_149
149 20832
Definition saveload.h:221
@ SLV_83
83 11589
Definition saveload.h:142
@ SLV_6
6.0 1721 6.1 1768
Definition saveload.h:46
@ SLV_34
34 6455
Definition saveload.h:83
@ SLV_LINKGRAPH_SECONDS
308 PR#10610 Store linkgraph update intervals in seconds instead of days.
Definition saveload.h:349
@ SLV_114
114 15601
Definition saveload.h:179
@ SLV_137
137 18912
Definition saveload.h:207
@ SLV_SAVEGAME_ID
313 PR#10719 Add an unique ID to every savegame (used to deduplicate surveys).
Definition saveload.h:355
@ SLV_131
131 18481
Definition saveload.h:200
@ SLV_11
11.0 2033 11.1 2041
Definition saveload.h:53
@ SLV_120
120 16439
Definition saveload.h:187
@ SLV_99
99 13838
Definition saveload.h:161
@ SLV_123
123 16909
Definition saveload.h:190
@ SLV_46
46 8705
Definition saveload.h:98
@ SLV_122
122 16855
Definition saveload.h:189
@ SLV_ENDING_YEAR
218 PR#7747 v1.10 Configurable ending year.
Definition saveload.h:305
@ SLV_141
141 19799
Definition saveload.h:212
@ SLV_112
112 15290
Definition saveload.h:177
@ SLV_125
125 17113
Definition saveload.h:193
@ SLV_166
166 23415
Definition saveload.h:242
@ SLV_98
98 13375
Definition saveload.h:160
@ SLV_WATER_TILE_TYPE
342 PR#13030 Simplify water tile type.
Definition saveload.h:390
@ SLV_117
117 16037
Definition saveload.h:183
@ SLV_140
140 19382
Definition saveload.h:211
@ SLV_126
126 17433
Definition saveload.h:194
@ SLV_138
138 18942 1.0.x
Definition saveload.h:208
@ SLV_ANIMATED_TILE_STATE_IN_MAP
347 PR#13082 Animated tile state saved for improved performance.
Definition saveload.h:396
@ SLV_MULTITILE_DOCKS
216 PR#7380 Multiple docks per station.
Definition saveload.h:303
@ SLV_86
86 12042
Definition saveload.h:146
@ SLV_ROAD_TYPES
214 PR#6811 NewGRF road types.
Definition saveload.h:300
@ SLV_1
1.0 0.1.x, 0.2.x
Definition saveload.h:33
@ SLV_GS_INDUSTRY_CONTROL
287 PR#7912 and PR#8115 GS industry control.
Definition saveload.h:324
@ SLV_164
164 23290
Definition saveload.h:239
@ SLV_160
160 21974 1.1.x
Definition saveload.h:235
@ SLV_38
38 7195
Definition saveload.h:88
@ SLV_145
145 20376
Definition saveload.h:217
@ SLV_48
48 8935
Definition saveload.h:100
@ SLV_57
57 9691
Definition saveload.h:111
@ SLV_104
104 14735
Definition saveload.h:167
@ SLV_52
52 9066
Definition saveload.h:105
@ SLV_134
134 18703
Definition saveload.h:203
@ SLV_165
165 23304
Definition saveload.h:241
@ SLV_144
144 20334
Definition saveload.h:215
@ SLV_2
2.0 0.3.0 2.1 0.3.1, 0.3.2
Definition saveload.h:34
@ SLV_INCREASE_HOUSE_LIMIT
348 PR#12288 Increase house limit to 4096.
Definition saveload.h:397
@ SLV_143
143 20048
Definition saveload.h:214
@ SLV_127
127 17439
Definition saveload.h:195
@ SLV_152
152 21171
Definition saveload.h:225
@ SLV_LAST_LOADING_TICK
301 PR#9693 Store tick of last loading for vehicles.
Definition saveload.h:341
@ SLV_76
76 11139
Definition saveload.h:134
@ SLV_SCRIPT_RANDOMIZER
333 PR#12063 v14.0-RC1 Save script randomizers.
Definition saveload.h:379
@ SLV_COMPANY_INAUGURATED_PERIOD
339 PR#12798 Companies show the period inaugurated in wallclock mode.
Definition saveload.h:386
@ SLV_78
78 11176
Definition saveload.h:136
@ SLV_106
106 14919
Definition saveload.h:170
@ SLV_DEPOT_UNBUNCHING
331 PR#11945 Allow unbunching shared order vehicles at a depot.
Definition saveload.h:377
@ SLV_119
119 16242
Definition saveload.h:185
@ SLV_139
139 19346
Definition saveload.h:209
@ SLV_SHIP_ACCELERATION
329 PR#10734 Start using Vehicle's acceleration field for ships too.
Definition saveload.h:374
@ SLV_135
135 18719
Definition saveload.h:205
@ SLV_MULTITRACK_LEVEL_CROSSINGS
302 PR#9931 v13.0 Multi-track level crossings.
Definition saveload.h:342
@ SLV_121
121 16694
Definition saveload.h:188
@ SLV_192
192 26700 FS#6066 Fix saving of order backups
Definition saveload.h:274
@ SLV_58
58 9762
Definition saveload.h:112
@ SLV_94
94 12816
Definition saveload.h:155
@ SLV_153
153 21263
Definition saveload.h:226
@ SLV_101
101 14233
Definition saveload.h:164
@ SLV_95
95 12924
Definition saveload.h:157
@ SLV_158
158 21933
Definition saveload.h:232
@ SLV_133
133 18674
Definition saveload.h:202
@ SLV_93
93 12648
Definition saveload.h:154
@ SLV_81
81 11244
Definition saveload.h:140
@ SLV_72
72 10601
Definition saveload.h:129
@ SLV_43
43 7642
Definition saveload.h:94
@ SLV_113
113 15340
Definition saveload.h:178
@ SLV_ECONOMY_DATE
326 PR#10700 Split calendar and economy timers and dates.
Definition saveload.h:371
@ SLV_45
45 8501
Definition saveload.h:97
@ SLV_128
128 18281
Definition saveload.h:196
@ SLV_GROUP_NUMBERS
336 PR#12297 Add per-company group numbers.
Definition saveload.h:383
@ SLV_NEWGRF_LAST_SERVICE
317 PR#11124 Added stable date_of_last_service to avoid NewGRF trouble.
Definition saveload.h:360
@ SLV_53
53 9316
Definition saveload.h:106
@ SLV_161
161 22567
Definition saveload.h:236
@ SLV_74
74 11030
Definition saveload.h:131
@ SLV_184
184 25508 Unit localisation split
Definition saveload.h:263
@ SLV_INCREASE_STATION_TYPE_FIELD_SIZE
337 PR#12572 Increase size of StationType field in map array
Definition saveload.h:384
@ SLV_88
88 12134
Definition saveload.h:148
@ SLV_156
156 21728
Definition saveload.h:230
@ SLV_NONFLOODING_WATER_TILES
345 PR#13013 Store water tile non-flooding state.
Definition saveload.h:394
@ SLV_62
62 9905
Definition saveload.h:117
@ SLV_59
59 9779
Definition saveload.h:113
@ SLV_82
82 11410
Definition saveload.h:141
@ SLV_194
194 26881 v1.5
Definition saveload.h:276
@ SLV_TREES_WATER_CLASS
213 PR#7405 WaterClass update for tree tiles.
Definition saveload.h:299
@ SLV_124
124 16993
Definition saveload.h:191
@ SLV_159
159 21962
Definition saveload.h:233
@ SLV_32
32 6001
Definition saveload.h:81
@ SLV_56
56 9667
Definition saveload.h:110
@ SLV_SHIPS_STOP_IN_LOCKS
206 PR#7150 Ship/lock movement changes.
Definition saveload.h:291
@ SLV_111
111 15190
Definition saveload.h:176
@ SLV_70
70 10541
Definition saveload.h:127
@ SLV_183
183 25363 Cargodist
Definition saveload.h:262
@ SLV_31
31 5999
Definition saveload.h:80
@ SLV_148
148 20659
Definition saveload.h:220
@ SLV_50
50 8973
Definition saveload.h:103
@ SLV_REPAIR_OBJECT_DOCKING_TILES
299 PR#9594 v12.0 Fixing issue with docking tiles overlapping objects.
Definition saveload.h:338
@ SLV_CONSISTENT_PARTIAL_Z
306 PR#10570 Conversion from an inconsistent partial Z calculation for slopes, to one that is (more) ...
Definition saveload.h:347
@ SLV_142
142 20003
Definition saveload.h:213
@ SLV_21
21 3472 0.4.x
Definition saveload.h:68
@ SLV_136
136 18764
Definition saveload.h:206
@ SLV_146
146 20446
Definition saveload.h:218
@ SLV_MAX_LOAN_FOR_COMPANY
330 PR#11224 Separate max loan for each company.
Definition saveload.h:376
@ SLV_24
24 4150
Definition saveload.h:71
@ SLV_9
9.0 1909
Definition saveload.h:50
bool IsSavegameVersionBeforeOrAt(SaveLoadVersion major)
Checks whether the savegame is below or at major.
Definition saveload.h:1277
Declaration of functions used in more save/load files.
void AfterLoadVehiclesPhase1(bool part_of_load)
Called after load for phase 1 of vehicle initialisation.
void ResetOldNames()
Free the memory of the old names array.
void FixupTrainLengths()
Fixup old train spacing.
void MoveBuoysToWaypoints()
Perform all steps to upgrade from the old station buoys to the new version that uses waypoints.
void UpdateOldAircraft()
need to be called to load aircraft from old version
void ConvertOldMultiheadToNew()
Converts all trains to the new subtype format introduced in savegame 16.2 It also links multiheaded e...
void ConnectMultiheadedTrains()
Link front and rear multiheaded engines to each other This is done when loading a savegame.
void AfterLoadRoadStops()
(Re)building of road stop caches after loading a savegame.
void MoveWaypointsToBaseStations()
Perform all steps to upgrade from the old waypoints to the new version that uses station.
void AfterLoadVehiclesPhase2(bool part_of_load)
Called after load for phase 2 of vehicle initialisation.
void UpdateHousesAndTowns()
Check and update town and house values.
Definition town_sl.cpp:64
std::string CopyFromOldName(StringID id)
Copy and convert old custom names to UTF-8.
void AfterLoadStoryBook()
Called after load to trash broken pages.
Definition story_sl.cpp:20
void ShowScriptDebugWindowIfScriptError()
Open the AI debug window if one of the AI scripts has crashed.
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
Definition settings.cpp:59
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:57
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition settings.cpp:58
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:56
@ SIGTYPE_COMBO
presignal inter-block
Definition signal_type.h:27
@ SIG_SEMAPHORE
Old-fashioned semaphore signal.
Definition signal_type.h:18
@ SIG_ELECTRIC
Light signal.
Definition signal_type.h:17
void UpdateAllSignVirtCoords()
Update the coordinates of all signs.
Definition signs.cpp:59
DiagDirection GetInclinedSlopeDirection(Slope s)
Returns the direction of an inclined slope.
Definition slope_func.h:239
void BuildOwnerLegend()
Completes the array for the owned property legend.
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
void UpdateStationAcceptance(Station *st, bool show_msg)
Update the acceptance for a station.
void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
Set rail station tile flags for the given tile.
StationType GetStationType(Tile t)
Get the station type of this tile.
Definition station_map.h:44
StationGfx GetStationGfx(Tile t)
Get the station graphics of this tile.
Definition station_map.h:68
void SetStationGfx(Tile t, StationGfx gfx)
Set the station graphics of this tile.
Definition station_map.h:80
bool IsAirportTile(Tile t)
Is this tile a station tile and an airport tile?
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
bool IsBuoy(Tile t)
Is tile t a buoy tile?
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
bool HasStationTileRail(Tile t)
Has this station tile a rail? In other words, is this station tile a rail station or rail waypoint?
void SetRailStationReservation(Tile t, bool b)
Set the reservation state of the rail station.
bool IsAnyRoadStop(Tile t)
Is the station at t a road station?
bool IsStationTileBlocked(Tile t)
Is tile t a blocked tile?
bool IsTruckStop(Tile t)
Is the station at t a truck stop?
bool IsStationRoadStop(Tile t)
Is the station at t a road station?
bool HasStationRail(Tile t)
Has this station tile a rail? In other words, is this station tile a rail station or rail waypoint?
static const int GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET
The offset for the drive through parts.
Definition station_map.h:36
bool IsOilRig(Tile t)
Is tile t part of an oilrig?
bool IsBuoyTile(Tile t)
Is tile t a buoy tile?
bool IsDock(Tile t)
Is tile t a dock tile?
@ FACIL_DOCK
Station with a dock.
@ FACIL_AIRPORT
Station with an airport.
@ FACIL_TRAIN
Station with train station.
StationType
Station types.
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition stdafx.h:343
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:81
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Information about a aircraft vehicle.
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition aircraft.h:72
Class to backup a specific variable and restore it later.
void Restore()
Restore the variable.
Base class for all station-ish types.
TileArea train_station
Tile area the train 'station' part covers.
Owner owner
The owner of this station.
StationRect rect
NOSAVE: Station spread out rectangle maintained by StationRect::xxx() functions.
Town * town
The town this station is associated with.
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
VehicleType type
Type of vehicle.
static void AfterLoad()
Savegame conversion for cargopackets.
Helper class to perform the cargo payment.
Specification of a cargo type.
Definition cargotype.h:76
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition cargotype.h:139
TownAcceptanceEffect town_acceptance_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition cargotype.h:88
CompanySettings company
default values for per-company settings
Structure to return information about the closest depot location, and whether it could be found.
CompanySettings settings
settings specific for each company
static bool IsValidAiID(size_t index)
Is this company a valid company, controlled by the computer (a NoAI program)?
bool freeform_edges
allow terraforming the tiles at the map edges
uint16_t max_bridge_length
maximum length of bridges
uint16_t terraform_frame_burst
how many tile heights may, over a short period, be terraformed?
uint16_t max_tunnel_length
maximum length of tunnels
uint16_t tree_frame_burst
how many trees may, over a short period, be planted?
uint8_t map_height_limit
the maximum allowed heightlevel
uint16_t clear_frame_burst
how many tiles may, over a short period, be cleared?
uint8_t number_towns
the amount of towns
uint32_t max_loan
the maximum initial loan
uint16_t competitors_interval
the interval (in minutes) between adding competitors
uint8_t industry_density
The industry density.
Disasters, like submarines, skyrangers and their shadows, belong to this class.
TownLayout town_layout
select town layout,
TimekeepingUnits timekeeping_units
time units to use for the game economy, either calendar or wallclock
bool allow_town_level_crossings
towns are allowed to build level crossings
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
bool station_noise_level
build new airports when the town noise level is still within accepted limits
bool infrastructure_maintenance
enable monthly maintenance fee for owner infrastructure
uint8_t feeder_payment_share
percentage of leg payment to virtually pay in feeder systems
TownCargoGenMode town_cargogen_mode
algorithm for generating cargo from houses,
uint8_t larger_towns
the number of cities to build. These start off larger and grow twice as fast
uint64_t inflation_payment
Cumulated inflation of cargo payment since game start; 16 bit fractional part.
uint64_t inflation_prices
Cumulated inflation of prices since game start; 16 bit fractional part.
Money old_max_loan_unround
Old: Unrounded max loan.
uint16_t old_max_loan_unround_fract
Old: Fraction of the unrounded max loan.
uint8_t misc_flags
Miscellaneous flags.
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Definition saveload.h:413
Information about GRF, used in the game and (part of it) in savegames.
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Basic data to distinguish a GRF.
MD5Hash md5sum
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF)
TimerGameCalendar::Year ending_year
scoring end date
uint8_t snow_line_height
the configured snow line height (deduced from "snow_coverage")
uint8_t landscape
the landscape we're currently in
uint8_t town_name
the town name generator used for town names
TimerGameCalendar::Year starting_year
starting date
LocaleSettings locale
settings related to used currency/unit system in the current game
PathfinderSettings pf
settings for all pathfinders
EconomySettings economy
settings to change the economy
ConstructionSettings construction
construction of things in-game
DifficultySettings difficulty
settings related to the difficulty
GameCreationSettings game_creation
settings used during the creation of a game (map)
StationSettings station
settings related to station management
VehicleSettings vehicle
options for vehicles
LinkGraphSettings linkgraph
settings for link graph calculations
Stores station stats for a single cargo.
@ GES_RATING
This indicates whether a cargo has a rating at the station.
static void UpdateAfterLoad()
Update all caches after loading a game, changing NewGRF, etc.
Group data.
Definition group.h:72
void Reset()
Completely reset the industry build data.
Defines the data structure for constructing industry.
std::array< CargoID, INDUSTRY_NUM_INPUTS > accepts_cargo
16 accepted cargoes.
IndustryBehaviour behaviour
How this industry will behave, and how others entities can use it.
Defines the internal data of a functional industry.
Definition industry.h:66
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition industry.h:238
uint16_t recalc_time
time (in days) for recalculating each link graph component.
DistributionType distribution_mail
distribution type for mail
DistributionType distribution_default
distribution type for all other goods
DistributionType distribution_pax
distribution type for passengers
DistributionType distribution_armoured
distribution type for armoured cargo class
uint16_t recalc_interval
time (in days) between subsequent checks for link graphs to be calculated.
uint8_t units_velocity_nautical
unit system for velocity of ships and aircraft
uint8_t currency
currency we currently use
uint8_t units_velocity
unit system for velocity of trains and road vehicles
uint8_t units_power
unit system for power
uint8_t units_height
unit system for height
uint8_t units_force
unit system for force
uint8_t units_volume
unit system for volume
uint8_t units_weight
unit system for weight
Size related data of the map.
Definition map_func.h:206
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:279
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
Definition map_func.h:363
static debug_inline uint SizeX()
Get the size of the map along the X.
Definition map_func.h:270
static uint MaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
Definition map_func.h:306
static debug_inline uint MaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition map_func.h:297
An object, such as transmitter, on the map.
Definition object_base.h:23
ObjectType type
Type of the object.
Definition object_base.h:24
Town * town
Town the object is built in.
Definition object_base.h:25
static void IncTypeCount(ObjectType type)
Increment the count of objects for this type.
Definition object_base.h:43
TimerGameCalendar::Date build_date
Date of construction.
Definition object_base.h:27
TileArea location
Location of the object.
Definition object_base.h:26
Data for backing up an order of a vehicle so it can be restored after a vehicle is rebuilt in the sam...
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition order_base.h:259
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:70
uint16_t w
The width of the area.
TileIndex tile
The base tile of the area.
uint16_t h
The height of the area.
uint8_t wait_for_pbs_path
how long to wait for a path reservation.
uint8_t wait_oneway_signal
waitingtime in days before a oneway signal
bool reverse_at_signals
whether to reverse at signals at all
bool forbid_90_deg
forbid trains to make 90 deg turns
uint8_t wait_twoway_signal
waitingtime in days before a twoway signal
Tindex index
Index of this pool item.
static size_t GetNumItems()
Returns number of valid items in the pool.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
static Titem * Get(size_t index)
Returns Titem with given index.
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
Definition pool_type.hpp:84
RailType railtype
Railtype, mangled if elrail is disabled.
Definition engine_type.h:46
A Stop for a Road Vehicle.
Buses, trucks and trams belong to this class.
Definition roadveh.h:98
uint8_t state
Definition roadveh.h:100
RoadType roadtype
NOSAVE: Roadtype of this vehicle.
Definition roadveh.h:108
uint8_t acceleration
Acceleration (1 unit = 1/3.2 mph per tick = 0.5 km-ish/h per tick)
Definition engine_type.h:71
All ships have this type.
Definition ship.h:32
static bool IsExpected(const BaseStation *st)
Helper for checking whether the given station is of this type.
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
static Station * Get(size_t index)
Gets station with given index.
static Station * GetIfValid(size_t index)
Returns station if the index is a valid index for this station type.
static Station * From(BaseStation *st)
Converts a BaseStation to SpecializedStation with type checking.
T * Next() const
Get next vehicle in the chain.
static Pool::IterateWrapper< T > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
bool modified_catchment
different-size catchment areas
bool serve_neutral_industries
company stations can serve industries with attached neutral stations
Station data structure.
RoadStop * bus_stops
All the road stops.
static void RecomputeCatchmentForAll()
Recomputes catchment of all stations.
Definition station.cpp:530
RoadStop * truck_stops
All the truck stops.
Struct about subsidies, offered and awarded.
Town data structure.
Definition town.h:54
'Train' is either a loco or a wagon.
Definition train.h:89
Default settings for vehicles.
uint8_t plane_crashes
number of plane crashes, 0 = none, 1 = reduced, 2 = normal
uint8_t roadveh_acceleration_model
realistic acceleration for road vehicles
uint8_t roadveh_slope_steepness
Steepness of hills for road vehicles when using realistic acceleration.
uint8_t train_acceleration_model
realistic acceleration for trains
uint8_t train_slope_steepness
Steepness of hills for trains when using realistic acceleration.
uint8_t road_side
the side of the road vehicles drive on
bool dynamic_engines
enable dynamic allocation of engine data
uint8_t max_train_length
maximum length for trains
uint8_t plane_speed
divisor for speed of aircraft
bool disable_elrails
when true, the elrails are disabled
Vehicle data structure.
Direction direction
facing
Order current_order
The current order (+ status, like: loading)
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
uint8_t vehstatus
Status.
TileIndex tile
Current tile index.
Owner owner
Which company owns the vehicle?
Representation of a waypoint.
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
Definition subsidy.cpp:134
bool MayAnimateTile(TileIndex tile)
Test if a tile may be animated.
Definition tile_cmd.h:202
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition tile_map.cpp:95
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition tile_map.cpp:136
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition tile_map.cpp:116
uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition tile_map.h:324
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition tile_map.h:214
void SetTileType(Tile tile, TileType type)
Set the type of a tile.
Definition tile_map.h:131
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
void SetTileOwner(Tile tile, Owner owner)
Sets the owner of a tile.
Definition tile_map.h:198
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition tile_map.h:312
static debug_inline TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition tile_map.h:96
void SetAnimationFrame(Tile t, uint8_t frame)
Set a new animation frame.
Definition tile_map.h:262
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
Definition tile_map.h:279
void SetTropicZone(Tile tile, TropicZone type)
Set the tropic zone.
Definition tile_map.h:225
static debug_inline uint TileHeight(Tile tile)
Returns the height of a tile.
Definition tile_map.h:29
@ TROPICZONE_NORMAL
Normal tropiczone.
Definition tile_type.h:77
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in ZOOM_BASE.
Definition tile_type.h:18
static const uint MIN_SNOWLINE_HEIGHT
Minimum snowline height.
Definition tile_type.h:32
static const uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
static const uint TILE_UNIT_MASK
For masking in/out the inner-tile world coordinate units.
Definition tile_type.h:16
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:95
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:87
@ MP_TREES
Tile got trees.
Definition tile_type.h:52
@ MP_ROAD
A tile with road (or tram tracks)
Definition tile_type.h:50
@ MP_STATION
A tile of a station.
Definition tile_type.h:53
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition tile_type.h:57
@ MP_CLEAR
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition tile_type.h:48
@ MP_HOUSE
A house by a town.
Definition tile_type.h:51
@ MP_WATER
Water tile.
Definition tile_type.h:54
@ MP_RAILWAY
A railway.
Definition tile_type.h:49
@ MP_INDUSTRY
Part of an industry.
Definition tile_type.h:56
@ MP_VOID
Invisible tiles at the SW and SE border.
Definition tile_type.h:55
@ MP_OBJECT
Contains objects such as transmitters and owned land.
Definition tile_type.h:58
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition town.h:33
const CargoSpec * FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect)
Determines the first cargo with a certain town effect.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition town.h:34
@ TOWN_CUSTOM_GROWTH
Growth rate is controlled by GS.
Definition town.h:199
void UpdateTownMaxPass(Town *t)
Update the maximum amount of montly passengers and mail for a town, based on its population.
void ClearAllTownCachedNames()
Clear the cached_name of all towns.
Definition town_cmd.cpp:435
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
static const uint16_t TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition town.h:35
void MakeDefaultName(T *obj)
Set the default name for a depot/waypoint.
Definition town.h:254
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition town_cmd.cpp:427
HouseID GetHouseType(Tile t)
Get the type of this house, which is an index into the house spec array.
Definition town_map.h:60
void SetHouseType(Tile t, HouseID house_id)
Set the house type.
Definition town_map.h:71
void SetLiftPosition(Tile t, uint8_t pos)
Set the position of the lift on this animated house.
Definition town_map.h:135
void SetHouseCompleted(Tile t, bool status)
Mark this house as been completed.
Definition town_map.h:156
void SetTownIndex(Tile t, TownID index)
Set the town index for a road or house tile.
Definition town_map.h:35
bool IsHouseCompleted(Tile t)
Get the completion of this house.
Definition town_map.h:145
static constexpr int RATING_INITIAL
initial rating
Definition town_type.h:43
@ TCGM_ORIGINAL
Original algorithm (quadratic cargo by population)
Definition town_type.h:104
TownLayout
Town Layouts.
Definition town_type.h:79
@ TL_RANDOM
Random town layout.
Definition town_type.h:86
@ TL_BETTER_ROADS
Extended original algorithm (min. 2 distance between roads)
Definition town_type.h:82
TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track bits incidating with that diagdir.
Definition track_func.h:524
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
Definition track_func.h:537
TrackBits TrackStatusToTrackBits(TrackStatus ts)
Returns the present-track-information of a TrackStatus.
Definition track_func.h:363
TrackBits
Allow incrementing of Track variables.
Definition track_type.h:35
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels)
Definition track_type.h:52
@ TRACK_BIT_Y
Y-axis track.
Definition track_type.h:38
@ TRACK_BIT_NONE
No track.
Definition track_type.h:36
@ TRACK_BIT_X
X-axis track.
Definition track_type.h:37
@ INVALID_TRACK
Flag for an invalid track.
Definition track_type.h:28
@ TRACK_LOWER
Track in the lower corner of the tile (south)
Definition track_type.h:24
@ TRACK_UPPER
Track in the upper corner of the tile (north)
Definition track_type.h:23
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition train_cmd.cpp:76
@ TFP_NONE
Normal operation.
Definition train.h:38
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
Definition train.h:39
TransportType
Available types of transport.
@ TRANSPORT_RAIL
Transport by train.
@ TRANSPORT_ROAD
Transport by road vehicle.
TreeGround GetTreeGround(Tile t)
Returns the groundtype for tree tiles.
Definition tree_map.h:102
TreeGround
Enumeration for ground types of tiles with trees.
Definition tree_map.h:52
@ TREE_GROUND_SHORE
shore
Definition tree_map.h:56
@ TREE_GROUND_SNOW_DESERT
a desert or snow tile, depend on landscape
Definition tree_map.h:55
bool IsTunnelTile(Tile t)
Is this a tunnel (entrance)?
Definition tunnel_map.h:34
const uint8_t _tunnel_visibility_frame[DIAGDIR_END]
Frame when a vehicle should be hidden in a tunnel with a certain direction.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TransportType GetTunnelBridgeTransportType(Tile t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
void SetTunnelBridgeReservation(Tile t, bool b)
Set the reservation state of the rail tunnel/bridge.
@ VF_PATHFINDER_LOST
Vehicle's pathfinder is lost.
@ VF_LOADING_FINISHED
Vehicle has finished loading.
@ VS_STOPPED
Vehicle is stopped by the player.
@ VS_HIDDEN
Vehicle is not visible.
@ VS_CRASHED
Vehicle is crashed.
@ VEH_INVALID
Non-existing type of vehicle.
@ VEH_ROAD
Road vehicle type.
@ VEH_SHIP
Ship vehicle type.
@ VEH_TRAIN
Train vehicle type.
void MakeVoid(Tile t)
Make a nice void tile ;)
Definition void_map.h:19
void MakeShore(Tile t)
Helper function to make a coast tile.
Definition water_map.h:381
void SetWaterClass(Tile t, WaterClass wc)
Set the water class at a tile.
Definition water_map.h:124
bool IsShipDepot(Tile t)
Is it a water tile with a ship depot on it?
Definition water_map.h:222
WaterClass
classes of water (for WATER_TILE_CLEAR water tile type).
Definition water_map.h:39
@ WATER_CLASS_SEA
Sea.
Definition water_map.h:40
@ WATER_CLASS_CANAL
Canal.
Definition water_map.h:41
@ WATER_CLASS_INVALID
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition water_map.h:43
@ WATER_CLASS_RIVER
River.
Definition water_map.h:42
bool IsShipDepotTile(Tile t)
Is it a ship depot tile?
Definition water_map.h:232
bool IsCoast(Tile t)
Is it a coast tile?
Definition water_map.h:201
WaterTileType GetWaterTileType(Tile t)
Get the water tile type of a tile.
Definition water_map.h:78
void SetNonFloodingWaterTile(Tile t, bool b)
Set the non-flooding water tile state of a tile.
Definition water_map.h:524
void SetWaterTileType(Tile t, WaterTileType type)
Set the water tile type of a tile.
Definition water_map.h:89
@ WATER_TILE_COAST
Coast.
Definition water_map.h:33
@ WATER_TILE_LOCK
Water lock.
Definition water_map.h:34
@ WATER_TILE_DEPOT
Water Depot.
Definition water_map.h:35
@ WATER_TILE_CLEAR
Plain water.
Definition water_map.h:32
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition water_map.h:112
void MakeCanal(Tile t, Owner o, uint8_t random_bits)
Make a canal tile.
Definition water_map.h:443
uint8_t GetLockPart(Tile t)
Get the part of a lock.
Definition water_map.h:326
TileIndex GetOtherShipDepotTile(Tile t)
Get the other tile of the ship depot.
Definition water_map.h:278
void SetDockingTile(Tile t, bool b)
Set the docking tile state of a tile.
Definition water_map.h:361
bool IsWater(Tile t)
Is it a plain water tile?
Definition water_map.h:147
bool IsLock(Tile t)
Is there a lock on a given water tile?
Definition water_map.h:303
void MakeSea(Tile t)
Make a sea tile.
Definition water_map.h:422
@ LOCK_PART_MIDDLE
Middle part of a lock.
Definition water_map.h:66
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition window.cpp:1818
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3219
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3236
Window functions not directly related to making/drawing windows.
@ WC_COMPANY_INFRASTRUCTURE
Company infrastructure overview; Window numbers:
@ WC_COMPANY_COLOUR
Company colour selection; Window numbers:
@ WC_BUILD_TOOLBAR
Build toolbar; Window numbers:
Definition window_type.h:73
void YapfNotifyTrackLayoutChange(TileIndex tile, Track track)
Use this function to notify YAPF that track layout (or signal configuration) has change.
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:16