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 station_base.h Base classes/functions for stations. */
10 #ifndef STATION_BASE_H
11 #define STATION_BASE_H
13 #include "core/random_func.hpp"
14 #include "base_station_base.h"
15 #include "newgrf_airport.h"
16 #include "cargopacket.h"
17 #include "industry_type.h"
18 #include "linkgraph/linkgraph_type.h"
19 #include "newgrf_storage.h"
20 #include "bitmap_type.h"
24 typedef Pool
<BaseStation
, StationID
, 32, 64000> StationPool
;
25 extern StationPool _station_pool
;
27 static const byte INITIAL_STATION_RATING
= 175;
30 * Flow statistics telling how much flow should be sent along a link. This is
31 * done by creating "flow shares" and using std::map's upper_bound() method to
32 * look them up with a random number. A flow share is the difference between a
33 * key in a map and the previous key. So one key in the map doesn't actually
34 * mean anything by itself.
38 typedef std::map
<uint32
, StationID
> SharesMap
;
40 static const SharesMap empty_sharesmap
;
43 * Invalid constructor. This can't be called as a FlowStat must not be
44 * empty. However, the constructor must be defined and reachable for
45 * FlowStat to be used in a std::map.
47 inline FlowStat() {NOT_REACHED();}
50 * Create a FlowStat with an initial entry.
51 * @param st Station the initial entry refers to.
52 * @param flow Amount of flow for the initial entry.
53 * @param restricted If the flow to be added is restricted.
55 inline FlowStat(StationID st
, uint flow
, bool restricted
= false)
58 this->shares
[flow
] = st
;
59 this->unrestricted
= restricted
? 0 : flow
;
63 * Add some flow to the end of the shares map. Only do that if you know
64 * that the station isn't in the map yet. Anything else may lead to
66 * @param st Remote station.
67 * @param flow Amount of flow to be added.
68 * @param restricted If the flow to be added is restricted.
70 inline void AppendShare(StationID st
, uint flow
, bool restricted
= false)
73 this->shares
[(--this->shares
.end())->first
+ flow
] = st
;
74 if (!restricted
) this->unrestricted
+= flow
;
77 uint
GetShare(StationID st
) const;
79 void ChangeShare(StationID st
, int flow
);
81 void RestrictShare(StationID st
);
83 void ReleaseShare(StationID st
);
85 void ScaleToMonthly(uint runtime
);
88 * Get the actual shares as a const pointer so that they can be iterated
90 * @return Actual shares.
92 inline const SharesMap
*GetShares() const { return &this->shares
; }
95 * Return total amount of unrestricted shares.
96 * @return Amount of unrestricted shares.
98 inline uint
GetUnrestricted() const { return this->unrestricted
; }
101 * Swap the shares maps, and thus the content of this FlowStat with the
103 * @param other FlowStat to swap with.
105 inline void SwapShares(FlowStat
&other
)
107 this->shares
.swap(other
.shares
);
108 Swap(this->unrestricted
, other
.unrestricted
);
112 * Get a station a package can be routed to. This done by drawing a
113 * random number between 0 and sum_shares and then looking that up in
114 * the map with lower_bound. So each share gets selected with a
115 * probability dependent on its flow. Do include restricted flows here.
116 * @param is_restricted Output if a restricted flow was chosen.
117 * @return A station ID from the shares map.
119 inline StationID
GetViaWithRestricted(bool &is_restricted
) const
121 assert(!this->shares
.empty());
122 uint rand
= RandomRange((--this->shares
.end())->first
);
123 is_restricted
= rand
>= this->unrestricted
;
124 return this->shares
.upper_bound(rand
)->second
;
128 * Get a station a package can be routed to. This done by drawing a
129 * random number between 0 and sum_shares and then looking that up in
130 * the map with lower_bound. So each share gets selected with a
131 * probability dependent on its flow. Don't include restricted flows.
132 * @return A station ID from the shares map.
134 inline StationID
GetVia() const
136 assert(!this->shares
.empty());
137 return this->unrestricted
> 0 ?
138 this->shares
.upper_bound(RandomRange(this->unrestricted
))->second
:
142 StationID
GetVia(StationID excluded
, StationID excluded2
= INVALID_STATION
) const;
147 SharesMap shares
; ///< Shares of flow to be sent via specified station (or consumed locally).
148 uint unrestricted
; ///< Limit for unrestricted shares.
151 /** Flow descriptions by origin stations. */
152 class FlowStatMap
: public std::map
<StationID
, FlowStat
> {
154 uint
GetFlow() const;
155 uint
GetFlowVia(StationID via
) const;
156 uint
GetFlowFrom(StationID from
) const;
157 uint
GetFlowFromVia(StationID from
, StationID via
) const;
159 void AddFlow(StationID origin
, StationID via
, uint amount
);
160 void PassOnFlow(StationID origin
, StationID via
, uint amount
);
161 StationIDStack
DeleteFlows(StationID via
);
162 void RestrictFlows(StationID via
);
163 void ReleaseFlows(StationID via
);
164 void FinalizeLocalConsumption(StationID self
);
168 * Stores station stats for a single cargo.
171 /** Status of this cargo for the station. */
172 enum GoodsEntryStatus
{
174 * Set when the station accepts the cargo currently for final deliveries.
175 * It is updated every STATION_ACCEPTANCE_TICKS ticks by checking surrounding tiles for acceptance >= 8/8.
180 * This indicates whether a cargo has a rating at the station.
181 * Set when cargo was ever waiting at the station.
182 * It is set when cargo supplied by surrounding tiles is moved to the station, or when
183 * arriving vehicles unload/transfer cargo without it being a final delivery.
185 * This flag is cleared after 255 * STATION_RATING_TICKS of not having seen a pickup.
190 * Set when a vehicle ever delivered cargo to the station for final delivery.
191 * This flag is never cleared.
196 * Set when cargo was delivered for final delivery last month.
197 * This flag is set to the value of GES_CURRENT_MONTH at the start of each month.
202 * Set when cargo was delivered for final delivery this month.
203 * This flag is reset on the beginning of every month.
208 * Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval.
209 * This flag is reset every STATION_ACCEPTANCE_TICKS ticks.
211 GES_ACCEPTED_BIGTICK
,
216 time_since_pickup(255),
217 rating(INITIAL_STATION_RATING
),
221 link_graph(INVALID_LINK_GRAPH
),
226 byte status
; ///< Status of this cargo, see #GoodsEntryStatus.
229 * Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
230 * The unit used is STATION_RATING_TICKS.
231 * This does not imply there was any cargo to load.
233 byte time_since_pickup
;
235 byte rating
; ///< %Station rating for this cargo.
238 * Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
239 * This does not imply there was any cargo to load.
240 * The unit used is a special vehicle-specific speed unit for station ratings.
243 * - Ships: 0.5 * km-ish/h
244 * - Aircraft: 8 * mph
249 * Age in years (up to 255) of the last vehicle that tried to load this cargo.
250 * This does not imply there was any cargo to load.
254 byte amount_fract
; ///< Fractional part of the amount in the cargo list
255 StationCargoList cargo
; ///< The cargo packets of cargo waiting in this station
257 LinkGraphID link_graph
; ///< Link graph this station belongs to.
258 NodeID node
; ///< ID of node in link graph referring to this goods entry.
259 FlowStatMap flows
; ///< Planned flows through this station.
260 uint max_waiting_cargo
; ///< Max cargo from this station waiting at any station.
263 * Reports whether a vehicle has ever tried to load the cargo at this station.
264 * This does not imply that there was cargo available for loading. Refer to GES_RATING for that.
265 * @return true if vehicle tried to load.
267 bool HasVehicleEverTriedLoading() const { return this->last_speed
!= 0; }
270 * Does this cargo have a rating at this station?
271 * @return true if the cargo has a rating, i.e. cargo has been moved to the station.
273 inline bool HasRating() const
275 return HasBit(this->status
, GES_RATING
);
279 * Get the best next hop for a cargo packet from station source.
280 * @param source Source of the packet.
281 * @return The chosen next hop or INVALID_STATION if none was found.
283 inline StationID
GetVia(StationID source
) const
285 FlowStatMap::const_iterator
flow_it(this->flows
.find(source
));
286 return flow_it
!= this->flows
.end() ? flow_it
->second
.GetVia() : INVALID_STATION
;
290 * Get the best next hop for a cargo packet from station source, optionally
291 * excluding one or two stations.
292 * @param source Source of the packet.
293 * @param excluded If this station would be chosen choose the second best one instead.
294 * @param excluded2 Second station to be excluded, if != INVALID_STATION.
295 * @return The chosen next hop or INVALID_STATION if none was found.
297 inline StationID
GetVia(StationID source
, StationID excluded
, StationID excluded2
= INVALID_STATION
) const
299 FlowStatMap::const_iterator
flow_it(this->flows
.find(source
));
300 return flow_it
!= this->flows
.end() ? flow_it
->second
.GetVia(excluded
, excluded2
) : INVALID_STATION
;
304 /** All airport-related information. Only valid if tile != INVALID_TILE. */
305 struct Airport
: public TileArea
{
306 Airport() : TileArea(INVALID_TILE
, 0, 0) {}
308 uint64 flags
; ///< stores which blocks on the airport are taken. was 16 bit earlier on, then 32
309 byte type
; ///< Type of this airport, @see AirportTypes
310 byte layout
; ///< Airport layout number.
311 Direction rotation
; ///< How this airport is rotated.
313 PersistentStorage
*psa
; ///< Persistent storage for NewGRF airports.
316 * Get the AirportSpec that from the airport type of this airport. If there
317 * is no airport (\c tile == INVALID_TILE) then return the dummy AirportSpec.
318 * @return The AirportSpec for this airport.
320 const AirportSpec
*GetSpec() const
322 if (this->tile
== INVALID_TILE
) return &AirportSpec::dummy
;
323 return AirportSpec::Get(this->type
);
327 * Get the finite-state machine for this airport or the finite-state machine
328 * for the dummy airport in case this isn't an airport.
329 * @pre this->type < NEW_AIRPORT_OFFSET.
330 * @return The state machine for this airport.
332 const AirportFTAClass
*GetFTA() const
334 return this->GetSpec()->fsm
;
337 /** Check if this airport has at least one hangar. */
338 inline bool HasHangar() const
340 return this->GetSpec()->nof_depots
> 0;
344 * Add the tileoffset to the base tile of this airport but rotate it first.
345 * The base tile is the northernmost tile of this airport. This function
346 * helps to make sure that getting the tile of a hangar works even for
347 * rotated airport layouts without requiring a rotated array of hangar tiles.
348 * @param tidc The tilediff to add to the airport tile.
349 * @return The tile of this airport plus the rotated offset.
351 inline TileIndex
GetRotatedTileFromOffset(TileIndexDiffC tidc
) const
353 const AirportSpec
*as
= this->GetSpec();
354 switch (this->rotation
) {
355 case DIR_N
: return this->tile
+ ToTileIndexDiff(tidc
);
357 case DIR_E
: return this->tile
+ TileDiffXY(tidc
.y
, as
->size_x
- 1 - tidc
.x
);
359 case DIR_S
: return this->tile
+ TileDiffXY(as
->size_x
- 1 - tidc
.x
, as
->size_y
- 1 - tidc
.y
);
361 case DIR_W
: return this->tile
+ TileDiffXY(as
->size_y
- 1 - tidc
.y
, tidc
.x
);
363 default: NOT_REACHED();
368 * Get the first tile of the given hangar.
369 * @param hangar_num The hangar to get the location of.
370 * @pre hangar_num < GetNumHangars().
371 * @return A tile with the given hangar.
373 inline TileIndex
GetHangarTile(uint hangar_num
) const
375 const AirportSpec
*as
= this->GetSpec();
376 for (uint i
= 0; i
< as
->nof_depots
; i
++) {
377 if (as
->depot_table
[i
].hangar_num
== hangar_num
) {
378 return this->GetRotatedTileFromOffset(as
->depot_table
[i
].ti
);
385 * Get the exit direction of the hangar at a specific tile.
386 * @param tile The tile to query.
387 * @pre IsHangarTile(tile).
388 * @return The exit direction of the hangar, taking airport rotation into account.
390 inline Direction
GetHangarExitDirection(TileIndex tile
) const
392 const AirportSpec
*as
= this->GetSpec();
393 const HangarTileTable
*htt
= GetHangarDataByTile(tile
);
394 return ChangeDir(htt
->dir
, DirDifference(this->rotation
, as
->rotation
[0]));
398 * Get the hangar number of the hangar at a specific tile.
399 * @param tile The tile to query.
400 * @pre IsHangarTile(tile).
401 * @return The hangar number of the hangar at the given tile.
403 inline uint
GetHangarNum(TileIndex tile
) const
405 const HangarTileTable
*htt
= GetHangarDataByTile(tile
);
406 return htt
->hangar_num
;
409 /** Get the number of hangars on this airport. */
410 inline uint
GetNumHangars() const
414 const AirportSpec
*as
= this->GetSpec();
415 for (uint i
= 0; i
< as
->nof_depots
; i
++) {
416 if (!HasBit(counted
, as
->depot_table
[i
].hangar_num
)) {
418 SetBit(counted
, as
->depot_table
[i
].hangar_num
);
426 * Retrieve hangar information of a hangar at a given tile.
427 * @param tile %Tile containing the hangar.
428 * @return The requested hangar information.
429 * @pre The \a tile must be at a hangar tile at an airport.
431 inline const HangarTileTable
*GetHangarDataByTile(TileIndex tile
) const
433 const AirportSpec
*as
= this->GetSpec();
434 for (uint i
= 0; i
< as
->nof_depots
; i
++) {
435 if (this->GetRotatedTileFromOffset(as
->depot_table
[i
].ti
) == tile
) {
436 return as
->depot_table
+ i
;
443 struct IndustryCompare
{
444 bool operator() (const Industry
*lhs
, const Industry
*rhs
) const;
447 typedef std::set
<Industry
*, IndustryCompare
> IndustryList
;
449 /** Station data structure */
450 struct Station FINAL
: SpecializedStation
<Station
, false> {
452 RoadStop
*GetPrimaryRoadStop(RoadStopType type
) const
454 return type
== ROADSTOP_BUS
? bus_stops
: truck_stops
;
457 RoadStop
*GetPrimaryRoadStop(const struct RoadVehicle
*v
) const;
459 RoadStop
*bus_stops
; ///< All the road stops
460 TileArea bus_station
; ///< Tile area the bus 'station' part covers
461 RoadStop
*truck_stops
; ///< All the truck stops
462 TileArea truck_station
; ///< Tile area the truck 'station' part covers
464 Airport airport
; ///< Tile area the airport covers
465 TileArea ship_station
; ///< Tile area the ship 'station' part covers
466 TileArea docking_station
; ///< Tile area the docking tiles cover
468 IndustryType indtype
; ///< Industry type to get the name from
470 BitmapTileArea catchment_tiles
; ///< NOSAVE: Set of individual tiles covered by catchment area
472 StationHadVehicleOfType had_vehicle_of_type
;
474 byte time_since_load
;
475 byte time_since_unload
;
477 byte last_vehicle_type
;
478 std::list
<Vehicle
*> loading_vehicles
;
479 GoodsEntry goods
[NUM_CARGO
]; ///< Goods at this station
480 CargoTypes always_accepted
; ///< Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn't accept cargo)
482 IndustryList industries_near
; ///< Cached list of industries near the station that can accept cargo, @see DeliverGoodsToIndustry()
483 Industry
*industry
; ///< NOSAVE: Associated industry for neutral stations. (Rebuilt on load from Industry->st)
485 Station(TileIndex tile
= INVALID_TILE
);
488 void AddFacility(StationFacility new_facility_bit
, TileIndex facil_xy
);
490 void MarkTilesDirty(bool cargo_change
) const;
492 void UpdateVirtCoord() override
;
494 void MoveSign(TileIndex new_xy
) override
;
496 void AfterStationTileSetChange(bool adding
, StationType type
);
498 uint
GetPlatformLength(TileIndex tile
, DiagDirection dir
) const override
;
499 uint
GetPlatformLength(TileIndex tile
) const override
;
500 void RecomputeCatchment();
501 static void RecomputeCatchmentForAll();
503 uint
GetCatchmentRadius() const;
504 Rect
GetCatchmentRect() const;
505 bool CatchmentCoversTown(TownID t
) const;
506 void AddIndustryToDeliver(Industry
*ind
);
507 void RemoveFromAllNearbyLists();
509 inline bool TileIsInCatchment(TileIndex tile
) const
511 return this->catchment_tiles
.HasTile(tile
);
514 inline bool TileBelongsToRailStation(TileIndex tile
) const override
516 return IsRailStationTile(tile
) && GetStationIndex(tile
) == this->index
;
519 inline bool TileBelongsToAirport(TileIndex tile
) const
521 return IsAirportTile(tile
) && GetStationIndex(tile
) == this->index
;
524 uint32
GetNewGRFVariable(const ResolverObject
&object
, byte variable
, byte parameter
, bool *available
) const override
;
526 void GetTileArea(TileArea
*ta
, StationType type
) const override
;
529 /** Iterator to iterate over all tiles belonging to an airport. */
530 class AirportTileIterator
: public OrthogonalTileIterator
{
532 const Station
*st
; ///< The station the airport is a part of.
536 * Construct the iterator.
537 * @param st Station the airport is part of.
539 AirportTileIterator(const Station
*st
) : OrthogonalTileIterator(st
->airport
), st(st
)
541 if (!st
->TileBelongsToAirport(this->tile
)) ++(*this);
544 inline TileIterator
& operator ++()
546 (*this).OrthogonalTileIterator::operator++();
547 while (this->tile
!= INVALID_TILE
&& !st
->TileBelongsToAirport(this->tile
)) {
548 (*this).OrthogonalTileIterator::operator++();
553 virtual TileIterator
*Clone() const
555 return new AirportTileIterator(*this);
559 void RebuildStationKdtree();
562 * Call a function on all stations that have any part of the requested area within their catchment.
563 * @tparam Func The type of funcion to call
564 * @param area The TileArea to check
565 * @param func The function to call, must take two parameters: Station* and TileIndex and return true
566 * if coverage of that tile is acceptable for a given station or false if search should continue
568 template<typename Func
>
569 void ForAllStationsAroundTiles(const TileArea
&ta
, Func func
)
571 /* Not using, or don't have a nearby stations list, so we need to scan. */
572 std::set
<StationID
> seen_stations
;
574 /* Scan an area around the building covering the maximum possible station
575 * to find the possible nearby stations. */
576 uint max_c
= _settings_game
.station
.modified_catchment
? MAX_CATCHMENT
: CA_UNMODIFIED
;
577 TileArea ta_ext
= TileArea(ta
).Expand(max_c
);
578 TILE_AREA_LOOP(tile
, ta_ext
) {
579 if (IsTileType(tile
, MP_STATION
)) seen_stations
.insert(GetStationIndex(tile
));
582 for (StationID stationid
: seen_stations
) {
583 Station
*st
= Station::GetIfValid(stationid
);
584 if (st
== nullptr) continue; /* Waypoint */
586 /* Check if station is attached to an industry */
587 if (!_settings_game
.station
.serve_neutral_industries
&& st
->industry
!= nullptr) continue;
589 /* Test if the tile is within the station's catchment */
590 TILE_AREA_LOOP(tile
, ta
) {
591 if (st
->TileIsInCatchment(tile
)) {
592 if (func(st
, tile
)) break;
598 #endif /* STATION_BASE_H */