Rework the way the ReinitSeparation command is called. The old way was way too danger...
[openttd-joker.git] / src / cargopacket.h
blob8130652dba509c3b3948c9d0f22b8d8e44ef19c4
1 /* $Id: cargopacket.h 26327 2014-02-09 21:10:25Z fonsinchen $ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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 */
10 /** @file cargopacket.h Base class for cargo packets. */
12 #ifndef CARGOPACKET_H
13 #define CARGOPACKET_H
15 #include "core/pool_type.hpp"
16 #include "economy_type.h"
17 #include "station_type.h"
18 #include "order_type.h"
19 #include "cargo_type.h"
20 #include "vehicle_type.h"
21 #include "core/multimap.hpp"
22 #include <deque>
24 /** Unique identifier for a single cargo packet. */
25 typedef uint32 CargoPacketID;
26 struct CargoPacket;
28 /** Type of the pool for cargo packets for a little over 16 million packets. */
29 typedef Pool<CargoPacket, CargoPacketID, 1024, 0xFFF000, PT_NORMAL, true, false> CargoPacketPool;
30 /** The actual pool with cargo packets. */
31 extern CargoPacketPool _cargopacket_pool;
33 struct GoodsEntry; // forward-declare for Stage() and RerouteStalePackets()
35 template <class Tinst, class Tcont> class CargoList;
36 class StationCargoList; // forward-declare, so we can use it in VehicleCargoList.
37 extern const struct SaveLoad *GetCargoPacketDesc();
39 typedef uint32 TileOrStationID;
41 /**
42 * Container for cargo from the same location and time.
44 struct CargoPacket : CargoPacketPool::PoolItem<&_cargopacket_pool> {
45 private:
46 Money feeder_share; ///< Value of feeder pickup to be paid for on delivery of cargo.
47 uint16 count; ///< The amount of cargo in this packet.
48 byte days_in_transit; ///< Amount of days this packet has been in transit.
49 SourceTypeByte source_type; ///< Type of \c source_id.
50 SourceID source_id; ///< Index of source, INVALID_SOURCE if unknown/invalid.
51 StationID source; ///< The station where the cargo came from first.
52 TileIndex source_xy; ///< The origin of the cargo (first station in feeder chain).
53 union {
54 TileOrStationID loaded_at_xy; ///< Location where this cargo has been loaded into the vehicle.
55 TileOrStationID next_station; ///< Station where the cargo wants to go next.
58 /** The CargoList caches, thus needs to know about it. */
59 template <class Tinst, class Tcont> friend class CargoList;
60 friend class VehicleCargoList;
61 friend class StationCargoList;
62 /** We want this to be saved, right? */
63 friend const struct SaveLoad *GetCargoPacketDesc();
64 public:
65 /** Maximum number of items in a single cargo packet. */
66 static const uint16 MAX_COUNT = UINT16_MAX;
68 CargoPacket();
69 CargoPacket(StationID source, TileIndex source_xy, uint16 count, SourceType source_type, SourceID source_id);
70 CargoPacket(uint16 count, byte days_in_transit, StationID source, TileIndex source_xy, TileIndex loaded_at_xy, Money feeder_share = 0, SourceType source_type = ST_INDUSTRY, SourceID source_id = INVALID_SOURCE);
72 /** Destroy the packet. */
73 ~CargoPacket() { }
75 CargoPacket *Split(uint new_size);
76 void Merge(CargoPacket *cp);
77 void Reduce(uint count);
79 /**
80 * Sets the tile where the packet was loaded last.
81 * @param load_place Tile where the packet was loaded last.
83 void SetLoadPlace(TileIndex load_place) { this->loaded_at_xy = load_place; }
85 /**
86 * Sets the station where the packet is supposed to go next.
87 * @param next_station Next station the packet should go to.
89 void SetNextStation(StationID next_station) { this->next_station = next_station; }
91 /**
92 * Adds some feeder share to the packet.
93 * @param new_share Feeder share to be added.
95 void AddFeederShare(Money new_share) { this->feeder_share += new_share; }
97 /**
98 * Gets the number of 'items' in this packet.
99 * @return Item count.
101 inline uint16 Count() const
103 return this->count;
107 * Gets the amount of money already paid to earlier vehicles in
108 * the feeder chain.
109 * @return Feeder share.
111 inline Money FeederShare() const
113 return this->feeder_share;
117 * Gets part of the amount of money already paid to earlier vehicles in
118 * the feeder chain.
119 * @param part Amount of cargo to get the share for.
120 * @return Feeder share for the given amount of cargo.
122 inline Money FeederShare(uint part) const
124 return this->feeder_share * part / static_cast<uint>(this->count);
128 * Gets the number of days this cargo has been in transit.
129 * This number isn't really in days, but in 2.5 days (CARGO_AGING_TICKS = 185 ticks) and
130 * it is capped at 255.
131 * @return Length this cargo has been in transit.
133 inline byte DaysInTransit() const
135 return this->days_in_transit;
139 * Resets the number of days this cargo has been in transit.
141 inline void ResetTransitDays()
143 this->days_in_transit = 0x00;
147 * Gets the type of the cargo's source. industry, town or head quarter.
148 * @return Source type.
150 inline SourceType SourceSubsidyType() const
152 return this->source_type;
156 * Gets the ID of the cargo's source. An IndustryID, TownID or CompanyID.
157 * @return Source ID.
159 inline SourceID SourceSubsidyID() const
161 return this->source_id;
165 * Gets the ID of the station where the cargo was loaded for the first time.
166 * @return StationID.
168 inline StationID SourceStation() const
170 return this->source;
174 * Gets the coordinates of the cargo's source station.
175 * @return Source station's coordinates.
177 inline TileIndex SourceStationXY() const
179 return this->source_xy;
183 * Gets the coordinates of the cargo's last loading station.
184 * @return Last loading station's coordinates.
186 inline TileIndex LoadedAtXY() const
188 return this->loaded_at_xy;
192 * Gets the ID of station the cargo wants to go next.
193 * @return Next station for this packets.
195 inline StationID NextStation() const
197 return this->next_station;
200 static void InvalidateAllFrom(SourceType src_type, SourceID src);
201 static void InvalidateAllFrom(StationID sid);
202 static void AfterLoad();
206 * Iterate over all _valid_ cargo packets from the given start.
207 * @param var Variable used as "iterator".
208 * @param start Cargo packet ID of the first packet to iterate over.
210 #define FOR_ALL_CARGOPACKETS_FROM(var, start) FOR_ALL_ITEMS_FROM(CargoPacket, cargopacket_index, var, start)
213 * Iterate over all _valid_ cargo packets from the begin of the pool.
214 * @param var Variable used as "iterator".
216 #define FOR_ALL_CARGOPACKETS(var) FOR_ALL_CARGOPACKETS_FROM(var, 0)
219 * Simple collection class for a list of cargo packets.
220 * @tparam Tinst Actual instantiation of this cargo list.
222 template <class Tinst, class Tcont>
223 class CargoList {
224 public:
225 /** The iterator for our container. */
226 typedef typename Tcont::iterator Iterator;
227 /** The reverse iterator for our container. */
228 typedef typename Tcont::reverse_iterator ReverseIterator;
229 /** The const iterator for our container. */
230 typedef typename Tcont::const_iterator ConstIterator;
231 /** The const reverse iterator for our container. */
232 typedef typename Tcont::const_reverse_iterator ConstReverseIterator;
234 /** Kind of actions that could be done with packets on move. */
235 enum MoveToAction {
236 MTA_BEGIN = 0,
237 MTA_TRANSFER = 0, ///< Transfer the cargo to the station.
238 MTA_DELIVER, ///< Deliver the cargo to some town or industry.
239 MTA_KEEP, ///< Keep the cargo in the vehicle.
240 MTA_LOAD, ///< Load the cargo from the station.
241 MTA_END,
242 NUM_MOVE_TO_ACTION = MTA_END
245 protected:
246 uint count; ///< Cache for the number of cargo entities.
247 uint cargo_days_in_transit; ///< Cache for the sum of number of days in transit of each entity; comparable to man-hours.
249 Tcont packets; ///< The cargo packets in this list.
251 void AddToCache(const CargoPacket *cp);
253 void RemoveFromCache(const CargoPacket *cp, uint count);
255 static bool TryMerge(CargoPacket *cp, CargoPacket *icp);
257 public:
258 /** Create the cargo list. */
259 CargoList() {}
261 ~CargoList();
263 void OnCleanPool();
266 * Returns a pointer to the cargo packet list (so you can iterate over it etc).
267 * @return Pointer to the packet list.
269 inline const Tcont *Packets() const
271 return &this->packets;
275 * Returns average number of days in transit for a cargo entity.
276 * @return The before mentioned number.
278 inline uint DaysInTransit() const
280 return this->count == 0 ? 0 : this->cargo_days_in_transit / this->count;
283 void InvalidateCache();
286 typedef std::deque<CargoPacket *> CargoPacketList;
289 * CargoList that is used for vehicles.
291 class VehicleCargoList : public CargoList<VehicleCargoList, CargoPacketList> {
292 protected:
293 /** The (direct) parent of this class. */
294 typedef CargoList<VehicleCargoList, CargoPacketList> Parent;
296 Money feeder_share; ///< Cache for the feeder share.
297 uint action_counts[NUM_MOVE_TO_ACTION]; ///< Counts of cargo to be transfered, delivered, kept and loaded.
299 template<class Taction>
300 void ShiftCargo(Taction action);
302 template<class Taction>
303 void PopCargo(Taction action);
306 * Assert that the designation counts add up.
308 inline void AssertCountConsistency() const
310 assert(this->action_counts[MTA_KEEP] +
311 this->action_counts[MTA_DELIVER] +
312 this->action_counts[MTA_TRANSFER] +
313 this->action_counts[MTA_LOAD] == this->count);
316 void AddToCache(const CargoPacket *cp);
317 void RemoveFromCache(const CargoPacket *cp, uint count);
319 void AddToMeta(const CargoPacket *cp, MoveToAction action);
320 void RemoveFromMeta(const CargoPacket *cp, MoveToAction action, uint count);
322 static MoveToAction ChooseAction(const CargoPacket *cp, StationID cargo_next,
323 StationID current_station, bool accepted, StationIDStack next_station);
325 public:
326 /** The station cargo list needs to control the unloading. */
327 friend class StationCargoList;
328 /** The super class ought to know what it's doing. */
329 friend class CargoList<VehicleCargoList, CargoPacketList>;
330 /** The vehicles have a cargo list (and we want that saved). */
331 friend const struct SaveLoad *GetVehicleDescription(VehicleType vt);
333 friend class CargoShift;
334 friend class CargoTransfer;
335 friend class CargoDelivery;
336 template<class Tsource>
337 friend class CargoRemoval;
338 friend class CargoReturn;
339 friend class VehicleCargoReroute;
342 * Returns source of the first cargo packet in this list.
343 * @return The before mentioned source.
345 inline StationID Source() const
347 return this->count == 0 ? INVALID_STATION : this->packets.front()->source;
351 * Returns total sum of the feeder share for all packets.
352 * @return The before mentioned number.
354 inline Money FeederShare() const
356 return this->feeder_share;
360 * Returns the amount of cargo designated for a given purpose.
361 * @param action Action the cargo is designated for.
362 * @return Amount of cargo designated for the given action.
364 inline uint ActionCount(MoveToAction action) const
366 return this->action_counts[action];
370 * Returns sum of cargo on board the vehicle (ie not only
371 * reserved).
372 * @return Cargo on board the vehicle.
374 inline uint StoredCount() const
376 return this->count - this->action_counts[MTA_LOAD];
380 * Returns sum of cargo, including reserved cargo.
381 * @return Sum of cargo.
383 inline uint TotalCount() const
385 return this->count;
389 * Returns sum of reserved cargo.
390 * @return Sum of reserved cargo.
392 inline uint ReservedCount() const
394 return this->action_counts[MTA_LOAD];
398 * Returns sum of cargo to be moved out of the vehicle at the current station.
399 * @return Cargo to be moved.
401 inline uint UnloadCount() const
403 return this->action_counts[MTA_TRANSFER] + this->action_counts[MTA_DELIVER];
407 * Returns the sum of cargo to be kept in the vehicle at the current station.
408 * @return Cargo to be kept or loaded.
410 inline uint RemainingCount() const
412 return this->action_counts[MTA_KEEP] + this->action_counts[MTA_LOAD];
415 void Append(CargoPacket *cp, MoveToAction action = MTA_KEEP);
417 void AgeCargo();
419 void InvalidateCache();
421 void SetTransferLoadPlace(TileIndex xy);
423 bool Stage(bool accepted, StationID current_station, StationIDStack next_station, uint8 order_flags, const GoodsEntry *ge, CargoPayment *payment);
426 * Marks all cargo in the vehicle as to be kept. This is mostly useful for
427 * loading old savegames. When loading is aborted the reserved cargo has
428 * to be returned first.
430 inline void KeepAll()
432 this->action_counts[MTA_DELIVER] = this->action_counts[MTA_TRANSFER] = this->action_counts[MTA_LOAD] = 0;
433 this->action_counts[MTA_KEEP] = this->count;
436 /* Methods for moving cargo around. First parameter is always maximum
437 * amount of cargo to be moved. Second parameter is destination (if
438 * applicable), return value is amount of cargo actually moved. */
440 template<MoveToAction Tfrom, MoveToAction Tto>
441 uint Reassign(uint max_move, TileOrStationID update = INVALID_TILE);
442 uint Return(uint max_move, StationCargoList *dest, StationID next_station);
443 uint Unload(uint max_move, StationCargoList *dest, CargoPayment *payment);
444 uint Shift(uint max_move, VehicleCargoList *dest);
445 uint Truncate(uint max_move = UINT_MAX);
446 uint Reroute(uint max_move, VehicleCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge);
449 * Are two the two CargoPackets mergeable in the context of
450 * a list of CargoPackets for a Vehicle?
451 * @param cp1 First CargoPacket.
452 * @param cp2 Second CargoPacket.
453 * @return True if they are mergeable.
455 static bool AreMergable(const CargoPacket *cp1, const CargoPacket *cp2)
457 return cp1->source_xy == cp2->source_xy &&
458 cp1->days_in_transit == cp2->days_in_transit &&
459 cp1->source_type == cp2->source_type &&
460 cp1->source_id == cp2->source_id &&
461 cp1->loaded_at_xy == cp2->loaded_at_xy;
465 typedef MultiMap<StationID, CargoPacket *, CargoPacketList> StationCargoPacketMap;
466 typedef std::map<StationID, uint> StationCargoAmountMap;
469 * CargoList that is used for stations.
471 class StationCargoList : public CargoList<StationCargoList, StationCargoPacketMap> {
472 protected:
473 /** The (direct) parent of this class. */
474 typedef CargoList<StationCargoList, StationCargoPacketMap> Parent;
476 uint reserved_count; ///< Amount of cargo being reserved for loading.
478 public:
479 /** The super class ought to know what it's doing. */
480 friend class CargoList<StationCargoList, StationCargoPacketMap>;
481 /** The stations, via GoodsEntry, have a CargoList. */
482 friend const struct SaveLoad *GetGoodsDesc();
484 friend class CargoLoad;
485 friend class CargoTransfer;
486 template<class Tsource>
487 friend class CargoRemoval;
488 friend class CargoReservation;
489 friend class CargoReturn;
490 friend class StationCargoReroute;
492 static void InvalidateAllFrom(SourceType src_type, SourceID src);
494 template<class Taction>
495 bool ShiftCargo(Taction &action, StationID next);
497 template<class Taction>
498 uint ShiftCargo(Taction action, StationIDStack next, bool include_invalid);
500 void Append(CargoPacket *cp, StationID next);
503 * Check for cargo headed for a specific station.
504 * @param next Station the cargo is headed for.
505 * @return If there is any cargo for that station.
507 inline bool HasCargoFor(StationIDStack next) const
509 while (!next.IsEmpty()) {
510 if (this->packets.find(next.Pop()) != this->packets.end()) return true;
512 /* Packets for INVALID_STTION can go anywhere. */
513 return this->packets.find(INVALID_STATION) != this->packets.end();
517 * Returns source of the first cargo packet in this list.
518 * @return The before mentioned source.
520 inline StationID Source() const
522 return this->count == 0 ? INVALID_STATION : this->packets.begin()->second.front()->source;
526 * Returns sum of cargo still available for loading at the sation.
527 * (i.e. not counting cargo which is already reserved for loading)
528 * @return Cargo on board the vehicle.
530 inline uint AvailableCount() const
532 return this->count;
536 * Returns sum of cargo reserved for loading onto vehicles.
537 * @return Cargo reserved for loading.
539 inline uint ReservedCount() const
541 return this->reserved_count;
545 * Returns total count of cargo at the station, including
546 * cargo which is already reserved for loading.
547 * @return Total cargo count.
549 inline uint TotalCount() const
551 return this->count + this->reserved_count;
554 /* Methods for moving cargo around. First parameter is always maximum
555 * amount of cargo to be moved. Second parameter is destination (if
556 * applicable), return value is amount of cargo actually moved. */
558 uint Reserve(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next);
559 uint Load(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next);
560 uint Truncate(uint max_move = UINT_MAX, StationCargoAmountMap *cargo_per_source = nullptr);
561 uint Reroute(uint max_move, StationCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge);
564 * Are two the two CargoPackets mergeable in the context of
565 * a list of CargoPackets for a Vehicle?
566 * @param cp1 First CargoPacket.
567 * @param cp2 Second CargoPacket.
568 * @return True if they are mergeable.
570 static bool AreMergable(const CargoPacket *cp1, const CargoPacket *cp2)
572 return cp1->source_xy == cp2->source_xy &&
573 cp1->days_in_transit == cp2->days_in_transit &&
574 cp1->source_type == cp2->source_type &&
575 cp1->source_id == cp2->source_id;
579 #endif /* CARGOPACKET_H */