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/>.
8 /** @file cargopacket.h Base class for cargo packets. */
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 "vehicle_type.h"
19 #include "core/multimap.hpp"
20 #include "saveload/saveload.h"
22 /** Unique identifier for a single cargo packet. */
23 typedef uint32_t CargoPacketID
;
26 /** Type of the pool for cargo packets for a little over 16 million packets. */
27 typedef Pool
<CargoPacket
, CargoPacketID
, 1024, 0xFFF000, PT_NORMAL
, true, false> CargoPacketPool
;
28 /** The actual pool with cargo packets. */
29 extern CargoPacketPool _cargopacket_pool
;
31 struct GoodsEntry
; // forward-declare for Stage() and RerouteStalePackets()
33 template <class Tinst
, class Tcont
> class CargoList
;
34 class StationCargoList
; // forward-declare, so we can use it in VehicleCargoList.
35 extern SaveLoadTable
GetCargoPacketDesc();
38 * Container for cargo from the same location and time.
40 struct CargoPacket
: CargoPacketPool::PoolItem
<&_cargopacket_pool
> {
42 /* A mathematical vector from (0,0). */
48 uint16_t count
{0}; ///< The amount of cargo in this packet.
49 uint16_t periods_in_transit
{0}; ///< Amount of cargo aging periods this packet has been in transit.
51 Money feeder_share
{0}; ///< Value of feeder pickup to be paid for on delivery of cargo.
53 TileIndex source_xy
{INVALID_TILE
}; ///< The origin of the cargo.
54 Vector travelled
{0, 0}; ///< If cargo is in station: the vector from the unload tile to the source tile. If in vehicle: an intermediate value.
56 SourceID source_id
{INVALID_SOURCE
}; ///< Index of industry/town/HQ, INVALID_SOURCE if unknown/invalid.
57 SourceType source_type
{SourceType::Industry
}; ///< Type of \c source_id.
60 bool in_vehicle
{false}; ///< NOSAVE: Whether this cargo is in a vehicle or not.
61 #endif /* WITH_ASSERT */
63 StationID first_station
{INVALID_STATION
}; ///< The station where the cargo came from first.
64 StationID next_hop
{INVALID_STATION
}; ///< Station where the cargo wants to go next.
66 /** The CargoList caches, thus needs to know about it. */
67 template <class Tinst
, class Tcont
> friend class CargoList
;
68 friend class VehicleCargoList
;
69 friend class StationCargoList
;
70 /** We want this to be saved, right? */
71 friend SaveLoadTable
GetCargoPacketDesc();
73 /** Maximum number of items in a single cargo packet. */
74 static const uint16_t MAX_COUNT
= UINT16_MAX
;
77 CargoPacket(StationID first_station
, uint16_t count
, SourceType source_type
, SourceID source_id
);
78 CargoPacket(uint16_t count
, uint16_t periods_in_transit
, StationID first_station
, TileIndex source_xy
, Money feeder_share
);
79 CargoPacket(uint16_t count
, Money feeder_share
, CargoPacket
&original
);
81 /** Destroy the packet. */
84 CargoPacket
*Split(uint new_size
);
85 void Merge(CargoPacket
*cp
);
86 void Reduce(uint count
);
89 * Sets the station where the packet is supposed to go next.
90 * @param next_hop Next station the packet should go to.
92 void SetNextHop(StationID next_hop
)
94 this->next_hop
= next_hop
;
98 * Update for the cargo being loaded on this tile.
100 * When a CargoPacket is created, it is moved to a station. But at that
101 * moment in time it is not known yet at which tile the cargo will be
102 * picked up. As this tile is used for payment information, we delay
103 * setting the source_xy till first pickup, getting a better idea where
104 * a cargo started from.
106 * Further more, we keep track of the amount of tiles the cargo moved
107 * inside a vehicle. This is used in GetDistance() below.
109 * @param tile Tile the cargo is being picked up from.
111 void UpdateLoadingTile(TileIndex tile
)
113 if (this->source_xy
== INVALID_TILE
) {
114 this->source_xy
= tile
;
118 assert(!this->in_vehicle
);
119 this->in_vehicle
= true;
120 #endif /* WITH_ASSERT */
122 /* We want to calculate the vector from tile-unload to tile-load. As
123 * we currently only know the latter, add it. When we know where we unload,
124 * we subtract is, giving us our vector (unload - load). */
125 this->travelled
.x
+= TileX(tile
);
126 this->travelled
.y
+= TileY(tile
);
130 * Update for the cargo being unloaded on this tile.
132 * @param tile Tile the cargo is being dropped off at.
134 void UpdateUnloadingTile(TileIndex tile
)
137 assert(this->in_vehicle
);
138 this->in_vehicle
= false;
139 #endif /* WITH_ASSERT */
141 this->travelled
.x
-= TileX(tile
);
142 this->travelled
.y
-= TileY(tile
);
146 * Adds some feeder share to the packet.
147 * @param new_share Feeder share to be added.
149 void AddFeederShare(Money new_share
)
151 this->feeder_share
+= new_share
;
155 * Gets the number of 'items' in this packet.
156 * @return Item count.
158 inline uint16_t Count() const
164 * Gets the amount of money already paid to earlier vehicles in
166 * @return Feeder share.
168 inline Money
GetFeederShare() const
170 return this->feeder_share
;
174 * Gets part of the amount of money already paid to earlier vehicles in
176 * @param part Amount of cargo to get the share for.
177 * @return Feeder share for the given amount of cargo.
179 inline Money
GetFeederShare(uint part
) const
181 return this->feeder_share
* part
/ static_cast<uint
>(this->count
);
185 * Gets the number of cargo aging periods this cargo has been in transit.
186 * By default a period is 2.5 days (CARGO_AGING_TICKS = 185 ticks), however
187 * vehicle NewGRFs can overide the length of the cargo aging period. The
188 * value is capped at UINT16_MAX.
189 * @return Length this cargo has been in transit.
191 inline uint16_t GetPeriodsInTransit() const
193 return this->periods_in_transit
;
197 * Gets the type of the cargo's source. industry, town or head quarter.
198 * @return Source type.
200 inline SourceType
GetSourceType() const
202 return this->source_type
;
206 * Gets the ID of the cargo's source. An IndustryID, TownID or CompanyID.
209 inline SourceID
GetSourceID() const
211 return this->source_id
;
215 * Gets the ID of the station where the cargo was loaded for the first time.
218 inline StationID
GetFirstStation() const
220 return this->first_station
;
224 * Get the current distance the cargo has traveled.
226 * @param current_tile Current tile of the cargo.
227 * @return uint The distance (in tiles) traveled.
229 inline uint
GetDistance(TileIndex current_tile
) const
231 assert(this->source_xy
!= INVALID_TILE
);
233 assert(this->in_vehicle
);
234 #endif /* WITH_ASSERT */
236 /* Distance is always requested when the cargo is still inside the
237 * vehicle. So first finish the calculation for travelled to
238 * become a vector. */
239 auto local_travelled
= travelled
;
240 local_travelled
.x
-= TileX(current_tile
);
241 local_travelled
.y
-= TileY(current_tile
);
243 /* Cargo-movement is a vector that indicates how much the cargo has
244 * actually traveled in a vehicle. This is the distance you get paid
245 * for. However, one could construct a route where this vector would
246 * be really long. To not overpay the player, cap out at the distance
247 * between source and destination.
249 * This way of calculating is to counter people moving cargo for free
250 * and instantly in stations, where you deliver it in one part of the
251 * station and pick it up in another. By using the actual distance
252 * traveled in a vehicle, using this trick doesn't give you more money.
254 * However, especially in large networks with large transfer station,
255 * etc, one could actually make the route a lot longer. In that case,
256 * use the actual distance between source and destination.
259 uint distance_travelled
= abs(local_travelled
.x
) + abs(local_travelled
.y
);
260 uint distance_source_dest
= DistanceManhattan(this->source_xy
, current_tile
);
261 return std::min(distance_travelled
, distance_source_dest
);
265 * Gets the ID of station the cargo wants to go next.
266 * @return Next station for this packets.
268 inline StationID
GetNextHop() const
270 return this->next_hop
;
273 static void InvalidateAllFrom(SourceType src_type
, SourceID src
);
274 static void InvalidateAllFrom(StationID sid
);
275 static void AfterLoad();
279 * Simple collection class for a list of cargo packets.
280 * @tparam Tinst Actual instantiation of this cargo list.
282 template <class Tinst
, class Tcont
>
285 /** The iterator for our container. */
286 typedef typename
Tcont::iterator Iterator
;
287 /** The reverse iterator for our container. */
288 typedef typename
Tcont::reverse_iterator ReverseIterator
;
289 /** The const iterator for our container. */
290 typedef typename
Tcont::const_iterator ConstIterator
;
291 /** The const reverse iterator for our container. */
292 typedef typename
Tcont::const_reverse_iterator ConstReverseIterator
;
294 /** Kind of actions that could be done with packets on move. */
297 MTA_TRANSFER
= 0, ///< Transfer the cargo to the station.
298 MTA_DELIVER
, ///< Deliver the cargo to some town or industry.
299 MTA_KEEP
, ///< Keep the cargo in the vehicle.
300 MTA_LOAD
, ///< Load the cargo from the station.
302 NUM_MOVE_TO_ACTION
= MTA_END
306 uint count
; ///< Cache for the number of cargo entities.
307 uint64_t cargo_periods_in_transit
; ///< Cache for the sum of number of cargo aging periods in transit of each entity; comparable to man-hours.
309 Tcont packets
; ///< The cargo packets in this list.
311 void AddToCache(const CargoPacket
*cp
);
313 void RemoveFromCache(const CargoPacket
*cp
, uint count
);
315 static bool TryMerge(CargoPacket
*cp
, CargoPacket
*icp
);
318 /** Create the cargo list. */
326 * Returns a pointer to the cargo packet list (so you can iterate over it etc).
327 * @return Pointer to the packet list.
329 inline const Tcont
*Packets() const
331 return &this->packets
;
335 * Returns average number of cargo aging periods in transit for a cargo entity.
336 * @return The before mentioned number.
338 inline uint
PeriodsInTransit() const
340 return this->count
== 0 ? 0 : this->cargo_periods_in_transit
/ this->count
;
343 void InvalidateCache();
346 typedef std::list
<CargoPacket
*> CargoPacketList
;
349 * CargoList that is used for vehicles.
351 class VehicleCargoList
: public CargoList
<VehicleCargoList
, CargoPacketList
> {
353 /** The (direct) parent of this class. */
354 typedef CargoList
<VehicleCargoList
, CargoPacketList
> Parent
;
356 Money feeder_share
; ///< Cache for the feeder share.
357 uint action_counts
[NUM_MOVE_TO_ACTION
]; ///< Counts of cargo to be transferred, delivered, kept and loaded.
359 template<class Taction
>
360 void ShiftCargo(Taction action
);
362 template<class Taction
>
363 void PopCargo(Taction action
);
366 * Assert that the designation counts add up.
368 inline void AssertCountConsistency() const
370 assert(this->action_counts
[MTA_KEEP
] +
371 this->action_counts
[MTA_DELIVER
] +
372 this->action_counts
[MTA_TRANSFER
] +
373 this->action_counts
[MTA_LOAD
] == this->count
);
376 void AddToCache(const CargoPacket
*cp
);
377 void RemoveFromCache(const CargoPacket
*cp
, uint count
);
379 void AddToMeta(const CargoPacket
*cp
, MoveToAction action
);
380 void RemoveFromMeta(const CargoPacket
*cp
, MoveToAction action
, uint count
);
382 static MoveToAction
ChooseAction(const CargoPacket
*cp
, StationID cargo_next
,
383 StationID current_station
, bool accepted
, StationIDStack next_station
);
386 /** The station cargo list needs to control the unloading. */
387 friend class StationCargoList
;
388 /** The super class ought to know what it's doing. */
389 friend class CargoList
<VehicleCargoList
, CargoPacketList
>;
390 /* So we can use private/protected variables in the saveload code */
391 friend class SlVehicleCommon
;
393 friend class CargoShift
;
394 friend class CargoTransfer
;
395 friend class CargoDelivery
;
396 template<class Tsource
>
397 friend class CargoRemoval
;
398 friend class CargoReturn
;
399 friend class VehicleCargoReroute
;
402 * Returns the first station of the first cargo packet in this list.
403 * @return The before mentioned station.
405 inline StationID
GetFirstStation() const
407 return this->count
== 0 ? INVALID_STATION
: this->packets
.front()->first_station
;
411 * Returns total sum of the feeder share for all packets.
412 * @return The before mentioned number.
414 inline Money
GetFeederShare() const
416 return this->feeder_share
;
420 * Returns the amount of cargo designated for a given purpose.
421 * @param action Action the cargo is designated for.
422 * @return Amount of cargo designated for the given action.
424 inline uint
ActionCount(MoveToAction action
) const
426 return this->action_counts
[action
];
430 * Returns sum of cargo on board the vehicle (ie not only
432 * @return Cargo on board the vehicle.
434 inline uint
StoredCount() const
436 return this->count
- this->action_counts
[MTA_LOAD
];
440 * Returns sum of cargo, including reserved cargo.
441 * @return Sum of cargo.
443 inline uint
TotalCount() const
449 * Returns sum of reserved cargo.
450 * @return Sum of reserved cargo.
452 inline uint
ReservedCount() const
454 return this->action_counts
[MTA_LOAD
];
458 * Returns sum of cargo to be moved out of the vehicle at the current station.
459 * @return Cargo to be moved.
461 inline uint
UnloadCount() const
463 return this->action_counts
[MTA_TRANSFER
] + this->action_counts
[MTA_DELIVER
];
467 * Returns the sum of cargo to be kept in the vehicle at the current station.
468 * @return Cargo to be kept or loaded.
470 inline uint
RemainingCount() const
472 return this->action_counts
[MTA_KEEP
] + this->action_counts
[MTA_LOAD
];
475 void Append(CargoPacket
*cp
, MoveToAction action
= MTA_KEEP
);
479 void InvalidateCache();
481 bool Stage(bool accepted
, StationID current_station
, StationIDStack next_station
, uint8_t order_flags
, const GoodsEntry
*ge
, CargoPayment
*payment
, TileIndex current_tile
);
484 * Marks all cargo in the vehicle as to be kept. This is mostly useful for
485 * loading old savegames. When loading is aborted the reserved cargo has
486 * to be returned first.
488 inline void KeepAll()
490 this->action_counts
[MTA_DELIVER
] = this->action_counts
[MTA_TRANSFER
] = this->action_counts
[MTA_LOAD
] = 0;
491 this->action_counts
[MTA_KEEP
] = this->count
;
494 /* Methods for moving cargo around. First parameter is always maximum
495 * amount of cargo to be moved. Second parameter is destination (if
496 * applicable), return value is amount of cargo actually moved. */
498 template<MoveToAction Tfrom
, MoveToAction Tto
>
499 uint
Reassign(uint max_move
);
500 uint
Return(uint max_move
, StationCargoList
*dest
, StationID next_station
, TileIndex current_tile
);
501 uint
Unload(uint max_move
, StationCargoList
*dest
, CargoPayment
*payment
, TileIndex current_tile
);
502 uint
Shift(uint max_move
, VehicleCargoList
*dest
);
503 uint
Truncate(uint max_move
= UINT_MAX
);
504 uint
Reroute(uint max_move
, VehicleCargoList
*dest
, StationID avoid
, StationID avoid2
, const GoodsEntry
*ge
);
507 * Are the two CargoPackets mergeable in the context of
508 * a list of CargoPackets for a Vehicle?
509 * @param cp1 First CargoPacket.
510 * @param cp2 Second CargoPacket.
511 * @return True if they are mergeable.
513 static bool AreMergable(const CargoPacket
*cp1
, const CargoPacket
*cp2
)
515 return cp1
->source_xy
== cp2
->source_xy
&&
516 cp1
->periods_in_transit
== cp2
->periods_in_transit
&&
517 cp1
->source_type
== cp2
->source_type
&&
518 cp1
->first_station
== cp2
->first_station
&&
519 cp1
->source_id
== cp2
->source_id
;
523 typedef MultiMap
<StationID
, CargoPacket
*> StationCargoPacketMap
;
524 typedef std::map
<StationID
, uint
> StationCargoAmountMap
;
527 * CargoList that is used for stations.
529 class StationCargoList
: public CargoList
<StationCargoList
, StationCargoPacketMap
> {
531 /** The (direct) parent of this class. */
532 typedef CargoList
<StationCargoList
, StationCargoPacketMap
> Parent
;
534 uint reserved_count
; ///< Amount of cargo being reserved for loading.
537 /** The super class ought to know what it's doing. */
538 friend class CargoList
<StationCargoList
, StationCargoPacketMap
>;
539 /* So we can use private/protected variables in the saveload code */
540 friend class SlStationGoods
;
542 friend class CargoLoad
;
543 friend class CargoTransfer
;
544 template<class Tsource
>
545 friend class CargoRemoval
;
546 friend class CargoReservation
;
547 friend class CargoReturn
;
548 friend class StationCargoReroute
;
550 static void InvalidateAllFrom(SourceType src_type
, SourceID src
);
552 template<class Taction
>
553 bool ShiftCargo(Taction
&action
, StationID next
);
555 template<class Taction
>
556 uint
ShiftCargo(Taction action
, StationIDStack next
, bool include_invalid
);
558 void Append(CargoPacket
*cp
, StationID next
);
561 * Check for cargo headed for a specific station.
562 * @param next Station the cargo is headed for.
563 * @return If there is any cargo for that station.
565 inline bool HasCargoFor(StationIDStack next
) const
567 while (!next
.IsEmpty()) {
568 if (this->packets
.find(next
.Pop()) != this->packets
.end()) return true;
570 /* Packets for INVALID_STATION can go anywhere. */
571 return this->packets
.find(INVALID_STATION
) != this->packets
.end();
575 * Returns first station of the first cargo packet in this list.
576 * @return The before mentioned station.
578 inline StationID
GetFirstStation() const
580 return this->count
== 0 ? INVALID_STATION
: this->packets
.begin()->second
.front()->first_station
;
584 * Returns sum of cargo still available for loading at the sation.
585 * (i.e. not counting cargo which is already reserved for loading)
586 * @return Cargo on board the vehicle.
588 inline uint
AvailableCount() const
594 * Returns sum of cargo reserved for loading onto vehicles.
595 * @return Cargo reserved for loading.
597 inline uint
ReservedCount() const
599 return this->reserved_count
;
603 * Returns total count of cargo at the station, including
604 * cargo which is already reserved for loading.
605 * @return Total cargo count.
607 inline uint
TotalCount() const
609 return this->count
+ this->reserved_count
;
612 /* Methods for moving cargo around. First parameter is always maximum
613 * amount of cargo to be moved. Second parameter is destination (if
614 * applicable), return value is amount of cargo actually moved. */
616 uint
Reserve(uint max_move
, VehicleCargoList
*dest
, StationIDStack next
, TileIndex current_tile
);
617 uint
Load(uint max_move
, VehicleCargoList
*dest
, StationIDStack next
, TileIndex current_tile
);
618 uint
Truncate(uint max_move
= UINT_MAX
, StationCargoAmountMap
*cargo_per_source
= nullptr);
619 uint
Reroute(uint max_move
, StationCargoList
*dest
, StationID avoid
, StationID avoid2
, const GoodsEntry
*ge
);
622 * Are the two CargoPackets mergeable in the context of
623 * a list of CargoPackets for a Station?
624 * @param cp1 First CargoPacket.
625 * @param cp2 Second CargoPacket.
626 * @return True if they are mergeable.
628 static bool AreMergable(const CargoPacket
*cp1
, const CargoPacket
*cp2
)
630 return cp1
->source_xy
== cp2
->source_xy
&&
631 cp1
->periods_in_transit
== cp2
->periods_in_transit
&&
632 cp1
->source_type
== cp2
->source_type
&&
633 cp1
->first_station
== cp2
->first_station
&&
634 cp1
->source_id
== cp2
->source_id
;
638 #endif /* CARGOPACKET_H */