OpenTTD Source 20261129-master-g72a8bdc861
station_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
9
10#include "../stdafx.h"
11
12#include "saveload.h"
14
15#include "../station_base.h"
16#include "../station_func.h"
17#include "../waypoint_base.h"
18#include "../roadstop_base.h"
19#include "../vehicle_base.h"
20#include "../newgrf_station.h"
21#include "../newgrf_roadstop.h"
22#include "../town.h"
24
25#include "table/strings.h"
26
27#include "../safeguards.h"
28
34{
35 if (!o.IsType(OT_GOTO_STATION)) return;
36
37 const Station *st = Station::Get(o.GetDestination().ToStationID());
38 if (!st->had_vehicle_of_type.Test(StationVehicleType::Waypoint)) return;
39
40 o.MakeGoToWaypoint(o.GetDestination().ToStationID());
41}
42
48{
49 /* Buoy orders become waypoint orders */
50 for (OrderList *ol : OrderList::Iterate()) {
51 VehicleType vt = ol->GetFirstSharedVehicle()->type;
52 if (vt != VehicleType::Ship && vt != VehicleType::Train) continue;
53
54 for (Order &o : ol->GetOrders()) UpdateWaypointOrder(o);
55 }
56
57 for (Vehicle *v : Vehicle::Iterate()) {
58 VehicleType vt = v->type;
59 if (vt != VehicleType::Ship && vt != VehicleType::Train) continue;
60
61 UpdateWaypointOrder(v->current_order);
62 }
63
64 /* Now make the stations waypoints */
65 for (Station *st : Station::Iterate()) {
66 if (!st->had_vehicle_of_type.Test(StationVehicleType::Waypoint)) continue;
67
68 StationID index = st->index;
69 TileIndex xy = st->xy;
70 Town *town = st->town;
71 StringID string_id = st->string_id;
72 std::string name = st->name;
73 TimerGameCalendar::Date build_date = st->build_date;
74 /* TTDPatch could use "buoys with rail station" for rail waypoints */
75 bool train = !st->train_station.IsEmpty();
76 TileArea train_st = st->train_station;
77
78 /* Delete the station, so we can make it a real waypoint. */
79 delete st;
80
81 /* Stations and waypoints are in the same pool, so if a station
82 * is deleted there must be place for a Waypoint. */
84 Waypoint *wp = Waypoint::CreateAtIndex(index, xy);
85 wp->town = town;
86 wp->string_id = train ? STR_SV_STNAME_WAYPOINT : STR_SV_STNAME_BUOY;
87 wp->name = std::move(name);
88 wp->delete_ctr = 0; // Just reset delete counter for once.
89 wp->build_date = build_date;
90 wp->owner = train ? GetTileOwner(xy) : OWNER_NONE;
91
92 if (IsInsideBS(string_id, STR_SV_STNAME_BUOY, 9)) wp->town_cn = (string_id - STR_SV_STNAME_BUOY).base();
93
94 if (train) {
95 /* When we make a rail waypoint of the station, convert the map as well. */
96 for (TileIndex t : train_st) {
97 Tile tile(t);
98 if (!IsTileType(tile, TileType::Station) || GetStationIndex(tile) != index) continue;
99
101 wp->spread.Add(t);
102 }
103
104 wp->train_station = train_st;
106 } else if (IsBuoyTile(xy) && GetStationIndex(xy) == index) {
107 wp->spread.Add(xy);
109 }
110 }
111}
112
113void AfterLoadStations()
114{
115 /* Update the speclists of all stations to point to the currently loaded custom stations. */
116 for (BaseStation *st : BaseStation::Iterate()) {
117 for (auto &sm : GetStationSpecList<StationSpec>(st)) {
118 if (sm.grfid.Empty()) continue;
119 sm.spec = StationClass::GetByGrf(sm.grfid, sm.localidx);
120 }
121 for (auto &sm : GetStationSpecList<RoadStopSpec>(st)) {
122 if (sm.grfid.Empty()) continue;
123 sm.spec = RoadStopClass::GetByGrf(sm.grfid, sm.localidx);
124 }
125
126 if (Station::IsExpected(st)) {
127 Station *sta = Station::From(st);
128 for (const RoadStop *rs = sta->bus_stops; rs != nullptr; rs = rs->next) sta->bus_station.Add(rs->xy);
129 for (const RoadStop *rs = sta->truck_stops; rs != nullptr; rs = rs->next) sta->truck_station.Add(rs->xy);
130 }
131
134 }
135
136 /* Station blocked, wires and pylon flags need to be stored in the map. This is effectively cached data, so no
137 * version check is necessary. */
138 for (const auto t : Map::Iterate()) {
139 if (HasStationTileRail(t)) SetRailStationTileFlags(t, GetStationSpec(t));
140 }
141}
142
147{
148 /* First construct the drive through entries */
149 for (RoadStop *rs : RoadStop::Iterate()) {
150 if (IsDriveThroughStopTile(rs->xy)) rs->MakeDriveThrough();
151 }
152 /* And then rebuild the data in those entries */
153 for (RoadStop *rs : RoadStop::Iterate()) {
154 if (!rs->status.Test(RoadStop::RoadStopStatusFlag::BaseEntry)) continue;
155
156 rs->GetEntry(DiagDirection::NE).Rebuild(rs);
157 rs->GetEntry(DiagDirection::NW).Rebuild(rs);
158 }
159}
160
161static const SaveLoad _roadstop_desc[] = {
165};
166
167static uint16_t _waiting_acceptance;
168static uint32_t _old_num_flows;
169static uint16_t _cargo_source;
170static uint32_t _cargo_source_xy;
171static uint8_t _cargo_periods;
172static Money _cargo_feeder_share;
173
174std::list<CargoPacket *> _packets;
175uint32_t _old_num_dests;
176
178 StationID source;
179 StationID via;
180 uint32_t share;
181 bool restricted;
182};
183
184typedef std::pair<const StationID, std::list<CargoPacket *> > StationCargoPair;
185
186static OldPersistentStorage _old_st_persistent_storage;
187
193static void SwapPackets(GoodsEntry *ge)
194{
195 StationCargoPacketMap &ge_packets = const_cast<StationCargoPacketMap &>(*ge->GetOrCreateData().cargo.Packets());
196
197 if (_packets.empty()) {
198 std::map<StationID, std::list<CargoPacket *> >::iterator it(ge_packets.find(StationID::Invalid()));
199 if (it == ge_packets.end()) {
200 return;
201 } else {
202 it->second.swap(_packets);
203 }
204 } else {
205 assert(ge_packets[StationID::Invalid()].empty());
206 ge_packets[StationID::Invalid()].swap(_packets);
207 }
208}
209
210template <typename T>
211class SlStationSpecList : public VectorSaveLoadHandler<SlStationSpecList<T>, BaseStation, SpecMapping<T>> {
212public:
213 static inline const SaveLoad description[] = {
217 };
218 static inline const SaveLoadCompatTable compat_description = _station_spec_list_sl_compat;
219
220 static inline uint8_t last_num_specs;
221
222 std::vector<SpecMapping<T>> &GetVector(BaseStation *bst) const override { return GetStationSpecList<T>(bst); }
223
228};
229
230/* Instantiate SlStationSpecList classes. */
231template class SlStationSpecList<StationSpec>;
233
235public:
236 using StationWaitingTriggersPair = std::pair<const TileIndex, StationRandomTriggers>;
237
238 static inline const SaveLoad description[] = {
239 SaveLoad::Variable<VarFileType::U32>("first", SLE_OBJECT_ADDRESS(StationWaitingTriggersPair, first)),
240 SaveLoad::Variable<VarFileType::U8>("second", SLE_OBJECT_ADDRESS(StationWaitingTriggersPair, second)),
241 };
242 static inline const SaveLoadCompatTable compat_description = _station_cargo_sl_compat;
243
244 void Save(BaseStation *st) const override
245 {
246 SlSetStructListLength(st->tile_waiting_random_triggers.size());
247 for (const auto &pair : st->tile_waiting_random_triggers) {
248 SlObject(const_cast<StationWaitingTriggersPair *>(&pair), this->GetDescription());
249 }
250 }
251
252 void Load(BaseStation *st) const override
253 {
254 size_t num = SlGetStructListLength(UINT32_MAX);
255 if (num == 0) return;
256
257 StationWaitingTriggersPair pair;
258 for (uint j = 0; j < num; ++j) {
259 SlObject(&pair, this->GetLoadDescription());
260 st->tile_waiting_random_triggers.emplace(pair.first, pair.second);
261 }
262 }
263};
264
266public:
267 static inline const SaveLoad description[] = {
268 SaveLoad::Variable<VarFileType::U16>("first", SLE_OBJECT_ADDRESS(StationCargoPair, first)),
269 SaveLoad::ReferenceList<SLRefType::CargoPacket>("second", SLE_OBJECT_ADDRESS(StationCargoPair, second)),
270 };
271 static inline const SaveLoadCompatTable compat_description = _station_cargo_sl_compat;
272
273 void Save(GoodsEntry *ge) const override
274 {
275 if (!ge->HasData()) {
277 return;
278 }
279
280 const auto *packets = ge->GetData().cargo.Packets();
281 SlSetStructListLength(packets->MapSize());
282 for (StationCargoPacketMap::ConstMapIterator it(packets->begin()); it != packets->end(); ++it) {
283 SlObject(const_cast<StationCargoPacketMap::value_type *>(&(*it)), this->GetDescription());
284 }
285 }
286
287 void Load(GoodsEntry *ge) const override
288 {
289 size_t num_dests = IsSavegameVersionBefore(SaveLoadVersion::SaveloadListLength) ? _old_num_dests : SlGetStructListLength(UINT32_MAX);
290 if (num_dests == 0) return;
291
293 StationCargoPair pair;
294 for (uint j = 0; j < num_dests; ++j) {
295 SlObject(&pair, this->GetLoadDescription());
296 const_cast<StationCargoPacketMap &>(*(data.cargo.Packets()))[pair.first].swap(pair.second);
297 assert(pair.second.empty());
298 }
299 }
300
301 void FixPointers(GoodsEntry *ge) const override
302 {
303 if (!ge->HasData()) return;
304
305 for (StationCargoPacketMap::ConstMapIterator it = ge->GetData().cargo.Packets()->begin(); it != ge->GetData().cargo.Packets()->end(); ++it) {
306 SlObject(const_cast<StationCargoPair *>(&(*it)), this->GetDescription());
307 }
308 }
309};
310
312public:
313 static inline const SaveLoad description[] = {
318 };
319 static inline const SaveLoadCompatTable compat_description = _station_flow_sl_compat;
320
321 void Save(GoodsEntry *ge) const override
322 {
323 if (!ge->HasData()) {
325 return;
326 }
327
328 size_t num_flows = 0;
329 for (const auto &it : ge->GetData().flows) {
330 num_flows += it.second.GetShares()->size();
331 }
332 SlSetStructListLength(num_flows);
333
334 for (const auto &outer_it : ge->GetData().flows) {
335 const FlowStat::SharesMap *shares = outer_it.second.GetShares();
336 uint32_t sum_shares = 0;
337 FlowSaveLoad flow{};
338 flow.source = outer_it.first;
339 for (auto &inner_it : *shares) {
340 flow.via = inner_it.second;
341 flow.share = inner_it.first - sum_shares;
342 flow.restricted = inner_it.first > outer_it.second.GetUnrestricted();
343 sum_shares = inner_it.first;
344 assert(flow.share > 0);
345 SlObject(&flow, this->GetDescription());
346 }
347 }
348 }
349
350 void Load(GoodsEntry *ge) const override
351 {
352 size_t num_flows = IsSavegameVersionBefore(SaveLoadVersion::SaveloadListLength) ? _old_num_flows : SlGetStructListLength(UINT32_MAX);
353 if (num_flows == 0) return;
354
356 FlowSaveLoad flow{};
357 FlowStat *fs = nullptr;
358 StationID prev_source = StationID::Invalid();
359 for (uint32_t j = 0; j < num_flows; ++j) {
360 SlObject(&flow, this->GetLoadDescription());
361 if (fs == nullptr || prev_source != flow.source) {
362 fs = &(data.flows.emplace(flow.source, FlowStat(flow.via, flow.share, flow.restricted))).first->second;
363 } else {
364 fs->AppendShare(flow.via, flow.share, flow.restricted);
365 }
366 prev_source = flow.source;
367 }
368 }
369};
370
373public:
382
383 static inline const SaveLoadCompatTable compat_description = {};
384
385 void Save(GoodsEntry::CargoHistoryData *chd) const override
386 {
387 auto &history = chd->history;
388 SlSetStructListLength(history.size());
389 for (auto &h : history) {
390 SlObject(&h, this->GetDescription());
391 }
392 }
393
394 void Load(GoodsEntry::CargoHistoryData *chd) const override
395 {
396 size_t len = SlGetStructListLength(UINT32_MAX);
397
398 auto &history = chd->history;
399 for (auto &h : history) {
400 if (--len > history.size()) break; // unsigned so wraps after hitting zero.
401 SlObject(&h, this->GetDescription());
402 }
403 }
404};
405
408public:
417
419
420 void Save(GoodsEntry *ge) const override
421 {
422 /* Cargo history data isn't really a list, however because it's optional data we use the list length to
423 * record whether the data is present or not. */
424
425 if (!ge->HasHistory()) {
427 return;
428 }
429
431 SlObject(&ge->GetHistory(), this->GetDescription());
432 }
433
434 void Load(GoodsEntry *ge) const override
435 {
436 if (SlGetStructListLength(1) != 1) return;
437 SlObject(&ge->GetOrCreateHistory(), this->GetLoadDescription());
438 }
439};
440
442public:
443 static inline uint cargo_reserved_count;
444
445 static inline const SaveLoad description[] = {
448 SaveLoad::Variable<VarFileType::U8>("time_since_pickup", SLE_OBJECT_ADDRESS(GoodsEntry, time_since_pickup)),
461 SaveLoad::Variable<VarFileType::U32>("cargo.reserved_count", SLE_GLOBAL_ADDRESS(SlStationGoods::cargo_reserved_count), SaveLoadVersion::CargoReservation),
468 SaveLoad::Variable<VarFileType::U16>("accumulated_rating", SLE_OBJECT_ADDRESS(GoodsEntry, accumulated_rating)),
470 };
471
472 static inline const SaveLoadCompatTable compat_description = _station_goods_sl_compat;
473
478 size_t GetNumCargo() const
479 {
483 /* Read from the savegame how long the list is. */
485 }
486
487 void Save(BaseStation *bst) const override
488 {
489 Station *st = Station::From(bst);
490
492
493 for (GoodsEntry &ge : st->goods) {
494 SlStationGoods::cargo_reserved_count = ge.HasData() ? ge.GetData().cargo.reserved_count : 0;
495 SlObject(&ge, this->GetDescription());
496 }
497 }
498
499 void Load(BaseStation *bst) const override
500 {
501 Station *st = Station::From(bst);
502
503 /* Before savegame version 161, persistent storages were not stored in a pool. */
505 /* Store the old persistent storage. The GRFID will be added later. */
508 std::copy(std::begin(_old_st_persistent_storage.storage), std::end(_old_st_persistent_storage.storage), std::begin(st->airport.psa->storage));
509 }
510
511 auto end = std::next(std::begin(st->goods), std::min(this->GetNumCargo(), std::size(st->goods)));
512 for (auto it = std::begin(st->goods); it != end; ++it) {
513 GoodsEntry &ge = *it;
514 SlObject(&ge, this->GetLoadDescription());
515 if (!IsSavegameVersionBefore(SaveLoadVersion::CargoReservation) && SlStationGoods::cargo_reserved_count != 0) {
516 ge.GetOrCreateData().cargo.reserved_count = SlStationGoods::cargo_reserved_count;
517 }
519 SwapPackets(&ge);
520 }
522 ge.status.Set(GoodsEntry::State::Acceptance, HasBit(_waiting_acceptance, 15));
523 if (GB(_waiting_acceptance, 0, 12) != 0) {
524 /* In old versions, enroute_from used 0xFF as StationID::Invalid() */
525 StationID source = (IsSavegameVersionBefore(SaveLoadVersion::LargerCargoSource) && _cargo_source == 0xFF) ? StationID::Invalid() : static_cast<StationID>(_cargo_source);
526
527 /* Make sure we can allocate the CargoPacket. This is safe
528 * as there can only be ~64k stations and 32 cargoes in these
529 * savegame versions. As the CargoPacketPool has more than
530 * 16 million entries; it fits by an order of magnitude. */
532
533 /* Don't construct the packet with station here, because that'll fail with old savegames */
534 CargoPacket *cp = CargoPacket::Create(GB(_waiting_acceptance, 0, 12), _cargo_periods, source, TileIndex{_cargo_source_xy}, _cargo_feeder_share);
535 ge.GetOrCreateData().cargo.Append(cp, StationID::Invalid());
537 }
538 }
539 }
540 }
541
542 void FixPointers(BaseStation *bst) const override
543 {
544 Station *st = Station::From(bst);
545
547 auto end = std::next(std::begin(st->goods), std::min(num_cargo, std::size(st->goods)));
548 for (auto it = std::begin(st->goods); it != end; ++it) {
549 GoodsEntry &ge = *it;
551 SwapPackets(&ge); // We have to swap back again to be in the format pre-183 expects.
552 SlObject(&ge, this->GetDescription());
553 SwapPackets(&ge);
554 } else {
555 SlObject(&ge, this->GetDescription());
556 }
557 }
558 }
559};
560
561static const SaveLoad _old_station_desc[] = {
569 SaveLoad::Variable<VarFileType::U8>("train_station.w", SLE_OBJECT_ADDRESS(Station, train_station.w)),
571
577
578 SaveLoad::Variable<VarFileType::U8>("time_since_load", SLE_OBJECT_ADDRESS(Station, time_since_load)),
579 SaveLoad::Variable<VarFileType::U8>("time_since_unload", SLE_OBJECT_ADDRESS(Station, time_since_unload)),
583 SaveLoad::Variable<VarFileType::U8>("airport.type", SLE_OBJECT_ADDRESS(Station, airport.type)),
587
589
592
595
596 /* Used by newstations for graphic variations */
600
602
605};
606
607struct STNSChunkHandler : ChunkHandler {
608 STNSChunkHandler() : ChunkHandler("STNS", ChunkType::ReadOnly) {}
609
610 void Load() const override
611 {
612 const std::vector<SaveLoad> slt = SlCompatTableHeader(_old_station_desc, _old_station_sl_compat);
613
614 _cargo_source_xy = 0;
615 _cargo_periods = 0;
616 _cargo_feeder_share = 0;
617
618 int index;
619 while ((index = SlIterateArray()) != -1) {
620 Station *st = Station::CreateAtIndex(StationID(index));
621
622 _waiting_acceptance = 0;
623 SlObject(st, slt);
624 }
625 }
626
627 void FixPointers() const override
628 {
629 /* From SaveLoadVersion::UnifyWaypointAndStation we store stations in STNN; before that in STNS. So do not
630 * fix pointers when the version is SaveLoadVersion::UnifyWaypointAndStation or up, as that would fix
631 * pointers twice: once in STNN chunk and once here. */
633
634 for (Station *st : Station::Iterate()) {
635 SlObject(st, _old_station_desc);
636 }
637 }
638};
639
641public:
642 static inline const SaveLoad description[] = {
645 SaveLoad::Variable<VarFileType::U8>("animation_frame", SLE_OBJECT_ADDRESS(RoadStopTileData, animation_frame)),
646 };
647 static inline const SaveLoadCompatTable compat_description = {};
648
649 std::vector<RoadStopTileData> &GetVector(BaseStation *bst) const override { return bst->custom_roadstop_tile_data; }
650};
651
657public:
658 static inline const SaveLoad description[] = {
667
668 /* Used by newstations for graphic variations */
670 SaveLoad::Variable<VarFileType::U8>("waiting_triggers", SLE_OBJECT_ADDRESS(BaseStation, waiting_random_triggers)),
671 SaveLoad::StructList<SlStationWaitingTriggers>("tile_waiting_triggers"),
673 };
674 static inline const SaveLoadCompatTable compat_description = _station_base_sl_compat;
675
676 void Save(BaseStation *bst) const override
677 {
678 SlObject(bst, this->GetDescription());
679 }
680
681 void Load(BaseStation *bst) const override
682 {
683 SlObject(bst, this->GetLoadDescription());
684 }
685
686 void FixPointers(BaseStation *bst) const override
687 {
688 SlObject(bst, this->GetDescription());
689 }
690};
691
696public:
697 static inline const SaveLoad description[] = {
699 SaveLoad::Variable<VarFileType::U32>("train_station.tile", SLE_OBJECT_ADDRESS(Station, train_station.tile)),
700 SaveLoad::Variable<VarFileType::U8>("train_station.w", SLE_OBJECT_ADDRESS(Station, train_station.w)),
701 SaveLoad::Variable<VarFileType::U8>("train_station.h", SLE_OBJECT_ADDRESS(Station, train_station.h)),
702
714 SaveLoad::Variable<VarFileType::U8>("airport.type", SLE_OBJECT_ADDRESS(Station, airport.type)),
716 SaveLoad::Variable<VarFileType::U64>("airport.flags", SLE_OBJECT_ADDRESS(Station, airport.blocks)),
720
722
723 SaveLoad::Variable<VarFileType::U8>("time_since_load", SLE_OBJECT_ADDRESS(Station, time_since_load)),
724 SaveLoad::Variable<VarFileType::U8>("time_since_unload", SLE_OBJECT_ADDRESS(Station, time_since_unload)),
725 SaveLoad::Variable<VarFileType::U8>("last_vehicle_type", SLE_OBJECT_ADDRESS(Station, last_vehicle_type)),
726 SaveLoad::Variable<VarFileType::U8>("had_vehicle_of_type", SLE_OBJECT_ADDRESS(Station, had_vehicle_of_type)),
727 SaveLoad::ReferenceList<SLRefType::Vehicle>("loading_vehicles", SLE_OBJECT_ADDRESS(Station, loading_vehicles)),
732 SaveLoad::Variable<VarFileType::U64>("valid_cargo_history", SLE_OBJECT_ADDRESS(Station, valid_cargo_history)),
733 };
734 static inline const SaveLoadCompatTable compat_description = _station_normal_sl_compat;
735
736 void Save(BaseStation *bst) const override
737 {
738 if (bst->facilities.Test(StationFacility::Waypoint)) return;
739 SlObject(bst, this->GetDescription());
740 }
741
742 void Load(BaseStation *bst) const override
743 {
744 if (bst->facilities.Test(StationFacility::Waypoint)) return;
745 SlObject(bst, this->GetLoadDescription());
746 }
747
748 void FixPointers(BaseStation *bst) const override
749 {
750 if (bst->facilities.Test(StationFacility::Waypoint)) return;
751 SlObject(bst, this->GetDescription());
752 }
753};
754
756public:
757 static inline const SaveLoad description[] = {
760
765 SaveLoad::Variable<VarFileType::U32>("road_waypoint_area.tile", SLE_OBJECT_ADDRESS(Waypoint, road_waypoint_area.tile), SaveLoadVersion::RoadWaypoints),
768 };
769 static inline const SaveLoadCompatTable compat_description = _station_waypoint_sl_compat;
770
771 void Save(BaseStation *bst) const override
772 {
773 if (!bst->facilities.Test(StationFacility::Waypoint)) return;
774 SlObject(bst, this->GetDescription());
775 }
776
777 void Load(BaseStation *bst) const override
778 {
779 if (!bst->facilities.Test(StationFacility::Waypoint)) return;
780 SlObject(bst, this->GetLoadDescription());
781 }
782
783 void FixPointers(BaseStation *bst) const override
784 {
785 if (!bst->facilities.Test(StationFacility::Waypoint)) return;
786 SlObject(bst, this->GetDescription());
787 }
788};
789
790static const SaveLoad _station_desc[] = {
791 SaveLoad::SaveByte("facilities", SLE_OBJECT_ADDRESS(BaseStation, facilities)),
797};
798
799struct STNNChunkHandler : ChunkHandler {
800 STNNChunkHandler() : ChunkHandler("STNN", ChunkType::Table) {}
801
802 void Save() const override
803 {
804 SlTableHeader(_station_desc);
805
806 /* Write the stations */
807 for (BaseStation *st : BaseStation::Iterate()) {
808 SlSetArrayIndex(st->index);
809 SlObject(st, _station_desc);
810 }
811 }
812
813
814 void Load() const override
815 {
816 const std::vector<SaveLoad> slt = SlCompatTableHeader(_station_desc, _station_sl_compat);
817
818 _old_num_flows = 0;
819
820 int index;
821 while ((index = SlIterateArray()) != -1) {
822 bool waypoint = static_cast<StationFacilities>(SlReadByte()).Test(StationFacility::Waypoint);
823
824 BaseStation *bst = waypoint ? (BaseStation *)Waypoint::CreateAtIndex(StationID(index)) : Station::CreateAtIndex(StationID(index));
825 SlObject(bst, slt);
826 }
827 }
828
829 void FixPointers() const override
830 {
831 /* From SaveLoadVersion::UnifyWaypointAndStation we store stations in STNN; before that in STNS. So do not
832 * fix pointers when the version is below SaveLoadVersion::UnifyWaypointAndStation, as that would fix
833 * pointers twice: once in STNS chunk and once here. */
835
836 for (BaseStation *bst : BaseStation::Iterate()) {
837 SlObject(bst, _station_desc);
838 }
839 }
840};
841
842struct ROADChunkHandler : ChunkHandler {
843 ROADChunkHandler() : ChunkHandler("ROAD", ChunkType::Table) {}
844
845 void Save() const override
846 {
847 SlTableHeader(_roadstop_desc);
848
849 for (RoadStop *rs : RoadStop::Iterate()) {
850 SlSetArrayIndex(rs->index);
851 SlObject(rs, _roadstop_desc);
852 }
853 }
854
855 void Load() const override
856 {
857 const std::vector<SaveLoad> slt = SlCompatTableHeader(_roadstop_desc, _roadstop_sl_compat);
858
859 int index;
860
861 while ((index = SlIterateArray()) != -1) {
862 RoadStop *rs = RoadStop::CreateAtIndex(RoadStopID(index), INVALID_TILE);
863
864 SlObject(rs, slt);
865 }
866 }
867
868 void FixPointers() const override
869 {
870 for (RoadStop *rs : RoadStop::Iterate()) {
871 SlObject(rs, _roadstop_desc);
872 }
873 }
874};
875
876static const STNSChunkHandler STNS;
877static const STNNChunkHandler STNN;
878static const ROADChunkHandler ROAD;
879static const ChunkHandlerRef station_chunk_handlers[] = {
880 STNS,
881 STNN,
882 ROAD,
883};
884
885extern const ChunkHandlerTable _station_chunk_handlers(station_chunk_handlers);
std::vector< SpecMapping< T > > & GetStationSpecList(BaseStation *bst)
Get spec mapping list for each supported custom spec type.
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.
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 bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
static constexpr CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:77
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Set()
Set all bits.
const Tcont * Packets() const
Returns a pointer to the cargo packet list (so you can iterate over it etc).
Default handler for saving/loading an object to/from disk.
Definition saveload.h:585
Flow statistics telling how much flow should be sent along a link.
void AppendShare(StationID st, uint flow, bool restricted=false)
Add some flow to the end of the shares map.
static const StationSpec * GetByGrf(GrfID grfid, uint16_t local_id)
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
SaveLoadTable GetLoadDescription() const
Get the description for how to load the chunk.
std::vector< RoadStopTileData > & GetVector(BaseStation *bst) const override
Get instance of vector to load/save.
SaveLoad handler for the BaseStation, which all other stations / waypoints make use of.
void Save(BaseStation *bst) const override
Save the object to disk.
void Load(BaseStation *bst) const override
Load the object from disk.
void FixPointers(BaseStation *bst) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
Saveload handler for staiton cargo history data.
void Load(GoodsEntry *ge) const override
Load the object from disk.
static const SaveLoadCompatTable compat_description
Compatibility saveload description for handler.
static const SaveLoad description[]
Saveload description for handler.
void Save(GoodsEntry *ge) const override
Save the object to disk.
Saveload handler for staiton cargo history.
void Save(GoodsEntry::CargoHistoryData *chd) const override
Save the object to disk.
static const SaveLoadCompatTable compat_description
Compatibility saveload description for handler.
void Load(GoodsEntry::CargoHistoryData *chd) const override
Load the object from disk.
static const SaveLoad description[]
Saveload description for handler.
void Save(GoodsEntry *ge) const override
Save the object to disk.
void FixPointers(GoodsEntry *ge) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
void Load(GoodsEntry *ge) const override
Load the object from disk.
void Load(GoodsEntry *ge) const override
Load the object from disk.
void Save(GoodsEntry *ge) const override
Save the object to disk.
size_t GetNumCargo() const
Get the number of cargoes used by this savegame version.
void FixPointers(BaseStation *bst) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
void Load(BaseStation *bst) const override
Load the object from disk.
void Save(BaseStation *bst) const override
Save the object to disk.
SaveLoad handler for a normal station (read: not a waypoint).
void FixPointers(BaseStation *bst) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
void Load(BaseStation *bst) const override
Load the object from disk.
void Save(BaseStation *bst) const override
Save the object to disk.
size_t GetLength() const override
Get number of elements to load into vector.
static uint8_t last_num_specs
Number of specs of the last loaded station.
std::vector< SpecMapping< T > > & GetVector(BaseStation *bst) const override
Get instance of vector to load/save.
void Load(BaseStation *st) const override
Load the object from disk.
void Save(BaseStation *st) const override
Save the object to disk.
void Save(BaseStation *bst) const override
Save the object to disk.
void FixPointers(BaseStation *bst) const override
A post-load callback to fix SaveLoadType::Reference integers into pointers.
void Load(BaseStation *bst) const override
Load the object from disk.
void Append(CargoPacket *cp, StationID next)
Appends the given cargo packet to the range of packets with the same next station.
uint reserved_count
Amount of cargo being reserved for loading.
Wrapper class to abstract away the way the tiles are stored.
Definition map_func.h:25
uint8_t & m6()
General purpose.
Definition map_func.h:167
StrongType::Typedef< int32_t, DateTag< struct Calendar >, StrongType::Compare, StrongType::Integer > Date
Default handler for saving/loading a vector to/from disk.
Definition saveload.h:1338
static constexpr Owner OWNER_NONE
The tile has no ownership.
@ NW
Northwest.
@ NE
Northeast, upper right on your monitor.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
@ Invalid
An invalid spec feature.
Definition newgrf.h:112
void RoadStopUpdateCachedTriggers(BaseStation *st)
Update the cached animation trigger bitmask for a station.
NewGRF definitions and structures for road stops.
void StationUpdateCachedTriggers(BaseStation *st)
Update the cached animation trigger bitmask for a station.
Header file for NewGRF stations.
Label< struct GrfIDTag > GrfID
The unique identifier of a NewGRF.
Definition newgrf_type.h:17
Base class for roadstops.
A number of safeguards to prevent using unsafe methods.
std::vector< SaveLoad > SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
Load a table header in a savegame compatible way.
size_t SlGetStructListLength(size_t limit)
Get the length of this list; if it exceeds the limit, error out.
int SlIterateArray()
Iterate through the elements of an array and read the whole thing.
Definition saveload.cpp:747
uint8_t SlReadByte()
Wrapper for reading a byte from the buffer.
Definition saveload.cpp:412
void SlObject(void *object, const SaveLoadTable &slt)
Main SaveLoad function.
std::vector< SaveLoad > SlTableHeader(const SaveLoadTable &slt)
Save or Load a table header.
void SlSetStructListLength(size_t length)
Set the length of this list.
Functions/types related to saving and loading games.
#define SLE_OBJECT_ADDRESS(base, variable)
Macro to be able to pass the variable type and construct the SaveLoad::AddressFunction given a base c...
Definition saveload.h:752
#define SLE_GLOBAL_ADDRESS(variable)
Macro to be able to pass the variable type and construct the SaveLoad::AddressFunction given a global...
Definition saveload.h:759
std::reference_wrapper< const ChunkHandler > ChunkHandlerRef
A reference to ChunkHandler.
Definition saveload.h:512
std::span< const ChunkHandlerRef > ChunkHandlerTable
A table of ChunkHandler entries.
Definition saveload.h:515
std::span< const struct SaveLoadCompat > SaveLoadCompatTable
A table of SaveLoadCompat entries.
Definition saveload.h:518
bool IsSavegameVersionBefore(SaveLoadVersion major, uint8_t minor=0)
Checks whether the savegame is below major.
Definition saveload.h:1223
@ BigDates
Saveload version: 31, SVN revision: 5999 Change date from 1920 - 2090 to 0 - 5 000 000.
Definition saveload.h:85
@ ExtendCargotypes
Saveload version: 199, GitHub pull request: 6802 Extend cargotypes to 64.
Definition saveload.h:286
@ UnifyWaypointAndStation
Saveload version: 123, SVN revision: 16909 Unify stations and waypoints.
Definition saveload.h:195
@ UnifyCurrency
Saveload version: 65, SVN revision: 10210 Make all variables related to currency 64 bits.
Definition saveload.h:126
@ LinkgraphRestrictedFlow
Saveload version: 187, SVN revision: 25899 Linkgraph - restricted flows.
Definition saveload.h:272
@ CargoReservation
Saveload version: 181, SVN revision: 25012 Persist the reservation of cargo for vehicles instead of ...
Definition saveload.h:265
@ FifoLoading
Saveload version: 57, SVN revision: 9691 First-in-first-out loading of vehicles.
Definition saveload.h:116
@ RoadWaypoints
Saveload version: 338, GitHub pull request: 12572 Road waypoints.
Definition saveload.h:389
@ ReplaceCustomNameArray
Saveload version: 84, SVN revision: 11822 Replace single fixed size array of custom names,...
Definition saveload.h:148
@ LastVehicleType
Saveload version: 26, SVN revision: 4466 Store the last vehicle type at stations instead of the vehi...
Definition saveload.h:79
@ NewGRFSuppliedStationName
Saveload version: 103, SVN revision: 14598 NewGRF industry supplying default names for nearby statio...
Definition saveload.h:171
@ VehicleCurrencyStationChanges
Saveload version: 2.0, release: 0.3.0 Adding vehicle state, larger currency size for statistics,...
Definition saveload.h:38
@ MultitileDocks
Saveload version: 216, GitHub pull request: 7380 Multiple docks per station.
Definition saveload.h:307
@ LargerCargoSource
Saveload version: 7.0, SVN revision: 1770 With more stations, the size of the cargo source needed to...
Definition saveload.h:53
@ TownAcceptance
Saveload version: 127, SVN revision: 17439 Store mask of cargos accepted by town houses and head qua...
Definition saveload.h:200
@ TransferOrder
Saveload version: 14.0, SVN revision: 2441 Transfer orders for feeder systems.
Definition saveload.h:62
@ FractionalCargoDelivery
Saveload version: 150, SVN revision: 20857 When spreading cargo over stations, spread fractional amo...
Definition saveload.h:228
@ NewGRFRoadStops
Saveload version: 303, GitHub pull request: 10144 NewGRF road stops.
Definition saveload.h:347
@ CargoSourceTile
Saveload version: 44, SVN revision: 8144 Store the source tile of the cargo, so accurate payment can...
Definition saveload.h:100
@ StoreAirportSize
Saveload version: 140, SVN revision: 19382 Store the size of the airport in the station.
Definition saveload.h:216
@ ExtendEntityMapping
Saveload version: 311, GitHub pull request: 10672 Extend entity mapping range.
Definition saveload.h:357
@ MultipleRoadStops
Saveload version: 6.0, SVN revision: 1721 Multi tile road stops, and some map size related fixes.
Definition saveload.h:51
@ RoadStopTileData
Saveload version: 340, GitHub pull request: 12883 Move storage of road stop tile data,...
Definition saveload.h:392
@ Cargodist
Saveload version: 183, SVN revision: 25363 Cargodist.
Definition saveload.h:267
@ MoreAirportBlocks
Saveload version: 46, SVN revision: 8705 Increase number of blocks an airport can have.
Definition saveload.h:103
@ MinVersion
First savegame version.
Definition saveload.h:35
@ WaypointMoreLikeStation
Saveload version: 122, SVN revision: 16855 Make waypoint data look more like stations.
Definition saveload.h:194
@ BiggerStationVariables
Saveload version: 3.0 Increase size of airport blocks/station build date.
Definition saveload.h:41
@ NewGRFAirportSmoke
Saveload version: 145, SVN revision: 20376 NewGRF support for airport and configurable amount of smo...
Definition saveload.h:222
@ SaveloadListLength
Saveload version: 293, GitHub pull request: 9374 Consistency in list length with SaveLoadType::Struc...
Definition saveload.h:335
@ MultiTileWaypoints
Saveload version: 124, SVN revision: 16993 Waypoints can be bigger than a single tile.
Definition saveload.h:196
@ NewGRFCargo
Saveload version: 55, SVN revision: 9638 Increase number of cargos and NewGRF control of cargos.
Definition saveload.h:114
@ CargoPackets
Saveload version: 68, SVN revision: 10266 Account for individual units of cargo, i....
Definition saveload.h:129
@ NewGRFStations
Saveload version: 27, SVN revision: 4757 NewGRF graphics for stations.
Definition saveload.h:80
@ PersistentStoragePool
Saveload version: 161, SVN revision: 22567 Store persistent storage in a pool.
Definition saveload.h:241
@ ReadOnly
Chunk is never saved.
Definition saveload.h:453
@ Table
An Array with a header describing the elements.
Definition saveload.h:449
Base classes/functions for stations.
void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
Set rail station tile flags for the given tile.
Functions related to stations.
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:26
bool HasStationTileRail(Tile t)
Has this station tile a rail?
bool IsBuoyTile(Tile t)
Is tile t a buoy tile?
void MoveBuoysToWaypoints()
Perform all steps to upgrade from the old station buoys to the new version that uses waypoints.
static void UpdateWaypointOrder(Order &o)
Update the buoy orders to be waypoint orders.
void AfterLoadRoadStops()
(Re)building of road stop caches after loading a savegame.
static void SwapPackets(GoodsEntry *ge)
Swap the temporary packets with the packets without specific destination in the given goods entry.
Loading of station chunks before table headers were added.
const SaveLoadCompat _station_base_sl_compat[]
Original field order for SlStationBase.
const SaveLoadCompat _roadstop_sl_compat[]
Original field order for _roadstop_desc.
const SaveLoadCompat _station_sl_compat[]
Original field order for _station_desc.
const SaveLoadCompat _station_cargo_sl_compat[]
Original field order for SlStationCargo.
const SaveLoadCompat _station_goods_sl_compat[]
Original field order for SlStationGoods.
const SaveLoadCompat _station_flow_sl_compat[]
Original field order for SlStationFlow.
const SaveLoadCompat _station_waypoint_sl_compat[]
Original field order for SlStationWaypoint.
const SaveLoadCompat _station_normal_sl_compat[]
Original field order for SlStationNormal.
const SaveLoadCompat _old_station_sl_compat[]
Original field order for _old_station_desc.
const SaveLoadCompat _station_spec_list_sl_compat[]
Original field order for SlStationSpecList.
@ Dock
Station with a dock.
@ Waypoint
Station is a waypoint.
@ Train
Station with train station.
@ Airport
Station with an airport.
@ RailWaypoint
Waypoint for trains.
EnumBitSet< StationFacility, uint8_t > StationFacilities
Bitset of StationFacility elements.
@ Waypoint
Station is a waypoint (Save load conversion and NewGRF only!).
Definition of base types and functions in a cross-platform compatible way.
@ AllowControlCode
Allow the special control codes.
Definition string_type.h:47
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
PersistentStorage * psa
Persistent storage for NewGRF airports.
Base class for all station-ish types.
StringID string_id
Default name (town area) of station.
StationFacilities facilities
The facilities that this station has.
TileArea train_station
Tile area the train 'station' part covers.
Owner owner
The owner of this station.
uint8_t delete_ctr
Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is ...
Town * town
The town this station is associated with.
std::vector< RoadStopTileData > custom_roadstop_tile_data
List of custom road stop tile data.
TimerGameCalendar::Date build_date
Date of construction.
std::string name
Custom name.
TileArea spread
NOSAVE: Station spread tile area.
Container for cargo from the same location and time.
Definition cargopacket.h:40
ChunkHandler(ChunkId id, ChunkType type)
Create this ChunkHandler.
Definition saveload.h:469
Storage for station cargo history.
HistoryData< CargoHistory > history
Historical cargo data.
Individual data point for station cargo history.
FlowStatMap flows
Planned flows through this station.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Stores station stats for a single cargo.
const CargoHistoryData & GetHistory() const
Get the cargo history data.
States status
Status of this cargo, see State.
@ Acceptance
Set when the station accepts the cargo currently for final deliveries.
@ Rating
This indicates whether a cargo has a rating at the station.
const GoodsEntryData & GetData() const
Get optional cargo packet/flow data.
CargoHistoryData & GetOrCreateHistory()
Get or create the cargo history data.
bool HasData() const
Test if this goods entry has optional cargo packet/flow data.
bool HasHistory() const
Test if cargo history is present.
GoodsEntryData & GetOrCreateData()
Get optional cargo packet/flow data.
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
Definition map_func.h:366
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition order_base.h:373
If you change this, keep in mind that it is also saved in 2 other places:
Definition order_base.h:33
DestinationID GetDestination() const
Gets the destination of this order.
Definition order_base.h:99
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
void MakeGoToWaypoint(StationID destination)
Makes this order a Go To Waypoint order.
Definition order_cmd.cpp:88
StorageType storage
Memory for the storage array.
static Pool::IterateWrapper< OrderList > Iterate(size_t from=0)
static T * CreateAtIndex(RoadStopID index, Targs &&... args)
void FixPointers() const override
Fix the pointers.
void Load() const override
Load the chunk.
void Save() const override
Save the chunk.
A Stop for a Road Vehicle.
@ BaseEntry
Non-zero when the entries on this road stop are the primary, i.e. the ones to delete.
RoadStop * next
Next stop of the given type at this station.
void FixPointers() const override
Fix the pointers.
void Save() const override
Save the chunk.
void Load() const override
Load the chunk.
void Load() const override
Load the chunk.
void FixPointers() const override
Fix the pointers.
SaveLoad type struct.
Definition saveload.h:762
static SaveLoad StructList(std::string name, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a list of structs, optionally in some savegame versions.
Definition saveload.h:1100
static SaveLoad SaveByte(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a byte variable in some savegame versions that is not automatically read by the SaveLoad c...
Definition saveload.h:1122
static SaveLoad Variable(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion, size_t extra=0)
Storage of a variable in some savegame versions.
Definition saveload.h:923
static SaveLoad ReferenceList(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a list of references to pool elements in some savegame versions.
Definition saveload.h:1075
static SaveLoad Array(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion, size_t extra=0)
Storage of an array in some savegame versions.
Definition saveload.h:1023
static SaveLoad Reference(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a reference to a pool element in some savegame versions.
Definition saveload.h:948
static SaveLoad Struct(std::string name, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a structs, optionally in some savegame versions.
Definition saveload.h:998
static SaveLoad String(std::string name, AddressFunction< T > address_func, StringValidationSettings string_validation_settings={}, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion, size_t extra=0)
Storage of a string in some savegame versions.
Definition saveload.h:974
static bool IsExpected(const BaseStation *st)
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static Waypoint * CreateAtIndex(StationID index, Targs &&... args)
static Station * Get(auto index)
static Station * From(BaseStation *st)
Station data structure.
RoadStop * bus_stops
All the road stops.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
TileArea bus_station
Tile area the bus 'station' part covers.
Airport airport
Tile area the airport covers.
TileArea truck_station
Tile area the truck 'station' part covers.
RoadStop * truck_stops
All the truck stops.
Town data structure.
Definition town.h:64
Vehicle data structure.
Representation of a waypoint.
uint16_t town_cn
The N-1th waypoint for this town (consecutive number).
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
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:92
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
@ Station
A tile of a station or airport.
Definition tile_type.h:54
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition of the game-calendar-timer.
Base of the town class.
Base class for all vehicles.
VehicleType
Available vehicle types.
@ Ship
Ship vehicle type.
@ Train
Train vehicle type.
Base of waypoints.