OpenTTD Source 20261112-master-gbcbec5e63f
cargopacket.h
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#ifndef CARGOPACKET_H
11#define CARGOPACKET_H
12
13#include "core/pool_type.hpp"
14#include "economy_type.h"
15#include "station_type.h"
16#include "order_type.h"
17#include "cargo_type.h"
18#include "source_type.h"
19#include "core/multimap.hpp"
21
24struct CargoPacket;
25
29extern CargoPacketPool _cargopacket_pool;
30
31struct GoodsEntry; // forward-declare for Stage() and RerouteStalePackets()
32
33template <class Tinst, class Tcont> class CargoList;
34class StationCargoList; // forward-declare, so we can use it in VehicleCargoList.
36
40struct CargoPacket : CargoPacketPool::PoolItem<&_cargopacket_pool> {
41private:
42 uint16_t count = 0;
43 uint16_t periods_in_transit = 0;
44
45 Money feeder_share = 0;
46
49
51
52#ifdef WITH_ASSERT
53 bool in_vehicle = false;
54#endif /* WITH_ASSERT */
55
56 StationID first_station = StationID::Invalid();
57 StationID next_hop = StationID::Invalid();
58
60 template <class Tinst, class Tcont> friend class CargoList;
61 friend class VehicleCargoList;
62 friend class StationCargoList;
65public:
67 static const uint16_t MAX_COUNT = UINT16_MAX;
68
72 CargoPacket(CargoPacketID index, uint16_t count, Money feeder_share, CargoPacket &original);
73
74 CargoPacket *Split(uint new_size);
75 void Merge(CargoPacket *cp);
76 void Reduce(uint count);
77
82 void SetNextHop(StationID next_hop)
83 {
84 this->next_hop = next_hop;
85 }
86
102 {
103 if (this->source_xy == INVALID_TILE) {
104 this->source_xy = tile;
105 }
106
107#ifdef WITH_ASSERT
108 assert(!this->in_vehicle);
109 this->in_vehicle = true;
110#endif /* WITH_ASSERT */
111
112 /* We want to calculate the vector from tile-unload to tile-load. As
113 * we currently only know the latter, add it. When we know where we unload,
114 * we subtract is, giving us our vector (unload - load). */
115 this->travelled.x += TileX(tile);
116 this->travelled.y += TileY(tile);
117 }
118
125 {
126#ifdef WITH_ASSERT
127 assert(this->in_vehicle);
128 this->in_vehicle = false;
129#endif /* WITH_ASSERT */
130
131 this->travelled.x -= TileX(tile);
132 this->travelled.y -= TileY(tile);
133 }
134
139 void AddFeederShare(Money new_share)
140 {
141 this->feeder_share += new_share;
142 }
143
148 inline uint16_t Count() const
149 {
150 return this->count;
151 }
152
158 inline Money GetFeederShare() const
159 {
160 return this->feeder_share;
161 }
162
169 inline Money GetFeederShare(uint part) const
170 {
171 return this->feeder_share * part / static_cast<uint>(this->count);
172 }
173
181 inline uint16_t GetPeriodsInTransit() const
182 {
183 return this->periods_in_transit;
184 }
185
190 inline Source GetSource() const
191 {
192 return this->source;
193 }
194
199 inline StationID GetFirstStation() const
200 {
201 return this->first_station;
202 }
203
210 inline uint GetDistance(TileIndex current_tile) const
211 {
212 assert(this->source_xy != INVALID_TILE);
213#ifdef WITH_ASSERT
214 assert(this->in_vehicle);
215#endif /* WITH_ASSERT */
216
217 /* Distance is always requested when the cargo is still inside the
218 * vehicle. So first finish the calculation for travelled to
219 * become a vector. */
220 auto local_travelled = travelled;
221 local_travelled.x -= TileX(current_tile);
222 local_travelled.y -= TileY(current_tile);
223
224 /* Cargo-movement is a vector that indicates how much the cargo has
225 * actually traveled in a vehicle. This is the distance you get paid
226 * for. However, one could construct a route where this vector would
227 * be really long. To not overpay the player, cap out at the distance
228 * between source and destination.
229 *
230 * This way of calculating is to counter people moving cargo for free
231 * and instantly in stations, where you deliver it in one part of the
232 * station and pick it up in another. By using the actual distance
233 * traveled in a vehicle, using this trick doesn't give you more money.
234 *
235 * However, especially in large networks with large transfer station,
236 * etc, one could actually make the route a lot longer. In that case,
237 * use the actual distance between source and destination.
238 */
239
240 uint distance_travelled = abs(local_travelled.x) + abs(local_travelled.y);
241 uint distance_source_dest = DistanceManhattan(this->source_xy, current_tile);
242 return std::min(distance_travelled, distance_source_dest);
243 }
244
249 inline StationID GetNextHop() const
250 {
251 return this->next_hop;
252 }
253
260 static bool AreMergable(const CargoPacket *cp1, const CargoPacket *cp2)
261 {
262 return cp1->source_xy == cp2->source_xy &&
264 cp1->first_station == cp2->first_station &&
265 cp1->source == cp2->source;
266 }
267
268 static void InvalidateAllFrom(Source src);
269 static void InvalidateAllFrom(StationID sid);
270 static void AfterLoad();
271};
272
277template <class Tinst, class Tcont>
279public:
281 typedef typename Tcont::iterator Iterator;
283 typedef typename Tcont::reverse_iterator ReverseIterator;
285 typedef typename Tcont::const_iterator ConstIterator;
287 typedef typename Tcont::const_reverse_iterator ConstReverseIterator;
288
290 enum class MoveToAction : uint8_t {
296 };
297
298protected:
299 uint count = 0;
301
302 Tcont packets{};
303
304 void AddToCache(const CargoPacket *cp);
305
306 void RemoveFromCache(const CargoPacket *cp, uint count);
307
308 static bool TryMerge(CargoPacket *cp, CargoPacket *icp);
309
310public:
313
315
317
322 inline const Tcont *Packets() const
323 {
324 return &this->packets;
325 }
326
331 inline uint PeriodsInTransit() const
332 {
333 return this->count == 0 ? 0 : this->cargo_periods_in_transit / this->count;
334 }
335
337};
338
339typedef std::list<CargoPacket *> CargoPacketList;
340
344class VehicleCargoList : public CargoList<VehicleCargoList, CargoPacketList> {
345protected:
348
351
352 template <class Taction>
353 void ShiftCargo(Taction action);
354
355 template <class Taction>
356 void PopCargo(Taction action);
357
361 inline void AssertCountConsistency() const
362 {
363 assert(this->action_counts[MoveToAction::Keep] +
364 this->action_counts[MoveToAction::Deliver] +
365 this->action_counts[MoveToAction::Transfer] +
366 this->action_counts[MoveToAction::Load] == this->count);
367 }
368
369 void AddToCache(const CargoPacket *cp);
370 void RemoveFromCache(const CargoPacket *cp, uint count);
371
372 void AddToMeta(const CargoPacket *cp, MoveToAction action);
373 void RemoveFromMeta(const CargoPacket *cp, MoveToAction action, uint count);
374 uint TryRemoveFromMeta(const CargoPacket *cp, MoveToAction action, uint count);
375
376 static MoveToAction ChooseAction(const CargoPacket *cp, StationID cargo_next,
377 StationID current_station, bool accepted, std::span<const StationID> next_station);
378
379public:
381 friend class StationCargoList;
383 friend class CargoList<VehicleCargoList, CargoPacketList>;
384 /* So we can use private/protected variables in the saveload code */
385 friend class SlVehicleCommon;
386
387 friend class CargoShift;
388 friend class CargoTransfer;
389 friend class CargoDelivery;
390 template <class Tsource>
391 friend class CargoRemoval;
392 friend class CargoReturn;
393 friend class VehicleCargoReroute;
394
399 inline StationID GetFirstStation() const
400 {
401 return this->count == 0 ? StationID::Invalid() : this->packets.front()->first_station;
402 }
403
408 inline Money GetFeederShare() const
409 {
410 return this->feeder_share;
411 }
412
418 inline uint ActionCount(MoveToAction action) const
419 {
420 return this->action_counts[action];
421 }
422
428 inline uint StoredCount() const
429 {
430 return this->count - this->action_counts[MoveToAction::Load];
431 }
432
437 inline uint TotalCount() const
438 {
439 return this->count;
440 }
441
446 inline uint ReservedCount() const
447 {
448 return this->action_counts[MoveToAction::Load];
449 }
450
455 inline uint UnloadCount() const
456 {
457 return this->action_counts[MoveToAction::Transfer] + this->action_counts[MoveToAction::Deliver];
458 }
459
464 inline uint RemainingCount() const
465 {
466 return this->action_counts[MoveToAction::Keep] + this->action_counts[MoveToAction::Load];
467 }
468
469 void Append(CargoPacket *cp, MoveToAction action = MoveToAction::Keep);
470
471 void AgeCargo();
472
473 void InvalidateCache();
474
475 bool Stage(bool accepted, StationID current_station, std::span<const StationID> next_station, OrderUnloadType unload_type, const GoodsEntry *ge, CargoType cargo, CargoPayment *payment, TileIndex current_tile);
476
482 inline void KeepAll()
483 {
484 this->action_counts[MoveToAction::Deliver] = 0;
485 this->action_counts[MoveToAction::Transfer] = 0;
486 this->action_counts[MoveToAction::Load] = 0;
487 this->action_counts[MoveToAction::Keep] = this->count;
488 }
489
490 /* Methods for moving cargo around. First parameter is always maximum
491 * amount of cargo to be moved. Second parameter is destination (if
492 * applicable), return value is amount of cargo actually moved. */
493
494 template <MoveToAction Tfrom, MoveToAction Tto>
495 uint Reassign(uint max_move);
496 uint Return(uint max_move, StationCargoList *dest, StationID next_station, TileIndex current_tile);
497 uint Unload(uint max_move, StationCargoList *dest, CargoType cargo, CargoPayment *payment, TileIndex current_tile);
498 uint Shift(uint max_move, VehicleCargoList *dest);
499 uint Truncate(uint max_move = UINT_MAX);
500 uint Reroute(uint max_move, VehicleCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge);
501};
502
503typedef MultiMap<StationID, CargoPacket *> StationCargoPacketMap;
504typedef std::map<StationID, uint> StationCargoAmountMap;
505
509class StationCargoList : public CargoList<StationCargoList, StationCargoPacketMap> {
510protected:
513
515
516public:
518 friend class CargoList<StationCargoList, StationCargoPacketMap>;
519 /* So we can use private/protected variables in the saveload code */
520 friend class SlStationGoods;
521
522 friend class CargoLoad;
523 friend class CargoTransfer;
524 template <class Tsource>
525 friend class CargoRemoval;
526 friend class CargoReservation;
527 friend class CargoReturn;
528 friend class StationCargoReroute;
529
530 static void InvalidateAllFrom(Source src);
531
532 template <class Taction>
533 bool ShiftCargo(Taction &action, StationID next);
534
535 template <class Taction>
536 uint ShiftCargo(Taction action, std::span<const StationID> next, bool include_invalid);
537
538 void Append(CargoPacket *cp, StationID next);
539
545 inline bool HasCargoFor(std::span<const StationID> next) const
546 {
547 for (const StationID &station : next) {
548 if (this->packets.find(station) != this->packets.end()) return true;
549 }
550 /* Packets for StationID::Invalid() can go anywhere. */
551 return this->packets.find(StationID::Invalid()) != this->packets.end();
552 }
553
558 inline StationID GetFirstStation() const
559 {
560 return this->count == 0 ? StationID::Invalid() : this->packets.begin()->second.front()->first_station;
561 }
562
568 inline uint AvailableCount() const
569 {
570 return this->count;
571 }
572
577 inline uint ReservedCount() const
578 {
579 return this->reserved_count;
580 }
581
587 inline uint TotalCount() const
588 {
589 return this->count + this->reserved_count;
590 }
591
592 /* Methods for moving cargo around. First parameter is always maximum
593 * amount of cargo to be moved. Second parameter is destination (if
594 * applicable), return value is amount of cargo actually moved. */
595
596 uint Reserve(uint max_move, VehicleCargoList *dest, std::span<const StationID> next, TileIndex current_tile);
597 uint Load(uint max_move, VehicleCargoList *dest, std::span<const StationID> next, TileIndex current_tile);
598 uint Truncate(uint max_move = UINT_MAX, StationCargoAmountMap *cargo_per_source = nullptr);
599 uint Reroute(uint max_move, StationCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge);
600};
601
602#endif /* CARGOPACKET_H */
Types related to cargoes...
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
PoolID< uint32_t, struct CargoPacketIDTag, 0xFFF000, 0xFFFFFF > CargoPacketID
Unique identifier for a single cargo packet.
Definition cargopacket.h:23
SaveLoadTable GetCargoPacketDesc()
Wrapper function to get the CargoPacket's internal structure while some of the variables itself are p...
Pool< CargoPacket, CargoPacketID, 1024, PoolType::Normal, true > CargoPacketPool
Type of the pool for cargo packets for a little over 16 million packets.
Definition cargopacket.h:27
Simple collection class for a list of cargo packets.
Tcont::reverse_iterator ReverseIterator
The reverse iterator for our container.
void OnCleanPool()
Empty the cargo list, but don't free the cargo packets; the cargo packets are cleaned by CargoPacket'...
~CargoList()
Destroy the cargolist ("frees" all cargo packets).
const Tcont * Packets() const
Returns a pointer to the cargo packet list (so you can iterate over it etc).
Tcont::const_iterator ConstIterator
The const iterator for our container.
CargoList()
Create the cargo list.
static bool TryMerge(CargoPacket *cp, CargoPacket *icp)
Tries to merge the second packet into the first and return if that was successful.
Tcont::iterator Iterator
The iterator for our container.
MoveToAction
Kind of actions that could be done with packets on move.
@ Keep
Keep the cargo in the vehicle.
@ Deliver
Deliver the cargo to some town or industry.
@ Transfer
Transfer the cargo to the station.
@ Load
Load the cargo from the station.
Tcont::const_reverse_iterator ConstReverseIterator
The const reverse iterator for our container.
uint PeriodsInTransit() const
Returns average number of cargo aging periods in transit for a cargo entity.
void AddToCache(const CargoPacket *cp)
Update the cache to reflect adding of this packet.
void InvalidateCache()
Invalidates the cached data and rebuilds it.
void RemoveFromCache(const CargoPacket *cp, uint count)
Update the cached values to reflect the removal of this packet or part of it.
Hand-rolled multimap as map of lists.
Definition multimap.hpp:223
CargoList that is used for stations.
bool HasCargoFor(std::span< const StationID > next) const
Check for cargo headed for a specific station.
CargoList< StationCargoList, StationCargoPacketMap > Parent
The (direct) parent of this class.
uint TotalCount() const
Returns total count of cargo at the station, including cargo which is already reserved for loading.
uint Reroute(uint max_move, StationCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge)
Routes packets with station "avoid" as next hop to a different place.
uint ReservedCount() const
Returns sum of cargo reserved for loading onto vehicles.
uint Load(uint max_move, VehicleCargoList *dest, std::span< const StationID > next, TileIndex current_tile)
Loads cargo onto a vehicle.
uint AvailableCount() const
Returns sum of cargo still available for loading at the station.
void Append(CargoPacket *cp, StationID next)
Appends the given cargo packet to the range of packets with the same next station.
uint Truncate(uint max_move=UINT_MAX, StationCargoAmountMap *cargo_per_source=nullptr)
Truncates where each destination loses roughly the same percentage of its cargo.
bool ShiftCargo(Taction &action, StationID next)
Shifts cargo from the front of the packet list for a specific station and applies some action to it.
uint reserved_count
Amount of cargo being reserved for loading.
uint Reserve(uint max_move, VehicleCargoList *dest, std::span< const StationID > next, TileIndex current_tile)
Reserves cargo for loading onto the vehicle.
StationID GetFirstStation() const
Returns first station of the first cargo packet in this list.
CargoList that is used for vehicles.
uint Shift(uint max_move, VehicleCargoList *dest)
Shifts cargo between two vehicles.
void AddToMeta(const CargoPacket *cp, MoveToAction action)
Adds a packet to the metadata.
uint UnloadCount() const
Returns sum of cargo to be moved out of the vehicle at the current station.
void PopCargo(Taction action)
Pops cargo from the back of the packet list and applies some action to it.
friend class StationCargoList
The station cargo list needs to control the unloading.
Money GetFeederShare() const
Returns total sum of the feeder share for all packets.
uint Reroute(uint max_move, VehicleCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge)
Routes packets with station "avoid" as next hop to a different place.
uint ActionCount(MoveToAction action) const
Returns the amount of cargo designated for a given purpose.
static MoveToAction ChooseAction(const CargoPacket *cp, StationID cargo_next, StationID current_station, bool accepted, std::span< const StationID > next_station)
Choose action to be performed with the given cargo packet.
uint Truncate(uint max_move=UINT_MAX)
Truncates the cargo in this list to the given amount.
void AssertCountConsistency() const
Assert that the designation counts add up.
void RemoveFromMeta(const CargoPacket *cp, MoveToAction action, uint count)
Removes a packet or part of it from the metadata.
uint Return(uint max_move, StationCargoList *dest, StationID next_station, TileIndex current_tile)
Returns reserved cargo to the station and removes it from the cache.
uint TotalCount() const
Returns sum of cargo, including reserved cargo.
uint ReservedCount() const
Returns sum of reserved cargo.
uint RemainingCount() const
Returns the sum of cargo to be kept in the vehicle at the current station.
EnumIndexArray< uint, MoveToAction, MoveToAction::End > action_counts
Counts of cargo to be transferred, delivered, kept and loaded.
CargoList< VehicleCargoList, CargoPacketList > Parent
The (direct) parent of this class.
Money feeder_share
Cache for the feeder share.
void RemoveFromCache(const CargoPacket *cp, uint count)
Update the cached values to reflect the removal of this packet or part of it.
uint Reassign(uint max_move)
Moves some cargo from one designation to another.
uint TryRemoveFromMeta(const CargoPacket *cp, MoveToAction action, uint count)
Try to remove a packet or part of it from the metadata.
void InvalidateCache()
Invalidates the cached data and rebuild it.
void AddToCache(const CargoPacket *cp)
Update the cache to reflect adding of this packet.
void KeepAll()
Marks all cargo in the vehicle as to be kept.
StationID GetFirstStation() const
Returns the first station of the first cargo packet in this list.
void AgeCargo()
Ages the all cargo in this list.
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
uint Unload(uint max_move, StationCargoList *dest, CargoType cargo, CargoPayment *payment, TileIndex current_tile)
Unloads cargo at the given station.
bool Stage(bool accepted, StationID current_station, std::span< const StationID > next_station, OrderUnloadType unload_type, const GoodsEntry *ge, CargoType cargo, CargoPayment *payment, TileIndex current_tile)
Stages cargo for unloading.
void ShiftCargo(Taction action)
Shifts cargo from the front of the packet list and applies some action to it.
void Append(CargoPacket *cp, MoveToAction action=MoveToAction::Keep)
Appends the given cargo packet.
Types related to the economy.
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:168
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
Multimap with deterministic ordering of items with equal keys.
Types related to orders.
OrderUnloadType
Unloading order types.
Definition order_type.h:67
Definition of Pool, structure used to access PoolItems, and PoolItem, base structure for Vehicle,...
Types often used outside the saveload code related to saving and loading games.
std::span< const struct SaveLoad > SaveLoadTable
A table of SaveLoad entries.
Type for the source of cargo.
@ Industry
Source/destination is an industry.
Definition source_type.h:21
Types related to stations.
Container for cargo from the same location and time.
Definition cargopacket.h:40
void Reduce(uint count)
Reduce the packet by the given amount and remove the feeder share.
uint16_t Count() const
Gets the number of 'items' in this packet.
Money GetFeederShare(uint part) const
Gets part of the amount of money already paid to earlier vehicles in the feeder chain.
friend class CargoList
The CargoList caches, thus needs to know about it.
Definition cargopacket.h:60
void Merge(CargoPacket *cp)
Merge another packet into this one.
Money feeder_share
Value of feeder pickup to be paid for on delivery of cargo.
Definition cargopacket.h:45
static const uint16_t MAX_COUNT
Maximum number of items in a single cargo packet.
Definition cargopacket.h:67
TileIndex source_xy
The origin of the cargo.
Definition cargopacket.h:47
void SetNextHop(StationID next_hop)
Sets the station where the packet is supposed to go next.
Definition cargopacket.h:82
CargoPacket * Split(uint new_size)
Split this packet in two and return the split off part.
StationID next_hop
Station where the cargo wants to go next.
Definition cargopacket.h:57
Source source
Source of the cargo.
Definition cargopacket.h:50
Coord2D< int16_t > travelled
If cargo is in station: the vector from the unload tile to the source tile. If in vehicle: an interme...
Definition cargopacket.h:48
void UpdateLoadingTile(TileIndex tile)
Update for the cargo being loaded on this tile.
friend SaveLoadTable GetCargoPacketDesc()
We want this to be saved, right?
void AddFeederShare(Money new_share)
Adds some feeder share to the packet.
CargoPacket(CargoPacketID index)
Create a new packet for savegame loading.
static bool AreMergable(const CargoPacket *cp1, const CargoPacket *cp2)
Are the two CargoPackets mergeable.
static void AfterLoad()
Savegame conversion for cargopackets.
StationID GetNextHop() const
Gets the ID of station the cargo wants to go next.
uint16_t count
The amount of cargo in this packet.
Definition cargopacket.h:42
Money GetFeederShare() const
Gets the amount of money already paid to earlier vehicles in the feeder chain.
StationID GetFirstStation() const
Gets the ID of the station where the cargo was loaded for the first time.
uint GetDistance(TileIndex current_tile) const
Get the current distance the cargo has traveled.
StationID first_station
The station where the cargo came from first.
Definition cargopacket.h:56
uint16_t GetPeriodsInTransit() const
Gets the number of cargo aging periods this cargo has been in transit.
Source GetSource() const
Gets the source of the packet for subsidy purposes.
static void InvalidateAllFrom(Source src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
void UpdateUnloadingTile(TileIndex tile)
Update for the cargo being unloaded on this tile.
uint16_t periods_in_transit
Amount of cargo aging periods this packet has been in transit.
Definition cargopacket.h:43
Helper class to perform the cargo payment.
A coordinate with two dimensions.
T y
Y coordinate.
T x
X coordinate.
Stores station stats for a single cargo.
Templated helper to make a PoolID a single POD value.
Definition pool_type.hpp:50
Base class for all pools.
A location from where cargo can come from (or go to).
Definition source_type.h:32
static constexpr SourceID Invalid
Invalid/unknown index of source.
Definition source_type.h:34
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