OpenTTD Source: src/saveload/waypoint_sl.cpp Source File

OpenTTD Source 15.0-RC2

waypoint_sl.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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "../stdafx.h"
11#include "../waypoint_base.h"
12#include "../debug.h"
13#include "../newgrf_station.h"
14#include "../vehicle_base.h"
15#include "../town.h"
16#include "../newgrf.h"
17#include "../timer/timer_game_calendar.h"
18#include "saveload_internal.h"
19
20#include "table/strings.h"
21
22#include "../safeguards.h"
23
24using OldWaypointID = uint16_t;
25
27 struct OldWaypoint {
28 OldWaypointID index;
29 TileIndex xy;
30 TownID town_index;
31 Town *town;
32 uint16_t town_cn;
33 StringID string_id;
34 std::string name;
35 uint8_t delete_ctr;
36 TimerGameCalendar::Date build_date;
37 uint8_t localidx;
38 uint32_t grfid;
39 const StationSpec *spec;
40 Owner owner;
41
42 StationID new_index;
43};
44
46 static std::vector<OldWaypoint> _old_waypoints;
47
52 static void UpdateWaypointOrder(Order &o)
53{
54 if (!o.IsType(OT_GOTO_WAYPOINT)) return;
55
56 for (OldWaypoint &wp : _old_waypoints) {
57 if (wp.index != o.GetDestination()) continue;
58
59 o.SetDestination(wp.new_index);
60 return;
61 }
62}
63
68 void MoveWaypointsToBaseStations()
69{
70 /* In version 17, ground type is moved from m2 to m4 for depots and
71 * waypoints to make way for storing the index in m2. The custom graphics
72 * id which was stored in m4 is now saved as a grf/id reference in the
73 * waypoint struct. */
74 if (IsSavegameVersionBefore(SLV_17)) {
75 for (OldWaypoint &wp : _old_waypoints) {
76 if (wp.delete_ctr != 0) continue; // The waypoint was deleted
77
78 /* Waypoint indices were not added to the map prior to this. */
79 Tile tile = wp.xy;
80 tile.m2() = wp.index;
81
82 if (HasBit(tile.m3(), 4)) {
83 wp.spec = StationClass::Get(STAT_CLASS_WAYP)->GetSpec(tile.m4() + 1);
84 }
85 }
86 } else {
87 /* As of version 17, we recalculate the custom graphic ID of waypoints
88 * from the GRF ID / station index. */
89 for (OldWaypoint &wp : _old_waypoints) {
90 const auto specs = StationClass::Get(STAT_CLASS_WAYP)->Specs();
91 auto found = std::ranges::find_if(specs, [&wp](const StationSpec *spec) { return spec != nullptr && spec->grf_prop.grfid == wp.grfid && spec->grf_prop.local_id == wp.localidx; });
92 if (found != std::end(specs)) wp.spec = *found;
93 }
94 }
95
96 if (!Waypoint::CanAllocateItem(_old_waypoints.size())) SlError(STR_ERROR_TOO_MANY_STATIONS_LOADING);
97
98 /* All saveload conversions have been done. Create the new waypoints! */
99 for (OldWaypoint &wp : _old_waypoints) {
100 TileIndex t = wp.xy;
101 /* Sometimes waypoint (sign) locations became disconnected from their actual location in
102 * the map array. If this is the case, try to locate the actual location in the map array */
103 if (!IsTileType(t, MP_RAILWAY) || GetRailTileType(t) != RailTileType{2} /* RAIL_TILE_WAYPOINT */ || Tile(t).m2() != wp.index) {
104 Debug(sl, 0, "Found waypoint tile {} with invalid position", t);
105 t = INVALID_TILE;
106 for (auto tile : Map::Iterate()) {
107 if (IsTileType(tile, MP_RAILWAY) && GetRailTileType(tile) == RailTileType{2} /* RAIL_TILE_WAYPOINT */ && tile.m2() == wp.index) {
108 t = TileIndex(tile);
109 Debug(sl, 0, "Found actual waypoint position at {}", TileIndex(tile));
110 break;
111 }
112 }
113 }
114 if (t == INVALID_TILE) {
115 SlErrorCorrupt("Waypoint with invalid tile");
116 }
117
118 Waypoint *new_wp = new Waypoint(t);
119 new_wp->town = wp.town;
120 new_wp->town_cn = wp.town_cn;
121 new_wp->name = wp.name;
122 new_wp->delete_ctr = 0; // Just reset delete counter for once.
123 new_wp->build_date = wp.build_date;
124 new_wp->owner = wp.owner;
125 new_wp->string_id = STR_SV_STNAME_WAYPOINT;
126
127 /* The tile might've been reserved! */
128 Tile tile(t);
129 bool reserved = !IsSavegameVersionBefore(SLV_100) && HasBit(tile.m5(), 4);
130
131 /* The tile really has our waypoint, so reassign the map array */
132 MakeRailWaypoint(tile, GetTileOwner(tile), new_wp->index, (Axis)GB(tile.m5(), 0, 1), 0, GetRailType(tile));
133 new_wp->facilities.Set(StationFacility::Train);
134 new_wp->owner = GetTileOwner(tile);
135
136 SetRailStationReservation(tile, reserved);
137
138 if (wp.spec != nullptr) {
139 auto specindex = AllocateSpecToStation(wp.spec, new_wp);
140 if (specindex.has_value()) AssignSpecToStation(wp.spec, new_wp, *specindex);
141 SetCustomStationSpecIndex(tile, specindex.value_or(0));
142 }
143 new_wp->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
144
145 wp.new_index = new_wp->index;
146 }
147
148 /* Update the orders of vehicles */
149 for (OrderList *ol : OrderList::Iterate()) {
150 if (ol->GetFirstSharedVehicle()->type != VEH_TRAIN) continue;
151
152 for (Order &o : ol->GetOrders()) UpdateWaypointOrder(o);
153 }
154
155 for (Vehicle *v : Vehicle::Iterate()) {
156 if (v->type != VEH_TRAIN) continue;
157
158 UpdateWaypointOrder(v->current_order);
159 }
160
161 ResetOldWaypoints();
162}
163
164void ResetOldWaypoints()
165{
166 _old_waypoints.clear();
167 _old_waypoints.shrink_to_fit();
168}
169
170static const SaveLoad _old_waypoint_desc[] = {
171 SLE_CONDVAR(OldWaypoint, xy, SLE_FILE_U16 | SLE_VAR_U32, SL_MIN_VERSION, SLV_6),
172 SLE_CONDVAR(OldWaypoint, xy, SLE_UINT32, SLV_6, SL_MAX_VERSION),
173 SLE_CONDVAR(OldWaypoint, town_index, SLE_UINT16, SLV_12, SLV_122),
174 SLE_CONDREF(OldWaypoint, town, REF_TOWN, SLV_122, SL_MAX_VERSION),
175 SLE_CONDVAR(OldWaypoint, town_cn, SLE_FILE_U8 | SLE_VAR_U16, SLV_12, SLV_89),
176 SLE_CONDVAR(OldWaypoint, town_cn, SLE_UINT16, SLV_89, SL_MAX_VERSION),
177 SLE_CONDVAR(OldWaypoint, string_id, SLE_STRINGID, SL_MIN_VERSION, SLV_84),
178 SLE_CONDSSTR(OldWaypoint, name, SLE_STR, SLV_84, SL_MAX_VERSION),
179 SLE_VAR(OldWaypoint, delete_ctr, SLE_UINT8),
180
181 SLE_CONDVAR(OldWaypoint, build_date, SLE_FILE_U16 | SLE_VAR_I32, SLV_3, SLV_31),
182 SLE_CONDVAR(OldWaypoint, build_date, SLE_INT32, SLV_31, SL_MAX_VERSION),
183 SLE_CONDVAR(OldWaypoint, localidx, SLE_UINT8, SLV_3, SL_MAX_VERSION),
184 SLE_CONDVAR(OldWaypoint, grfid, SLE_UINT32, SLV_17, SL_MAX_VERSION),
185 SLE_CONDVAR(OldWaypoint, owner, SLE_UINT8, SLV_101, SL_MAX_VERSION),
186};
187
188 struct CHKPChunkHandler : ChunkHandler {
189 CHKPChunkHandler() : ChunkHandler('CHKP', CH_READONLY) {}
190
191 void Load() const override
192 {
193 /* Precaution for when loading failed and it didn't get cleared */
194 ResetOldWaypoints();
195
196 int index;
197
198 while ((index = SlIterateArray()) != -1) {
199 OldWaypoint *wp = &_old_waypoints.emplace_back();
200
201 wp->index = static_cast<OldWaypointID>(index);
202 SlObject(wp, _old_waypoint_desc);
203 }
204 }
205
206 void FixPointers() const override
207 {
208 for (OldWaypoint &wp : _old_waypoints) {
209 SlObject(&wp, _old_waypoint_desc);
210
211 if (IsSavegameVersionBefore(SLV_12)) {
212 wp.town_cn = (wp.string_id & 0xC000) == 0xC000 ? (wp.string_id >> 8) & 0x3F : 0;
213 wp.town = ClosestTownFromTile(wp.xy, UINT_MAX);
214 } else if (IsSavegameVersionBefore(SLV_122)) {
215 /* Only for versions 12 .. 122 */
216 if (!Town::IsValidID(wp.town_index)) {
217 /* Upon a corrupted waypoint we'll likely get here. The next step will be to
218 * loop over all Ptrs procs to nullptr the pointers. However, we don't know
219 * whether we're in the nullptr or "normal" Ptrs proc. So just clear the list
220 * of old waypoints we constructed and then this waypoint (and the other
221 * possibly corrupt ones) will not be queried in the nullptr Ptrs proc run. */
222 _old_waypoints.clear();
223 SlErrorCorrupt("Referencing invalid Town");
224 }
225 wp.town = Town::Get(wp.town_index);
226 }
227 if (IsSavegameVersionBefore(SLV_84)) {
228 wp.name = CopyFromOldName(wp.string_id);
229 }
230 }
231 }
232};
233
234static const CHKPChunkHandler CHKP;
235static const ChunkHandlerRef waypoint_chunk_handlers[] = {
236 CHKP,
237};
238
239extern const ChunkHandlerTable _waypoint_chunk_handlers(waypoint_chunk_handlers);
GB
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition bitmath_func.hpp:32
HasBit
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition bitmath_func.hpp:103
BaseBitSet::Set
constexpr Timpl & Set()
Set all bits.
Definition base_bitset_type.hpp:40
NewGRFClass::Specs
std::span< Tspec *const > Specs() const
Get read-only span of specs of this class.
Definition newgrf_class.h:58
NewGRFClass::Get
static NewGRFClass * Get(Tindex class_index)
Get a particular class.
Definition newgrf_class_func.h:82
NewGRFClass::GetSpec
const Tspec * GetSpec(uint index) const
Get a spec from the class at a given index.
Definition newgrf_class_func.h:114
Tile
Wrapper class to abstract away the way the tiles are stored.
Definition map_func.h:25
Tile::m5
uint8_t & m5()
General purpose.
Definition map_func.h:161
Tile::m4
uint8_t & m4()
General purpose.
Definition map_func.h:149
Tile::m3
uint8_t & m3()
General purpose.
Definition map_func.h:137
Tile::m2
uint16_t & m2()
Primarily used for indices to towns, industries and stations.
Definition map_func.h:125
Debug
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
Axis
Axis
Allow incrementing of DiagDirDiff variables.
Definition direction_type.h:123
AssignSpecToStation
void AssignSpecToStation(const StationSpec *spec, BaseStation *st, uint8_t specindex)
Assign a previously allocated StationSpec specindex to a Station.
Definition newgrf_station.cpp:740
AllocateSpecToStation
std::optional< uint8_t > AllocateSpecToStation(const StationSpec *spec, BaseStation *st)
Allocate a StationSpec to a Station.
Definition newgrf_station.cpp:705
STAT_CLASS_WAYP
@ STAT_CLASS_WAYP
Waypoint class.
Definition newgrf_station.h:106
GetRailTileType
static RailTileType GetRailTileType(Tile t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
Definition rail_map.h:36
GetRailType
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition rail_map.h:115
RailTileType
RailTileType
Different types of Rail-related tiles.
Definition rail_map.h:23
SlError
void SlError(StringID string, const std::string &extra_msg)
Error handler.
Definition saveload.cpp:339
SlIterateArray
int SlIterateArray()
Iterate through the elements of an array and read the whole thing.
Definition saveload.cpp:677
SlErrorCorrupt
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition saveload.cpp:369
SlObject
void SlObject(void *object, const SaveLoadTable &slt)
Main SaveLoad function.
Definition saveload.cpp:1846
ChunkHandlerRef
std::reference_wrapper< const ChunkHandler > ChunkHandlerRef
A reference to ChunkHandler.
Definition saveload.h:524
REF_TOWN
@ REF_TOWN
Load/save a reference to a town.
Definition saveload.h:618
ChunkHandlerTable
std::span< const ChunkHandlerRef > ChunkHandlerTable
A table of ChunkHandler entries.
Definition saveload.h:527
SLE_CONDSSTR
#define SLE_CONDSSTR(base, variable, type, from, to)
Storage of a std::string in some savegame versions.
Definition saveload.h:948
SLE_CONDVAR
#define SLE_CONDVAR(base, variable, type, from, to)
Storage of a variable in some savegame versions.
Definition saveload.h:883
IsSavegameVersionBefore
bool IsSavegameVersionBefore(SaveLoadVersion major, uint8_t minor=0)
Checks whether the savegame is below major.
Definition saveload.h:1278
SLV_89
@ SLV_89
89 12160
Definition saveload.h:149
SLV_84
@ SLV_84
84 11822
Definition saveload.h:143
SLV_17
@ SLV_17
17.0 3212 17.1 3218
Definition saveload.h:62
SLV_100
@ SLV_100
100 13952
Definition saveload.h:163
SLV_6
@ SLV_6
6.0 1721 6.1 1768
Definition saveload.h:46
SLV_122
@ SLV_122
122 16855
Definition saveload.h:189
SLV_12
@ SLV_12
12.1 2046
Definition saveload.h:55
SL_MAX_VERSION
@ SL_MAX_VERSION
Highest possible saveload version.
Definition saveload.h:416
SL_MIN_VERSION
@ SL_MIN_VERSION
First savegame version.
Definition saveload.h:31
SLV_3
@ SLV_3
3.x lost
Definition saveload.h:36
SLV_101
@ SLV_101
101 14233
Definition saveload.h:164
SLV_31
@ SLV_31
31 5999
Definition saveload.h:80
SLE_CONDREF
#define SLE_CONDREF(base, variable, type, from, to)
Storage of a reference in some savegame versions.
Definition saveload.h:904
CH_READONLY
@ CH_READONLY
Chunk is never saved.
Definition saveload.h:474
SLE_VAR
#define SLE_VAR(base, variable, type)
Storage of a variable in every version of a savegame.
Definition saveload.h:1017
saveload_internal.h
Declaration of functions used in more save/load files.
CopyFromOldName
std::string CopyFromOldName(StringID id)
Copy and convert old custom names to UTF-8.
Definition strings_sl.cpp:59
SetCustomStationSpecIndex
void SetCustomStationSpecIndex(Tile t, uint8_t specindex)
Set the custom station spec for this tile.
Definition station_map.h:630
SetRailStationReservation
void SetRailStationReservation(Tile t, bool b)
Set the reservation state of the rail station.
Definition station_map.h:571
MakeRailWaypoint
void MakeRailWaypoint(Tile t, Owner o, StationID sid, Axis a, uint8_t section, RailType rt)
Make the given tile a rail waypoint tile.
Definition station_map.h:759
StationFacility::Train
@ Train
Station with train station.
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition strings_type.h:19
BaseStation::string_id
StringID string_id
Default name (town area) of station.
Definition base_station_base.h:64
BaseStation::facilities
StationFacilities facilities
The facilities that this station has.
Definition base_station_base.h:69
BaseStation::owner
Owner owner
The owner of this station.
Definition base_station_base.h:68
BaseStation::delete_ctr
uint8_t delete_ctr
Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is ...
Definition base_station_base.h:61
BaseStation::rect
StationRect rect
NOSAVE: Station spread out rectangle maintained by StationRect::xxx() functions.
Definition base_station_base.h:84
BaseStation::town
Town * town
The town this station is associated with.
Definition base_station_base.h:67
BaseStation::build_date
TimerGameCalendar::Date build_date
Date of construction.
Definition base_station_base.h:74
BaseStation::name
std::string name
Custom name.
Definition base_station_base.h:63
CHKPChunkHandler
Definition waypoint_sl.cpp:188
CHKPChunkHandler::Load
void Load() const override
Load the chunk.
Definition waypoint_sl.cpp:191
CHKPChunkHandler::FixPointers
void FixPointers() const override
Fix the pointers.
Definition waypoint_sl.cpp:206
ChunkHandler
Handlers and description of chunk.
Definition saveload.h:478
GRFFilePropsBase::local_id
uint16_t local_id
id defined by the grf file for this entity
Definition newgrf_commons.h:316
GRFFilePropsBase::grfid
uint32_t grfid
grfid that introduced this entity.
Definition newgrf_commons.h:317
Map::Iterate
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
Definition map_func.h:375
OldWaypoint
Helper structure to convert from the old waypoint system.
Definition waypoint_sl.cpp:27
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition order_base.h:274
Order
Definition order_base.h:33
Order::GetDestination
DestinationID GetDestination() const
Gets the destination of this order.
Definition order_base.h:99
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
Order::SetDestination
void SetDestination(DestinationID destination)
Sets the destination of this order.
Definition order_base.h:106
PoolID< uint16_t, struct TownIDTag, 64000, 0xFFFF >
Pool::PoolItem<&_orderlist_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition pool_type.hpp:436
Pool::PoolItem<&_town_pool >::Get
static Titem * Get(auto index)
Returns Titem with given index.
Definition pool_type.hpp:387
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition pool_type.hpp:286
Pool::PoolItem<&_station_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition pool_type.hpp:357
Pool::PoolItem<&_town_pool >::IsValidID
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition pool_type.hpp:376
SaveLoad
SaveLoad type struct.
Definition saveload.h:732
StationSpec
Station specification.
Definition newgrf_station.h:123
StationSpec::grf_prop
CargoGRFFileProps grf_prop
Link to NewGRF.
Definition newgrf_station.h:130
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
Town
Town data structure.
Definition town.h:63
Vehicle
Vehicle data structure.
Definition vehicle_base.h:205
Waypoint
Representation of a waypoint.
Definition waypoint_base.h:23
Waypoint::town_cn
uint16_t town_cn
The N-1th waypoint for this town (consecutive number)
Definition waypoint_base.h:24
IsTileType
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
GetTileOwner
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
INVALID_TILE
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:95
TileIndex
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_RAILWAY
@ MP_RAILWAY
A railway.
Definition tile_type.h:49
ClosestTownFromTile
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition town_cmd.cpp:3952
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition vehicle_type.h:25
UpdateWaypointOrder
static void UpdateWaypointOrder(Order &o)
Update the waypoint orders to get the new waypoint ID.
Definition waypoint_sl.cpp:52
_old_waypoints
static std::vector< OldWaypoint > _old_waypoints
Temporary array with old waypoints.
Definition waypoint_sl.cpp:46
MoveWaypointsToBaseStations
void MoveWaypointsToBaseStations()
Perform all steps to upgrade from the old waypoints to the new version that uses station.
Definition waypoint_sl.cpp:68