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/>.
10 /** @file cargopacket.cpp Implementation of the cargo packets. */
13 #include "station_base.h"
14 #include "core/pool_func.hpp"
15 #include "core/random_func.hpp"
16 #include "economy_base.h"
17 #include "cargoaction.h"
18 #include "order_type.h"
22 #include "safeguards.h"
24 /* Initialize the cargopacket-pool */
25 CargoPacketPool
_cargopacket_pool("CargoPacket");
26 INSTANTIATE_POOL_METHODS(CargoPacket
)
29 * Create a new packet for savegame loading.
31 CargoPacket::CargoPacket()
33 this->source_type
= ST_INDUSTRY
;
34 this->source_id
= INVALID_SOURCE
;
38 * Creates a new cargo packet.
39 * @param source Source station of the packet.
40 * @param source_xy Source location of the packet.
41 * @param count Number of cargo entities to put in this packet.
42 * @param source_type 'Type' of source the packet comes from (for subsidies).
43 * @param source_id Actual source of the packet (for subsidies).
45 * @note We have to zero memory ourselves here because we are using a 'new'
46 * that, in contrary to all other pools, does not memset to 0.
48 CargoPacket::CargoPacket(StationID source
, TileIndex source_xy
, uint16 count
, SourceType source_type
, SourceID source_id
) :
58 this->source_type
= source_type
;
62 * Creates a new cargo packet. Initializes the fields that cannot be changed later.
63 * Used when loading or splitting packets.
64 * @param count Number of cargo entities to put in this packet.
65 * @param days_in_transit Number of days the cargo has been in transit.
66 * @param source Station the cargo was initially loaded.
67 * @param source_xy Station location the cargo was initially loaded.
68 * @param loaded_at_xy Location the cargo was loaded last.
69 * @param feeder_share Feeder share the packet has already accumulated.
70 * @param source_type 'Type' of source the packet comes from (for subsidies).
71 * @param source_id Actual source of the packet (for subsidies).
72 * @note We have to zero memory ourselves here because we are using a 'new'
73 * that, in contrary to all other pools, does not memset to 0.
75 CargoPacket::CargoPacket(uint16 count
, byte days_in_transit
, StationID source
, TileIndex source_xy
, TileIndex loaded_at_xy
, Money feeder_share
, SourceType source_type
, SourceID source_id
) :
76 feeder_share(feeder_share
),
78 days_in_transit(days_in_transit
),
82 loaded_at_xy(loaded_at_xy
)
85 this->source_type
= source_type
;
89 * Split this packet in two and return the split off part.
90 * @param new_size Size of the split part.
91 * @return Split off part, or NULL if no packet could be allocated!
93 CargoPacket
*CargoPacket::Split(uint new_size
)
95 if (!CargoPacket::CanAllocateItem()) return NULL
;
97 Money fs
= this->FeederShare(new_size
);
98 CargoPacket
*cp_new
= new CargoPacket(new_size
, this->days_in_transit
, this->source
, this->source_xy
, this->loaded_at_xy
, fs
, this->source_type
, this->source_id
);
99 this->feeder_share
-= fs
;
100 this->count
-= new_size
;
105 * Merge another packet into this one.
106 * @param cp Packet to be merged in.
108 void CargoPacket::Merge(CargoPacket
*cp
)
110 this->count
+= cp
->count
;
111 this->feeder_share
+= cp
->feeder_share
;
116 * Reduce the packet by the given amount and remove the feeder share.
117 * @param count Amount to be removed.
119 void CargoPacket::Reduce(uint count
)
121 assert(count
< this->count
);
122 this->feeder_share
-= this->FeederShare(count
);
123 this->count
-= count
;
127 * Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
128 * @param src_type Type of source.
129 * @param src Index of source.
131 /* static */ void CargoPacket::InvalidateAllFrom(SourceType src_type
, SourceID src
)
134 FOR_ALL_CARGOPACKETS(cp
) {
135 if (cp
->source_type
== src_type
&& cp
->source_id
== src
) cp
->source_id
= INVALID_SOURCE
;
140 * Invalidates (sets source to INVALID_STATION) all cargo packets from given station.
141 * @param sid Station that gets removed.
143 /* static */ void CargoPacket::InvalidateAllFrom(StationID sid
)
146 FOR_ALL_CARGOPACKETS(cp
) {
147 if (cp
->source
== sid
) cp
->source
= INVALID_STATION
;
153 * Cargo list implementation
158 * Destroy the cargolist ("frees" all cargo packets).
160 template <class Tinst
, class Tcont
>
161 CargoList
<Tinst
, Tcont
>::~CargoList()
163 for (Iterator
it(this->packets
.begin()); it
!= this->packets
.end(); ++it
) {
169 * Empty the cargo list, but don't free the cargo packets;
170 * the cargo packets are cleaned by CargoPacket's CleanPool.
172 template <class Tinst
, class Tcont
>
173 void CargoList
<Tinst
, Tcont
>::OnCleanPool()
175 this->packets
.clear();
179 * Update the cached values to reflect the removal of this packet or part of it.
180 * Decreases count and days_in_transit.
181 * @param cp Packet to be removed from cache.
182 * @param count Amount of cargo from the given packet to be removed.
184 template <class Tinst
, class Tcont
>
185 void CargoList
<Tinst
, Tcont
>::RemoveFromCache(const CargoPacket
*cp
, uint count
)
187 assert(count
<= cp
->count
);
188 this->count
-= count
;
189 this->cargo_days_in_transit
-= cp
->days_in_transit
* count
;
193 * Update the cache to reflect adding of this packet.
194 * Increases count and days_in_transit.
195 * @param cp New packet to be inserted.
197 template <class Tinst
, class Tcont
>
198 void CargoList
<Tinst
, Tcont
>::AddToCache(const CargoPacket
*cp
)
200 this->count
+= cp
->count
;
201 this->cargo_days_in_transit
+= cp
->days_in_transit
* cp
->count
;
204 /** Invalidates the cached data and rebuilds it. */
205 template <class Tinst
, class Tcont
>
206 void CargoList
<Tinst
, Tcont
>::InvalidateCache()
209 this->cargo_days_in_transit
= 0;
211 for (ConstIterator
it(this->packets
.begin()); it
!= this->packets
.end(); it
++) {
212 static_cast<Tinst
*>(this)->AddToCache(*it
);
217 * Tries to merge the second packet into the first and return if that was
219 * @param icp Packet to be merged into.
220 * @param cp Packet to be eliminated.
221 * @return If the packets could be merged.
223 template <class Tinst
, class Tcont
>
224 /* static */ bool CargoList
<Tinst
, Tcont
>::TryMerge(CargoPacket
*icp
, CargoPacket
*cp
)
226 if (Tinst::AreMergable(icp
, cp
) &&
227 icp
->count
+ cp
->count
<= CargoPacket::MAX_COUNT
) {
237 * Vehicle cargo list implementation.
242 * Appends the given cargo packet. Tries to merge it with another one in the
243 * packets list. If no fitting packet is found, appends it. You can only append
244 * packets to the ranges of packets designated for keeping or loading.
245 * Furthermore if there are already packets reserved for loading you cannot
246 * directly add packets to the "keep" list. You first have to load the reserved
248 * @warning After appending this packet may not exist anymore!
249 * @note Do not use the cargo packet anymore after it has been appended to this CargoList!
250 * @param cp Cargo packet to add.
251 * @param action Either MTA_KEEP if you want to add the packet directly or MTA_LOAD
252 * if you want to reserve it first.
254 * @pre action == MTA_LOAD || (action == MTA_KEEP && this->designation_counts[MTA_LOAD] == 0)
256 void VehicleCargoList::Append(CargoPacket
*cp
, MoveToAction action
)
259 assert(action
== MTA_LOAD
||
260 (action
== MTA_KEEP
&& this->action_counts
[MTA_LOAD
] == 0));
261 this->AddToMeta(cp
, action
);
263 if (this->count
== cp
->count
) {
264 this->packets
.push_back(cp
);
268 uint sum
= cp
->count
;
269 for (ReverseIterator
it(this->packets
.rbegin()); it
!= this->packets
.rend(); it
++) {
270 CargoPacket
*icp
= *it
;
271 if (VehicleCargoList::TryMerge(icp
, cp
)) return;
273 if (sum
>= this->action_counts
[action
]) {
274 this->packets
.push_back(cp
);
283 * Shifts cargo from the front of the packet list and applies some action to it.
284 * @tparam Taction Action class or function to be used. It should define
285 * "bool operator()(CargoPacket *)". If true is returned the
286 * cargo packet will be removed from the list. Otherwise it
287 * will be kept and the loop will be aborted.
288 * @param action Action instance to be applied.
290 template<class Taction
>
291 void VehicleCargoList::ShiftCargo(Taction action
)
293 Iterator
it(this->packets
.begin());
294 while (it
!= this->packets
.end() && action
.MaxMove() > 0) {
295 CargoPacket
*cp
= *it
;
297 it
= this->packets
.erase(it
);
305 * Pops cargo from the back of the packet list and applies some action to it.
306 * @tparam Taction Action class or function to be used. It should define
307 * "bool operator()(CargoPacket *)". If true is returned the
308 * cargo packet will be removed from the list. Otherwise it
309 * will be kept and the loop will be aborted.
310 * @param action Action instance to be applied.
312 template<class Taction
>
313 void VehicleCargoList::PopCargo(Taction action
)
315 if (this->packets
.empty()) return;
316 for (auto it
= this->packets
.end(); it
!= this->packets
.begin();) {
317 if (action
.MaxMove() <= 0) break;
319 CargoPacket
*cp
= *it
;
321 it
= this->packets
.erase(it
);
329 * Update the cached values to reflect the removal of this packet or part of it.
330 * Decreases count, feeder share and days_in_transit.
331 * @param cp Packet to be removed from cache.
332 * @param count Amount of cargo from the given packet to be removed.
334 void VehicleCargoList::RemoveFromCache(const CargoPacket
*cp
, uint count
)
336 this->feeder_share
-= cp
->FeederShare(count
);
337 this->Parent::RemoveFromCache(cp
, count
);
341 * Update the cache to reflect adding of this packet.
342 * Increases count, feeder share and days_in_transit.
343 * @param cp New packet to be inserted.
345 void VehicleCargoList::AddToCache(const CargoPacket
*cp
)
347 this->feeder_share
+= cp
->feeder_share
;
348 this->Parent::AddToCache(cp
);
352 * Removes a packet or part of it from the metadata.
353 * @param cp Packet to be removed.
354 * @param action MoveToAction of the packet (for updating the counts).
355 * @param count Amount of cargo to be removed.
357 void VehicleCargoList::RemoveFromMeta(const CargoPacket
*cp
, MoveToAction action
, uint count
)
359 assert(count
<= this->action_counts
[action
]);
360 this->AssertCountConsistency();
361 this->RemoveFromCache(cp
, count
);
362 this->action_counts
[action
] -= count
;
363 this->AssertCountConsistency();
367 * Adds a packet to the metadata.
368 * @param cp Packet to be added.
369 * @param action MoveToAction of the packet.
371 void VehicleCargoList::AddToMeta(const CargoPacket
*cp
, MoveToAction action
)
373 this->AssertCountConsistency();
374 this->AddToCache(cp
);
375 this->action_counts
[action
] += cp
->count
;
376 this->AssertCountConsistency();
380 * Ages the all cargo in this list.
382 void VehicleCargoList::AgeCargo()
384 for (ConstIterator
it(this->packets
.begin()); it
!= this->packets
.end(); it
++) {
385 CargoPacket
*cp
= *it
;
386 /* If we're at the maximum, then we can't increase no more. */
387 if (cp
->days_in_transit
== 0xFF) continue;
389 cp
->days_in_transit
++;
390 this->cargo_days_in_transit
+= cp
->count
;
395 * Sets loaded_at_xy to the current station for all cargo to be transfered.
396 * This is done when stopping or skipping while the vehicle is unloading. In
397 * that case the vehicle will get part of its transfer credits early and it may
398 * get more transfer credits than it's entitled to.
399 * @param xy New loaded_at_xy for the cargo.
401 void VehicleCargoList::SetTransferLoadPlace(TileIndex xy
)
404 for (Iterator it
= this->packets
.begin(); sum
< this->action_counts
[MTA_TRANSFER
]; ++it
) {
405 CargoPacket
*cp
= *it
;
406 cp
->loaded_at_xy
= xy
;
412 * Choose action to be performed with the given cargo packet.
413 * @param cp The packet.
414 * @param cargo_next Next hop the cargo wants to pass.
415 * @param current_station Current station of the vehicle carrying the cargo.
416 * @param accepted If the cargo is accepted at the current station.
417 * @param next_station Next station(s) the vehicle may stop at.
418 * @return MoveToAction to be performed.
420 /* static */ VehicleCargoList::MoveToAction
VehicleCargoList::ChooseAction(const CargoPacket
*cp
, StationID cargo_next
,
421 StationID current_station
, bool accepted
, StationIDStack next_station
)
423 if (cargo_next
== INVALID_STATION
) {
424 return (accepted
&& cp
->source
!= current_station
) ? MTA_DELIVER
: MTA_KEEP
;
425 } else if (cargo_next
== current_station
) {
427 } else if (next_station
.Contains(cargo_next
)) {
435 * Stages cargo for unloading. The cargo is sorted so that packets to be
436 * transferred, delivered or kept are in consecutive chunks in the list. At the
437 * same time the designation_counts are updated to reflect the size of those
439 * @param accepted If the cargo will be accepted at the station.
440 * @param current_station ID of the station.
441 * @param next_station ID of the station the vehicle will go to next.
442 * @param order_flags OrderUnloadFlags that will apply to the unload operation.
443 * @param ge GoodsEntry for getting the flows.
444 * @param payment Payment object for registering transfers.
445 * return If any cargo will be unloaded.
447 bool VehicleCargoList::Stage(bool accepted
, StationID current_station
, StationIDStack next_station
, uint8 order_flags
, const GoodsEntry
*ge
, CargoPayment
*payment
)
449 this->AssertCountConsistency();
450 assert(this->action_counts
[MTA_LOAD
] == 0);
451 this->action_counts
[MTA_TRANSFER
] = this->action_counts
[MTA_DELIVER
] = this->action_counts
[MTA_KEEP
] = 0;
452 Iterator it
= this->packets
.begin();
454 CargoPacketList transfer_deliver
;
455 std::vector
<CargoPacket
*> keep
;
457 bool force_keep
= (order_flags
& OUFB_NO_UNLOAD
) != 0;
458 bool force_unload
= (order_flags
& OUFB_UNLOAD
) != 0;
459 bool force_transfer
= (order_flags
& (OUFB_TRANSFER
| OUFB_UNLOAD
)) != 0;
460 assert(this->count
> 0 || it
== this->packets
.end());
461 while (sum
< this->count
) {
462 CargoPacket
*cp
= *it
;
464 it
= this->packets
.erase(it
);
465 StationID cargo_next
= INVALID_STATION
;
466 MoveToAction action
= MTA_LOAD
;
469 } else if (force_unload
&& accepted
&& cp
->source
!= current_station
) {
470 action
= MTA_DELIVER
;
471 } else if (force_transfer
) {
472 action
= MTA_TRANSFER
;
473 /* We cannot send the cargo to any of the possible next hops and
474 * also not to the current station. */
475 FlowStatMap::const_iterator
flow_it(ge
->flows
.find(cp
->source
));
476 if (flow_it
== ge
->flows
.end()) {
477 cargo_next
= INVALID_STATION
;
479 FlowStat new_shares
= flow_it
->second
;
480 new_shares
.ChangeShare(current_station
, INT_MIN
);
481 StationIDStack excluded
= next_station
;
482 while (!excluded
.IsEmpty() && !new_shares
.GetShares()->empty()) {
483 new_shares
.ChangeShare(excluded
.Pop(), INT_MIN
);
485 if (new_shares
.GetShares()->empty()) {
486 cargo_next
= INVALID_STATION
;
488 cargo_next
= new_shares
.GetVia();
492 /* Rewrite an invalid source station to some random other one to
493 * avoid keeping the cargo in the vehicle forever. */
494 if (cp
->source
== INVALID_STATION
&& !ge
->flows
.empty()) {
495 cp
->source
= ge
->flows
.begin()->first
;
497 bool restricted
= false;
498 FlowStatMap::const_iterator
flow_it(ge
->flows
.find(cp
->source
));
499 if (flow_it
== ge
->flows
.end()) {
500 cargo_next
= INVALID_STATION
;
502 cargo_next
= flow_it
->second
.GetViaWithRestricted(restricted
);
504 action
= VehicleCargoList::ChooseAction(cp
, cargo_next
, current_station
, accepted
, next_station
);
505 if (restricted
&& action
== MTA_TRANSFER
) {
506 /* If the flow is restricted we can't transfer to it. Choose an
507 * unrestricted one instead. */
508 cargo_next
= flow_it
->second
.GetVia();
509 action
= VehicleCargoList::ChooseAction(cp
, cargo_next
, current_station
, accepted
, next_station
);
518 transfer_deliver
.push_back(cp
);
521 transfer_deliver
.push_front(cp
);
522 /* Add feeder share here to allow reusing field for next station. */
523 share
= payment
->PayTransfer(cp
, cp
->count
);
524 cp
->AddFeederShare(share
);
525 this->feeder_share
+= share
;
526 cp
->next_station
= cargo_next
;
531 this->action_counts
[action
] += cp
->count
;
534 assert(this->packets
.empty());
535 this->packets
= std::move(transfer_deliver
);
536 this->packets
.insert(this->packets
.end(), keep
.begin(), keep
.end());
537 this->AssertCountConsistency();
538 return this->action_counts
[MTA_DELIVER
] > 0 || this->action_counts
[MTA_TRANSFER
] > 0;
541 /** Invalidates the cached data and rebuild it. */
542 void VehicleCargoList::InvalidateCache()
544 this->feeder_share
= 0;
545 this->Parent::InvalidateCache();
549 * Moves some cargo from one designation to another. You can only move
550 * between adjacent designations. E.g. you can keep cargo that was previously
551 * reserved (MTA_LOAD), but you can't reserve cargo that's marked as to be
552 * delivered. Furthermore, as this method doesn't change the actual packets,
553 * you cannot move cargo from or to MTA_TRANSFER. You need a specialized
554 * template method for that.
555 * @tparam from Previous designation of cargo.
556 * @tparam to New designation of cargo.
557 * @param max_move Maximum amount of cargo to reassign.
558 * @return Amount of cargo actually reassigned.
560 template<VehicleCargoList::MoveToAction Tfrom
, VehicleCargoList::MoveToAction Tto
>
561 uint
VehicleCargoList::Reassign(uint max_move
, TileOrStationID
)
563 assert_tcompile(Tfrom
!= MTA_TRANSFER
&& Tto
!= MTA_TRANSFER
);
564 assert_tcompile(Tfrom
- Tto
== 1 || Tto
- Tfrom
== 1);
565 max_move
= min(this->action_counts
[Tfrom
], max_move
);
566 this->action_counts
[Tfrom
] -= max_move
;
567 this->action_counts
[Tto
] += max_move
;
572 * Reassign cargo from MTA_DELIVER to MTA_TRANSFER and take care of the next
573 * station the cargo wants to visit.
574 * @param max_move Maximum amount of cargo to reassign.
575 * @param next_station Station to record as next hop in the reassigned packets.
576 * @return Amount of cargo actually reassigned.
579 uint
VehicleCargoList::Reassign
<VehicleCargoList::MTA_DELIVER
, VehicleCargoList::MTA_TRANSFER
>(uint max_move
, TileOrStationID next_station
)
581 max_move
= min(this->action_counts
[MTA_DELIVER
], max_move
);
584 for (Iterator
it(this->packets
.begin()); sum
< this->action_counts
[MTA_TRANSFER
] + max_move
;) {
585 CargoPacket
*cp
= *it
++;
587 if (sum
<= this->action_counts
[MTA_TRANSFER
]) continue;
588 if (sum
> this->action_counts
[MTA_TRANSFER
] + max_move
) {
589 CargoPacket
*cp_split
= cp
->Split(sum
- this->action_counts
[MTA_TRANSFER
] + max_move
);
590 sum
-= cp_split
->Count();
591 this->packets
.insert(it
, cp_split
);
593 cp
->next_station
= next_station
;
596 this->action_counts
[MTA_DELIVER
] -= max_move
;
597 this->action_counts
[MTA_TRANSFER
] += max_move
;
602 * Returns reserved cargo to the station and removes it from the cache.
603 * @param max_move Maximum amount of cargo to move.
604 * @param dest Station the cargo is returned to.
605 * @param ID of next the station the cargo wants to go next.
606 * @return Amount of cargo actually returned.
608 uint
VehicleCargoList::Return(uint max_move
, StationCargoList
*dest
, StationID next
)
610 max_move
= min(this->action_counts
[MTA_LOAD
], max_move
);
611 this->PopCargo(CargoReturn(this, dest
, max_move
, next
));
616 * Shifts cargo between two vehicles.
617 * @param dest Other vehicle's cargo list.
618 * @param max_move Maximum amount of cargo to be moved.
619 * @return Amount of cargo actually moved.
621 uint
VehicleCargoList::Shift(uint max_move
, VehicleCargoList
*dest
)
623 max_move
= min(this->count
, max_move
);
624 this->PopCargo(CargoShift(this, dest
, max_move
));
629 * Unloads cargo at the given station. Deliver or transfer, depending on the
630 * ranges defined by designation_counts.
631 * @param dest StationCargoList to add transferred cargo to.
632 * @param max_move Maximum amount of cargo to move.
633 * @param payment Payment object to register payments in.
634 * @return Amount of cargo actually unloaded.
636 uint
VehicleCargoList::Unload(uint max_move
, StationCargoList
*dest
, CargoPayment
*payment
)
639 if (this->action_counts
[MTA_TRANSFER
] > 0) {
640 uint move
= min(this->action_counts
[MTA_TRANSFER
], max_move
);
641 this->ShiftCargo(CargoTransfer(this, dest
, move
));
644 if (this->action_counts
[MTA_TRANSFER
] == 0 && this->action_counts
[MTA_DELIVER
] > 0 && moved
< max_move
) {
645 uint move
= min(this->action_counts
[MTA_DELIVER
], max_move
- moved
);
646 this->ShiftCargo(CargoDelivery(this, move
, payment
));
653 * Truncates the cargo in this list to the given amount. It leaves the
654 * first cargo entities and removes max_move from the back of the list.
655 * @param max_move Maximum amount of entities to be removed from the list.
656 * @return Amount of entities actually moved.
658 uint
VehicleCargoList::Truncate(uint max_move
)
660 max_move
= min(this->count
, max_move
);
661 if (max_move
> this->ActionCount(MTA_KEEP
)) this->KeepAll();
662 this->PopCargo(CargoRemoval
<VehicleCargoList
>(this, max_move
));
667 * Routes packets with station "avoid" as next hop to a different place.
668 * @param max_move Maximum amount of cargo to move.
669 * @param dest List to prepend the cargo to.
670 * @param avoid Station to exclude from routing and current next hop of packets to reroute.
671 * @param avoid2 Additional station to exclude from routing.
672 * @oaram ge GoodsEntry to get the routing info from.
674 uint
VehicleCargoList::Reroute(uint max_move
, VehicleCargoList
*dest
, StationID avoid
, StationID avoid2
, const GoodsEntry
*ge
)
676 max_move
= min(this->action_counts
[MTA_TRANSFER
], max_move
);
677 this->ShiftCargo(VehicleCargoReroute(this, dest
, max_move
, avoid
, avoid2
, ge
));
683 * Station cargo list implementation.
688 * Appends the given cargo packet to the range of packets with the same next station
689 * @warning After appending this packet may not exist anymore!
690 * @note Do not use the cargo packet anymore after it has been appended to this CargoList!
691 * @param next the next hop
692 * @param cp the cargo packet to add
695 void StationCargoList::Append(CargoPacket
*cp
, StationID next
)
698 this->AddToCache(cp
);
700 StationCargoPacketMap::List
&list
= this->packets
[next
];
701 for (StationCargoPacketMap::List::reverse_iterator
it(list
.rbegin());
702 it
!= list
.rend(); it
++) {
703 if (StationCargoList::TryMerge(*it
, cp
)) return;
706 /* The packet could not be merged with another one */
711 * Shifts cargo from the front of the packet list for a specific station and
712 * applies some action to it.
713 * @tparam Taction Action class or function to be used. It should define
714 * "bool operator()(CargoPacket *)". If true is returned the
715 * cargo packet will be removed from the list. Otherwise it
716 * will be kept and the loop will be aborted.
717 * @param action Action instance to be applied.
718 * @param next Next hop the cargo wants to visit.
719 * @return True if all packets with the given next hop have been removed,
722 template <class Taction
>
723 bool StationCargoList::ShiftCargo(Taction
&action
, StationID next
)
725 std::pair
<Iterator
, Iterator
> range(this->packets
.equal_range(next
));
726 for (Iterator
it(range
.first
); it
!= range
.second
&& it
.GetKey() == next
;) {
727 if (action
.MaxMove() == 0) return false;
728 CargoPacket
*cp
= *it
;
730 it
= this->packets
.erase(it
);
739 * Shifts cargo from the front of the packet list for a specific station and
740 * and optional also from the list for "any station", then applies some action
742 * @tparam Taction Action class or function to be used. It should define
743 * "bool operator()(CargoPacket *)". If true is returned the
744 * cargo packet will be removed from the list. Otherwise it
745 * will be kept and the loop will be aborted.
746 * @param action Action instance to be applied.
747 * @param next Next hop the cargo wants to visit.
748 * @param include_invalid If cargo from the INVALID_STATION list should be
750 * @return Amount of cargo actually moved.
752 template <class Taction
>
753 uint
StationCargoList::ShiftCargo(Taction action
, StationIDStack next
, bool include_invalid
)
755 uint max_move
= action
.MaxMove();
756 while (!next
.IsEmpty()) {
757 this->ShiftCargo(action
, next
.Pop());
758 if (action
.MaxMove() == 0) break;
760 if (include_invalid
&& action
.MaxMove() > 0) {
761 this->ShiftCargo(action
, INVALID_STATION
);
763 return max_move
- action
.MaxMove();
767 * Truncates where each destination loses roughly the same percentage of its
768 * cargo. This is done by randomizing the selection of packets to be removed.
769 * Optionally count the cargo by origin station.
770 * @param max_move Maximum amount of cargo to remove.
771 * @param cargo_per_source Container for counting the cargo by origin.
772 * @return Amount of cargo actually moved.
774 uint
StationCargoList::Truncate(uint max_move
, StationCargoAmountMap
*cargo_per_source
)
776 max_move
= min(max_move
, this->count
);
777 uint prev_count
= this->count
;
780 bool do_count
= cargo_per_source
!= NULL
;
781 while (max_move
> moved
) {
782 for (Iterator
it(this->packets
.begin()); it
!= this->packets
.end();) {
783 CargoPacket
*cp
= *it
;
784 if (prev_count
> max_move
&& RandomRange(prev_count
) < prev_count
- max_move
) {
785 if (do_count
&& loop
== 0) {
786 (*cargo_per_source
)[cp
->source
] += cp
->count
;
791 uint diff
= max_move
- moved
;
792 if (cp
->count
> diff
) {
794 this->RemoveFromCache(cp
, diff
);
799 if (do_count
) (*cargo_per_source
)[cp
->source
] -= diff
;
802 if (do_count
) (*cargo_per_source
)[cp
->source
] += cp
->count
;
806 it
= this->packets
.erase(it
);
807 if (do_count
&& loop
> 0) {
808 (*cargo_per_source
)[cp
->source
] -= cp
->count
;
811 this->RemoveFromCache(cp
, cp
->count
);
821 * Reserves cargo for loading onto the vehicle.
822 * @param max_move Maximum amount of cargo to reserve.
823 * @param dest VehicleCargoList to reserve for.
824 * @param load_place Tile index of the current station.
825 * @param next_station Next station(s) the loading vehicle will visit.
826 * @return Amount of cargo actually reserved.
828 uint
StationCargoList::Reserve(uint max_move
, VehicleCargoList
*dest
, TileIndex load_place
, StationIDStack next_station
)
830 return this->ShiftCargo(CargoReservation(this, dest
, max_move
, load_place
), next_station
, true);
834 * Loads cargo onto a vehicle. If the vehicle has reserved cargo load that.
835 * Otherwise load cargo from the station.
836 * @param max_move Amount of cargo to load.
837 * @param dest Vehicle cargo list where the cargo resides.
838 * @param load_place The new loaded_at_xy to be assigned to packets being moved.
839 * @param next_station Next station(s) the loading vehicle will visit.
840 * @return Amount of cargo actually loaded.
841 * @note Vehicles may or may not reserve, depending on their orders. The two
842 * modes of loading are exclusive, though. If cargo is reserved we don't
843 * need to load unreserved cargo.
845 uint
StationCargoList::Load(uint max_move
, VehicleCargoList
*dest
, TileIndex load_place
, StationIDStack next_station
)
847 uint move
= min(dest
->ActionCount(VehicleCargoList::MTA_LOAD
), max_move
);
849 this->reserved_count
-= move
;
850 dest
->Reassign
<VehicleCargoList::MTA_LOAD
, VehicleCargoList::MTA_KEEP
>(move
);
853 return this->ShiftCargo(CargoLoad(this, dest
, max_move
, load_place
), next_station
, true);
858 * Routes packets with station "avoid" as next hop to a different place.
859 * @param max_move Maximum amount of cargo to move.
860 * @param dest List to append the cargo to.
861 * @param avoid Station to exclude from routing and current next hop of packets to reroute.
862 * @param avoid2 Additional station to exclude from routing.
863 * @oaram ge GoodsEntry to get the routing info from.
865 uint
StationCargoList::Reroute(uint max_move
, StationCargoList
*dest
, StationID avoid
, StationID avoid2
, const GoodsEntry
*ge
)
867 return this->ShiftCargo(StationCargoReroute(this, dest
, max_move
, avoid
, avoid2
, ge
), avoid
, false);
871 * We have to instantiate everything we want to be usable.
873 template class CargoList
<VehicleCargoList
, CargoPacketList
>;
874 template class CargoList
<StationCargoList
, StationCargoPacketMap
>;
875 template uint
VehicleCargoList::Reassign
<VehicleCargoList::MTA_DELIVER
, VehicleCargoList::MTA_KEEP
>(uint
, TileOrStationID
);