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_cmd.cpp Handling of station tiles. */
12 #include "bridge_map.h"
13 #include "vehiclelist_func.h"
14 #include "viewport_func.h"
15 #include "viewport_kdtree.h"
16 #include "command_func.h"
18 #include "news_func.h"
23 #include "newgrf_cargo.h"
24 #include "newgrf_debug.h"
25 #include "newgrf_station.h"
26 #include "newgrf_canal.h" /* For the buoy */
27 #include "pathfinder/yapf/yapf_cache.h"
28 #include "road_internal.h" /* For drawing catenary/checking road removal */
29 #include "autoslope.h"
31 #include "strings_internal.h"
32 #include "clear_func.h"
33 #include "timer/timer_game_calendar.h"
34 #include "vehicle_func.h"
35 #include "string_func.h"
36 #include "animated_tile_func.h"
37 #include "elrail_func.h"
38 #include "station_base.h"
39 #include "station_func.h"
40 #include "station_kdtree.h"
41 #include "roadstop_base.h"
42 #include "newgrf_railtype.h"
43 #include "newgrf_roadtype.h"
44 #include "waypoint_base.h"
45 #include "waypoint_func.h"
48 #include "core/random_func.hpp"
49 #include "core/container_func.hpp"
50 #include "company_base.h"
51 #include "table/airporttile_ids.h"
52 #include "newgrf_airporttiles.h"
53 #include "order_backup.h"
54 #include "newgrf_house.h"
55 #include "company_gui.h"
56 #include "linkgraph/linkgraph_base.h"
57 #include "linkgraph/refresh.h"
58 #include "tunnelbridge_map.h"
59 #include "station_cmd.h"
60 #include "waypoint_cmd.h"
61 #include "landscape_cmd.h"
63 #include "newgrf_roadstop.h"
64 #include "timer/timer.h"
65 #include "timer/timer_game_calendar.h"
66 #include "timer/timer_game_economy.h"
67 #include "timer/timer_game_tick.h"
68 #include "cheat_type.h"
69 #include "road_func.h"
71 #include "widgets/station_widget.h"
73 #include "table/strings.h"
77 #include "safeguards.h"
80 * Static instance of FlowStat::SharesMap.
81 * Note: This instance is created on task start.
82 * Lazy creation on first usage results in a data race between the CDist threads.
84 /* static */ const FlowStat::SharesMap
FlowStat::empty_sharesmap
;
87 * Check whether the given tile is a hangar.
88 * @param t the tile to of whether it is a hangar.
89 * @pre IsTileType(t, MP_STATION)
90 * @return true if and only if the tile is a hangar.
94 assert(IsTileType(t
, MP_STATION
));
96 /* If the tile isn't an airport there's no chance it's a hangar. */
97 if (!IsAirport(t
)) return false;
99 const Station
*st
= Station::GetByTile(t
);
100 const AirportSpec
*as
= st
->airport
.GetSpec();
102 for (const auto &depot
: as
->depots
) {
103 if (st
->airport
.GetRotatedTileFromOffset(depot
.ti
) == TileIndex(t
)) return true;
110 * Look for a station owned by the given company around the given tile area.
111 * @param ta the area to search over
112 * @param closest_station the closest owned station found so far
113 * @param company the company whose stations to look for
114 * @param st to 'return' the found station
115 * @param filter Filter function
116 * @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
118 template <class T
, class F
>
119 CommandCost
GetStationAround(TileArea ta
, StationID closest_station
, CompanyID company
, T
**st
, F filter
)
123 /* check around to see if there are any stations there owned by the company */
124 for (TileIndex tile_cur
: ta
) {
125 if (IsTileType(tile_cur
, MP_STATION
)) {
126 StationID t
= GetStationIndex(tile_cur
);
127 if (!T::IsValidID(t
) || T::Get(t
)->owner
!= company
|| !filter(T::Get(t
))) continue;
128 if (closest_station
== INVALID_STATION
) {
130 } else if (closest_station
!= t
) {
131 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
135 *st
= (closest_station
== INVALID_STATION
) ? nullptr : T::Get(closest_station
);
136 return CommandCost();
140 * Function to check whether the given tile matches some criterion.
141 * @param tile the tile to check
142 * @return true if it matches, false otherwise
144 typedef bool (*CMSAMatcher
)(TileIndex tile
);
147 * Counts the numbers of tiles matching a specific type in the area around
148 * @param tile the center tile of the 'count area'
149 * @param cmp the comparator/matcher (@see CMSAMatcher)
150 * @return the number of matching tiles around
152 static int CountMapSquareAround(TileIndex tile
, CMSAMatcher cmp
)
156 for (int dx
= -3; dx
<= 3; dx
++) {
157 for (int dy
= -3; dy
<= 3; dy
++) {
158 TileIndex t
= TileAddWrap(tile
, dx
, dy
);
159 if (t
!= INVALID_TILE
&& cmp(t
)) num
++;
167 * Check whether the tile is a mine.
168 * @param tile the tile to investigate.
169 * @return true if and only if the tile is a mine
171 static bool CMSAMine(TileIndex tile
)
174 if (!IsTileType(tile
, MP_INDUSTRY
)) return false;
176 const Industry
*ind
= Industry::GetByTile(tile
);
178 /* No extractive industry */
179 if ((GetIndustrySpec(ind
->type
)->life_type
& INDUSTRYLIFE_EXTRACTIVE
) == 0) return false;
181 for (const auto &p
: ind
->produced
) {
182 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
183 * Also the production of passengers and mail is ignored. */
184 if (IsValidCargoID(p
.cargo
) &&
185 (CargoSpec::Get(p
.cargo
)->classes
& (CC_LIQUID
| CC_PASSENGERS
| CC_MAIL
)) == 0) {
194 * Check whether the tile is water.
195 * @param tile the tile to investigate.
196 * @return true if and only if the tile is a water tile
198 static bool CMSAWater(TileIndex tile
)
200 return IsTileType(tile
, MP_WATER
) && IsWater(tile
);
204 * Check whether the tile is a tree.
205 * @param tile the tile to investigate.
206 * @return true if and only if the tile is a tree tile
208 static bool CMSATree(TileIndex tile
)
210 return IsTileType(tile
, MP_TREES
);
213 #define M(x) ((x) - STR_SV_STNAME)
218 STATIONNAMING_AIRPORT
,
219 STATIONNAMING_OILRIG
,
221 STATIONNAMING_HELIPORT
,
224 /** Information to handle station action 0 property 24 correctly */
225 struct StationNameInformation
{
226 uint32_t free_names
; ///< Current bitset of free names (we can remove names).
227 std::bitset
<NUM_INDUSTRYTYPES
> indtypes
; ///< Bit set indicating when an industry type has been found.
231 * Find a station action 0 property 24 station name, or reduce the
232 * free_names if needed.
233 * @param tile the tile to search
234 * @param user_data the StationNameInformation to base the search on
235 * @return true if the tile contains an industry that has not given
236 * its name to one of the other stations in town.
238 static bool FindNearIndustryName(TileIndex tile
, void *user_data
)
240 /* All already found industry types */
241 StationNameInformation
*sni
= (StationNameInformation
*)user_data
;
242 if (!IsTileType(tile
, MP_INDUSTRY
)) return false;
244 /* If the station name is undefined it means that it doesn't name a station */
245 IndustryType indtype
= GetIndustryType(tile
);
246 if (GetIndustrySpec(indtype
)->station_name
== STR_UNDEFINED
) return false;
248 /* In all cases if an industry that provides a name is found two of
249 * the standard names will be disabled. */
250 sni
->free_names
&= ~(1 << M(STR_SV_STNAME_OILFIELD
) | 1 << M(STR_SV_STNAME_MINES
));
251 return !sni
->indtypes
[indtype
];
254 static StringID
GenerateStationName(Station
*st
, TileIndex tile
, StationNaming name_class
)
256 static const uint32_t _gen_station_name_bits
[] = {
257 0, // STATIONNAMING_RAIL
258 0, // STATIONNAMING_ROAD
259 1U << M(STR_SV_STNAME_AIRPORT
), // STATIONNAMING_AIRPORT
260 1U << M(STR_SV_STNAME_OILFIELD
), // STATIONNAMING_OILRIG
261 1U << M(STR_SV_STNAME_DOCKS
), // STATIONNAMING_DOCK
262 1U << M(STR_SV_STNAME_HELIPORT
), // STATIONNAMING_HELIPORT
265 const Town
*t
= st
->town
;
267 StationNameInformation sni
{};
268 sni
.free_names
= UINT32_MAX
;
270 for (const Station
*s
: Station::Iterate()) {
271 if (s
!= st
&& s
->town
== t
) {
272 if (s
->indtype
!= IT_INVALID
) {
273 sni
.indtypes
[s
->indtype
] = true;
274 StringID name
= GetIndustrySpec(s
->indtype
)->station_name
;
275 if (name
!= STR_UNDEFINED
) {
276 /* Filter for other industrytypes with the same name */
277 for (IndustryType it
= 0; it
< NUM_INDUSTRYTYPES
; it
++) {
278 const IndustrySpec
*indsp
= GetIndustrySpec(it
);
279 if (indsp
->enabled
&& indsp
->station_name
== name
) sni
.indtypes
[it
] = true;
284 uint str
= M(s
->string_id
);
286 if (str
== M(STR_SV_STNAME_FOREST
)) {
287 str
= M(STR_SV_STNAME_WOODS
);
289 ClrBit(sni
.free_names
, str
);
294 TileIndex indtile
= tile
;
295 if (CircularTileSearch(&indtile
, 7, FindNearIndustryName
, &sni
)) {
296 /* An industry has been found nearby */
297 IndustryType indtype
= GetIndustryType(indtile
);
298 const IndustrySpec
*indsp
= GetIndustrySpec(indtype
);
299 /* STR_NULL means it only disables oil rig/mines */
300 if (indsp
->station_name
!= STR_NULL
) {
301 st
->indtype
= indtype
;
302 return STR_SV_STNAME_FALLBACK
;
306 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
308 /* check default names */
309 uint32_t tmp
= sni
.free_names
& _gen_station_name_bits
[name_class
];
310 if (tmp
!= 0) return STR_SV_STNAME
+ FindFirstBit(tmp
);
313 if (HasBit(sni
.free_names
, M(STR_SV_STNAME_MINES
))) {
314 if (CountMapSquareAround(tile
, CMSAMine
) >= 2) {
315 return STR_SV_STNAME_MINES
;
319 /* check close enough to town to get central as name? */
320 if (DistanceMax(tile
, t
->xy
) < 8) {
321 if (HasBit(sni
.free_names
, M(STR_SV_STNAME
))) return STR_SV_STNAME
;
323 if (HasBit(sni
.free_names
, M(STR_SV_STNAME_CENTRAL
))) return STR_SV_STNAME_CENTRAL
;
327 if (HasBit(sni
.free_names
, M(STR_SV_STNAME_LAKESIDE
)) &&
328 DistanceFromEdge(tile
) < 20 &&
329 CountMapSquareAround(tile
, CMSAWater
) >= 5) {
330 return STR_SV_STNAME_LAKESIDE
;
334 if (HasBit(sni
.free_names
, M(STR_SV_STNAME_WOODS
)) && (
335 CountMapSquareAround(tile
, CMSATree
) >= 8 ||
336 CountMapSquareAround(tile
, IsTileForestIndustry
) >= 2)
338 return _settings_game
.game_creation
.landscape
== LT_TROPIC
? STR_SV_STNAME_FOREST
: STR_SV_STNAME_WOODS
;
341 /* check elevation compared to town */
342 int z
= GetTileZ(tile
);
343 int z2
= GetTileZ(t
->xy
);
345 if (HasBit(sni
.free_names
, M(STR_SV_STNAME_VALLEY
))) return STR_SV_STNAME_VALLEY
;
347 if (HasBit(sni
.free_names
, M(STR_SV_STNAME_HEIGHTS
))) return STR_SV_STNAME_HEIGHTS
;
350 /* check direction compared to town */
351 static const int8_t _direction_and_table
[] = {
352 ~( (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
353 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
354 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
355 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) ),
358 sni
.free_names
&= _direction_and_table
[
359 (TileX(tile
) < TileX(t
->xy
)) +
360 (TileY(tile
) < TileY(t
->xy
)) * 2];
362 /** Bitmask of remaining station names that can be used when a more specific name has not been used. */
363 static const uint32_t fallback_names
= (
364 (1U << M(STR_SV_STNAME_NORTH
)) |
365 (1U << M(STR_SV_STNAME_SOUTH
)) |
366 (1U << M(STR_SV_STNAME_EAST
)) |
367 (1U << M(STR_SV_STNAME_WEST
)) |
368 (1U << M(STR_SV_STNAME_TRANSFER
)) |
369 (1U << M(STR_SV_STNAME_HALT
)) |
370 (1U << M(STR_SV_STNAME_EXCHANGE
)) |
371 (1U << M(STR_SV_STNAME_ANNEXE
)) |
372 (1U << M(STR_SV_STNAME_SIDINGS
)) |
373 (1U << M(STR_SV_STNAME_BRANCH
)) |
374 (1U << M(STR_SV_STNAME_UPPER
)) |
375 (1U << M(STR_SV_STNAME_LOWER
))
378 sni
.free_names
&= fallback_names
;
379 return (sni
.free_names
== 0) ? STR_SV_STNAME_FALLBACK
: (STR_SV_STNAME
+ FindFirstBit(sni
.free_names
));
384 * Find the closest deleted station of the current company
385 * @param tile the tile to search from.
386 * @return the closest station or nullptr if too far.
388 static Station
*GetClosestDeletedStation(TileIndex tile
)
392 Station
*best_station
= nullptr;
393 ForAllStationsRadius(tile
, threshold
, [&](Station
*st
) {
394 if (!st
->IsInUse() && st
->owner
== _current_company
) {
395 uint cur_dist
= DistanceManhattan(tile
, st
->xy
);
397 if (cur_dist
< threshold
) {
398 threshold
= cur_dist
;
400 } else if (cur_dist
== threshold
&& best_station
!= nullptr) {
401 /* In case of a tie, lowest station ID wins */
402 if (st
->index
< best_station
->index
) best_station
= st
;
411 void Station::GetTileArea(TileArea
*ta
, StationType type
) const
415 *ta
= this->train_station
;
418 case STATION_AIRPORT
:
423 *ta
= this->truck_station
;
427 *ta
= this->bus_station
;
432 *ta
= this->docking_station
;
435 default: NOT_REACHED();
440 * Update the virtual coords needed to draw the station sign.
442 void Station::UpdateVirtCoord()
444 Point pt
= RemapCoords2(TileX(this->xy
) * TILE_SIZE
, TileY(this->xy
) * TILE_SIZE
);
446 pt
.y
-= 32 * ZOOM_BASE
;
447 if ((this->facilities
& FACIL_AIRPORT
) && this->airport
.type
== AT_OILRIG
) pt
.y
-= 16 * ZOOM_BASE
;
449 if (this->sign
.kdtree_valid
) _viewport_sign_kdtree
.Remove(ViewportSignKdtreeItem::MakeStation(this->index
));
451 SetDParam(0, this->index
);
452 SetDParam(1, this->facilities
);
453 this->sign
.UpdatePosition(pt
.x
, pt
.y
, STR_VIEWPORT_STATION
, STR_VIEWPORT_STATION_TINY
);
455 _viewport_sign_kdtree
.Insert(ViewportSignKdtreeItem::MakeStation(this->index
));
457 SetWindowDirty(WC_STATION_VIEW
, this->index
);
461 * Move the station main coordinate somewhere else.
462 * @param new_xy new tile location of the sign
464 void Station::MoveSign(TileIndex new_xy
)
466 if (this->xy
== new_xy
) return;
468 _station_kdtree
.Remove(this->index
);
470 this->BaseStation::MoveSign(new_xy
);
472 _station_kdtree
.Insert(this->index
);
475 /** Update the virtual coords needed to draw the station sign for all stations. */
476 void UpdateAllStationVirtCoords()
478 for (BaseStation
*st
: BaseStation::Iterate()) {
479 st
->UpdateVirtCoord();
483 void BaseStation::FillCachedName() const
485 auto tmp_params
= MakeParameters(this->index
);
486 this->cached_name
= GetStringWithArgs(Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME
: STR_STATION_NAME
, tmp_params
);
489 void ClearAllStationCachedNames()
491 for (BaseStation
*st
: BaseStation::Iterate()) {
492 st
->cached_name
.clear();
497 * Get a mask of the cargo types that the station accepts.
498 * @param st Station to query
499 * @return the expected mask
501 CargoTypes
GetAcceptanceMask(const Station
*st
)
505 for (auto it
= std::begin(st
->goods
); it
!= std::end(st
->goods
); ++it
) {
506 if (HasBit(it
->status
, GoodsEntry::GES_ACCEPTANCE
)) SetBit(mask
, std::distance(std::begin(st
->goods
), it
));
512 * Get a mask of the cargo types that are empty at the station.
513 * @param st Station to query
514 * @return the empty mask
516 CargoTypes
GetEmptyMask(const Station
*st
)
520 for (auto it
= std::begin(st
->goods
); it
!= std::end(st
->goods
); ++it
) {
521 if (it
->cargo
.TotalCount() == 0) SetBit(mask
, std::distance(std::begin(st
->goods
), it
));
527 * Add news item for when a station changes which cargoes it accepts.
528 * @param st Station of cargo change.
529 * @param cargoes Bit mask of cargo types to list.
530 * @param reject True iff the station rejects the cargo types.
532 static void ShowRejectOrAcceptNews(const Station
*st
, CargoTypes cargoes
, bool reject
)
534 SetDParam(0, st
->index
);
535 SetDParam(1, cargoes
);
536 StringID msg
= reject
? STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_LIST
: STR_NEWS_STATION_NOW_ACCEPTS_CARGO_LIST
;
537 AddNewsItem(msg
, NT_ACCEPTANCE
, NF_INCOLOUR
| NF_SMALL
, NR_STATION
, st
->index
);
541 * Get the cargo types being produced around the tile (in a rectangle).
542 * @param north_tile Northern most tile of area
543 * @param w X extent of the area
544 * @param h Y extent of the area
545 * @param rad Search radius in addition to the given area
547 CargoArray
GetProductionAroundTiles(TileIndex north_tile
, int w
, int h
, int rad
)
549 CargoArray produced
{};
550 std::set
<IndustryID
> industries
;
551 TileArea ta
= TileArea(north_tile
, w
, h
).Expand(rad
);
553 /* Loop over all tiles to get the produced cargo of
554 * everything except industries */
555 for (TileIndex tile
: ta
) {
556 if (IsTileType(tile
, MP_INDUSTRY
)) industries
.insert(GetIndustryIndex(tile
));
557 AddProducedCargo(tile
, produced
);
560 /* Loop over the seen industries. They produce cargo for
561 * anything that is within 'rad' of any one of their tiles.
563 for (IndustryID industry
: industries
) {
564 const Industry
*i
= Industry::Get(industry
);
565 /* Skip industry with neutral station */
566 if (i
->neutral_station
!= nullptr && !_settings_game
.station
.serve_neutral_industries
) continue;
568 for (const auto &p
: i
->produced
) {
569 if (IsValidCargoID(p
.cargo
)) produced
[p
.cargo
]++;
577 * Get the acceptance of cargoes around the tile in 1/8.
578 * @param center_tile Center of the search area
579 * @param w X extent of area
580 * @param h Y extent of area
581 * @param rad Search radius in addition to given area
582 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
583 * @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
585 CargoArray
GetAcceptanceAroundTiles(TileIndex center_tile
, int w
, int h
, int rad
, CargoTypes
*always_accepted
)
587 CargoArray acceptance
{};
588 if (always_accepted
!= nullptr) *always_accepted
= 0;
590 TileArea ta
= TileArea(center_tile
, w
, h
).Expand(rad
);
592 for (TileIndex tile
: ta
) {
593 /* Ignore industry if it has a neutral station. */
594 if (!_settings_game
.station
.serve_neutral_industries
&& IsTileType(tile
, MP_INDUSTRY
) && Industry::GetByTile(tile
)->neutral_station
!= nullptr) continue;
596 AddAcceptedCargo(tile
, acceptance
, always_accepted
);
603 * Get the acceptance of cargoes around the station in.
604 * @param st Station to get acceptance of.
605 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
607 static CargoArray
GetAcceptanceAroundStation(const Station
*st
, CargoTypes
*always_accepted
)
609 CargoArray acceptance
{};
610 if (always_accepted
!= nullptr) *always_accepted
= 0;
612 BitmapTileIterator
it(st
->catchment_tiles
);
613 for (TileIndex tile
= it
; tile
!= INVALID_TILE
; tile
= ++it
) {
614 AddAcceptedCargo(tile
, acceptance
, always_accepted
);
621 * Update the acceptance for a station.
622 * @param st Station to update
623 * @param show_msg controls whether to display a message that acceptance was changed.
625 void UpdateStationAcceptance(Station
*st
, bool show_msg
)
627 /* old accepted goods types */
628 CargoTypes old_acc
= GetAcceptanceMask(st
);
630 /* And retrieve the acceptance. */
631 CargoArray acceptance
{};
632 if (!st
->rect
.IsEmpty()) {
633 acceptance
= GetAcceptanceAroundStation(st
, &st
->always_accepted
);
636 /* Adjust in case our station only accepts fewer kinds of goods */
637 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
638 uint amt
= acceptance
[i
];
640 /* Make sure the station can accept the goods type. */
641 bool is_passengers
= IsCargoInClass(i
, CC_PASSENGERS
);
642 if ((!is_passengers
&& !(st
->facilities
& ~FACIL_BUS_STOP
)) ||
643 (is_passengers
&& !(st
->facilities
& ~FACIL_TRUCK_STOP
))) {
647 GoodsEntry
&ge
= st
->goods
[i
];
648 SB(ge
.status
, GoodsEntry::GES_ACCEPTANCE
, 1, amt
>= 8);
649 if (LinkGraph::IsValidID(ge
.link_graph
)) {
650 (*LinkGraph::Get(ge
.link_graph
))[ge
.node
].SetDemand(amt
/ 8);
654 /* Only show a message in case the acceptance was actually changed. */
655 CargoTypes new_acc
= GetAcceptanceMask(st
);
656 if (old_acc
== new_acc
) return;
658 /* show a message to report that the acceptance was changed? */
659 if (show_msg
&& st
->owner
== _local_company
&& st
->IsInUse()) {
660 /* Combine old and new masks to get changes */
661 CargoTypes accepts
= new_acc
& ~old_acc
;
662 CargoTypes rejects
= ~new_acc
& old_acc
;
664 /* Show news message if there are any changes */
665 if (accepts
!= 0) ShowRejectOrAcceptNews(st
, accepts
, false);
666 if (rejects
!= 0) ShowRejectOrAcceptNews(st
, rejects
, true);
669 /* redraw the station view since acceptance changed */
670 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ACCEPT_RATING_LIST
);
673 static void UpdateStationSignCoord(BaseStation
*st
)
675 const StationRect
*r
= &st
->rect
;
677 if (r
->IsEmpty()) return; // no tiles belong to this station
679 /* clamp sign coord to be inside the station rect */
680 TileIndex new_xy
= TileXY(ClampU(TileX(st
->xy
), r
->left
, r
->right
), ClampU(TileY(st
->xy
), r
->top
, r
->bottom
));
681 st
->MoveSign(new_xy
);
683 if (!Station::IsExpected(st
)) return;
684 Station
*full_station
= Station::From(st
);
685 for (const GoodsEntry
&ge
: full_station
->goods
) {
686 LinkGraphID lg
= ge
.link_graph
;
687 if (!LinkGraph::IsValidID(lg
)) continue;
688 (*LinkGraph::Get(lg
))[ge
.node
].UpdateLocation(st
->xy
);
693 * Common part of building various station parts and possibly attaching them to an existing one.
694 * @param[in,out] st Station to attach to
695 * @param flags Command flags
696 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
697 * @param area Area occupied by the new part
698 * @param name_class Station naming class to use to generate the new station's name
699 * @return Command error that occurred, if any
701 static CommandCost
BuildStationPart(Station
**st
, DoCommandFlag flags
, bool reuse
, TileArea area
, StationNaming name_class
)
703 /* Find a deleted station close to us */
704 if (*st
== nullptr && reuse
) *st
= GetClosestDeletedStation(area
.tile
);
706 if (*st
!= nullptr) {
707 if ((*st
)->owner
!= _current_company
) {
708 return_cmd_error(CMD_ERROR
);
711 CommandCost ret
= (*st
)->rect
.BeforeAddRect(area
.tile
, area
.w
, area
.h
, StationRect::ADD_TEST
);
712 if (ret
.Failed()) return ret
;
714 /* allocate and initialize new station */
715 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING
);
717 if (flags
& DC_EXEC
) {
718 *st
= new Station(area
.tile
);
719 _station_kdtree
.Insert((*st
)->index
);
721 (*st
)->town
= ClosestTownFromTile(area
.tile
, UINT_MAX
);
722 (*st
)->string_id
= GenerateStationName(*st
, area
.tile
, name_class
);
724 if (Company::IsValidID(_current_company
)) {
725 SetBit((*st
)->town
->have_ratings
, _current_company
);
729 return CommandCost();
733 * This is called right after a station was deleted.
734 * It checks if the whole station is free of substations, and if so, the station will be
735 * deleted after a little while.
738 static void DeleteStationIfEmpty(BaseStation
*st
)
740 if (!st
->IsInUse()) {
742 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
744 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
745 UpdateStationSignCoord(st
);
749 * After adding/removing tiles to station, update some station-related stuff.
750 * @param adding True if adding tiles, false if removing them.
751 * @param type StationType being modified.
753 void Station::AfterStationTileSetChange(bool adding
, StationType type
)
755 this->UpdateVirtCoord();
756 DirtyCompanyInfrastructureWindows(this->owner
);
759 this->RecomputeCatchment();
760 MarkCatchmentTilesDirty();
761 InvalidateWindowData(WC_STATION_LIST
, this->owner
, 0);
763 MarkCatchmentTilesDirty();
768 SetWindowWidgetDirty(WC_STATION_VIEW
, this->index
, WID_SV_TRAINS
);
770 case STATION_AIRPORT
:
774 SetWindowWidgetDirty(WC_STATION_VIEW
, this->index
, WID_SV_ROADVEHS
);
777 SetWindowWidgetDirty(WC_STATION_VIEW
, this->index
, WID_SV_SHIPS
);
779 default: NOT_REACHED();
783 UpdateStationAcceptance(this, false);
784 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
786 DeleteStationIfEmpty(this);
787 this->RecomputeCatchment();
792 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
);
795 * Checks if the given tile is buildable, flat and has a certain height.
796 * @param tile TileIndex to check.
797 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
798 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
799 * @param allow_steep Whether steep slopes are allowed.
800 * @param check_bridge Check for the existence of a bridge.
801 * @return The cost in case of success, or an error code if it failed.
803 CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
= true)
805 if (check_bridge
&& IsBridgeAbove(tile
)) {
806 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
809 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
810 if (ret
.Failed()) return ret
;
812 auto [tileh
, z
] = GetTileSlopeZ(tile
);
814 /* Prohibit building if
815 * 1) The tile is "steep" (i.e. stretches two height levels).
816 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
818 if ((!allow_steep
&& IsSteepSlope(tileh
)) ||
819 ((!_settings_game
.construction
.build_on_slopes
) && tileh
!= SLOPE_FLAT
)) {
820 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
823 CommandCost
cost(EXPENSES_CONSTRUCTION
);
824 int flat_z
= z
+ GetSlopeMaxZ(tileh
);
825 if (tileh
!= SLOPE_FLAT
) {
826 /* Forbid building if the tile faces a slope in a invalid direction. */
827 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
!= DIAGDIR_END
; dir
++) {
828 if (HasBit(invalid_dirs
, dir
) && !CanBuildDepotByTileh(dir
, tileh
)) {
829 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
832 cost
.AddCost(_price
[PR_BUILD_FOUNDATION
]);
835 /* The level of this tile must be equal to allowed_z. */
839 } else if (allowed_z
!= flat_z
) {
840 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
847 * Checks if an airport can be built at the given location and clear the area.
848 * @param tile_iter Airport tile iterator.
849 * @param flags Operation to perform.
850 * @return The cost in case of success, or an error code if it failed.
852 static CommandCost
CheckFlatLandAirport(AirportTileTableIterator tile_iter
, DoCommandFlag flags
)
854 CommandCost
cost(EXPENSES_CONSTRUCTION
);
857 for (; tile_iter
!= INVALID_TILE
; ++tile_iter
) {
858 CommandCost ret
= CheckBuildableTile(tile_iter
, 0, allowed_z
, true);
859 if (ret
.Failed()) return ret
;
862 ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile_iter
);
863 if (ret
.Failed()) return ret
;
871 * Checks if a rail station can be built at the given tile.
872 * @param tile_cur Tile to check.
873 * @param north_tile North tile of the area being checked.
874 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
875 * @param flags Operation to perform.
876 * @param axis Rail station axis.
877 * @param station StationID to be queried and returned if available.
878 * @param rt The rail type to check for (overbuilding rail stations over rail).
879 * @param affected_vehicles List of trains with PBS reservations on the tiles
880 * @param spec_class Station class.
881 * @param spec_index Index into the station class.
882 * @param plat_len Platform length.
883 * @param numtracks Number of platforms.
884 * @return The cost in case of success, or an error code if it failed.
886 static CommandCost
CheckFlatLandRailStation(TileIndex tile_cur
, TileIndex north_tile
, int &allowed_z
, DoCommandFlag flags
, Axis axis
, StationID
*station
, RailType rt
, std::vector
<Train
*> &affected_vehicles
, StationClassID spec_class
, uint16_t spec_index
, uint8_t plat_len
, uint8_t numtracks
)
888 CommandCost
cost(EXPENSES_CONSTRUCTION
);
889 uint invalid_dirs
= 5 << axis
;
891 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
892 bool slope_cb
= statspec
!= nullptr && HasBit(statspec
->callback_mask
, CBM_STATION_SLOPE_CHECK
);
894 CommandCost ret
= CheckBuildableTile(tile_cur
, invalid_dirs
, allowed_z
, false);
895 if (ret
.Failed()) return ret
;
899 /* Do slope check if requested. */
900 ret
= PerformStationTileSlopeCheck(north_tile
, tile_cur
, statspec
, axis
, plat_len
, numtracks
);
901 if (ret
.Failed()) return ret
;
904 /* if station is set, then we have special handling to allow building on top of already existing stations.
905 * so station points to INVALID_STATION if we can build on any station.
906 * Or it points to a station if we're only allowed to build on exactly that station. */
907 if (station
!= nullptr && IsTileType(tile_cur
, MP_STATION
)) {
908 if (!IsRailStation(tile_cur
)) {
909 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
911 StationID st
= GetStationIndex(tile_cur
);
912 if (*station
== INVALID_STATION
) {
914 } else if (*station
!= st
) {
915 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
919 /* If we are building a station with a valid railtype, we may be able to overbuild an existing rail tile. */
920 if (rt
!= INVALID_RAILTYPE
&& IsPlainRailTile(tile_cur
)) {
921 /* Don't overbuild signals. */
922 if (HasSignals(tile_cur
)) return_cmd_error(STR_ERROR_MUST_REMOVE_SIGNALS_FIRST
);
924 /* The current rail type must have power on the to-be-built type (e.g. convert normal rail to electrified rail). */
925 if (HasPowerOnRail(GetRailType(tile_cur
), rt
)) {
926 TrackBits tracks
= GetTrackBits(tile_cur
);
927 Track track
= RemoveFirstTrack(&tracks
);
928 Track expected_track
= HasBit(invalid_dirs
, DIAGDIR_NE
) ? TRACK_X
: TRACK_Y
;
930 /* The existing track must align with the desired station axis. */
931 if (tracks
== TRACK_BIT_NONE
&& track
== expected_track
) {
932 /* Check for trains having a reservation for this tile. */
933 if (HasBit(GetRailReservationTrackBits(tile_cur
), track
)) {
934 Train
*v
= GetTrainForReservation(tile_cur
, track
);
936 affected_vehicles
.push_back(v
);
939 ret
= Command
<CMD_REMOVE_SINGLE_RAIL
>::Do(flags
, tile_cur
, track
);
940 if (ret
.Failed()) return ret
;
942 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
947 ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile_cur
);
948 if (ret
.Failed()) return ret
;
956 * Checks if a road stop can be built at the given tile.
957 * @param cur_tile Tile to check.
958 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
959 * @param flags Operation to perform.
960 * @param invalid_dirs Prohibited directions (set of DiagDirections).
961 * @param is_drive_through True if trying to build a drive-through station.
962 * @param station_type Station type (bus, truck or road waypoint).
963 * @param axis Axis of a drive-through road stop.
964 * @param station StationID to be queried and returned if available.
965 * @param rt Road type to build, may be INVALID_ROADTYPE if an existing road is required.
966 * @return The cost in case of success, or an error code if it failed.
968 CommandCost
CheckFlatLandRoadStop(TileIndex cur_tile
, int &allowed_z
, DoCommandFlag flags
, uint invalid_dirs
, bool is_drive_through
, StationType station_type
, Axis axis
, StationID
*station
, RoadType rt
)
970 CommandCost
cost(EXPENSES_CONSTRUCTION
);
972 CommandCost ret
= CheckBuildableTile(cur_tile
, invalid_dirs
, allowed_z
, !is_drive_through
);
973 if (ret
.Failed()) return ret
;
976 /* If station is set, then we have special handling to allow building on top of already existing stations.
977 * Station points to INVALID_STATION if we can build on any station.
978 * Or it points to a station if we're only allowed to build on exactly that station. */
979 if (station
!= nullptr && IsTileType(cur_tile
, MP_STATION
)) {
980 if (!IsAnyRoadStop(cur_tile
)) {
981 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
983 if (station_type
!= GetStationType(cur_tile
) ||
984 is_drive_through
!= IsDriveThroughStopTile(cur_tile
)) {
985 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
987 /* Drive-through station in the wrong direction. */
988 if (is_drive_through
&& IsDriveThroughStopTile(cur_tile
) && GetDriveThroughStopAxis(cur_tile
) != axis
) {
989 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
991 StationID st
= GetStationIndex(cur_tile
);
992 if (*station
== INVALID_STATION
) {
994 } else if (*station
!= st
) {
995 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
999 bool build_over_road
= is_drive_through
&& IsNormalRoadTile(cur_tile
);
1000 /* Road bits in the wrong direction. */
1001 RoadBits rb
= IsNormalRoadTile(cur_tile
) ? GetAllRoadBits(cur_tile
) : ROAD_NONE
;
1002 if (build_over_road
&& (rb
& (axis
== AXIS_X
? ROAD_Y
: ROAD_X
)) != 0) {
1003 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1004 switch (CountBits(rb
)) {
1006 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
1009 if (rb
== ROAD_X
|| rb
== ROAD_Y
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
1010 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER
);
1013 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION
);
1017 if (build_over_road
) {
1018 /* There is a road, check if we can build road+tram stop over it. */
1019 RoadType road_rt
= GetRoadType(cur_tile
, RTT_ROAD
);
1020 if (road_rt
!= INVALID_ROADTYPE
) {
1021 Owner road_owner
= GetRoadOwner(cur_tile
, RTT_ROAD
);
1022 if (road_owner
== OWNER_TOWN
) {
1023 if (!_settings_game
.construction
.road_stop_on_town_road
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD
);
1024 } else if (!_settings_game
.construction
.road_stop_on_competitor_road
&& road_owner
!= OWNER_NONE
) {
1025 ret
= CheckOwnership(road_owner
);
1026 if (ret
.Failed()) return ret
;
1028 uint num_pieces
= CountBits(GetRoadBits(cur_tile
, RTT_ROAD
));
1030 if (rt
!= INVALID_ROADTYPE
&& RoadTypeIsRoad(rt
) && !HasPowerOnRoad(rt
, road_rt
)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD
);
1032 if (GetDisallowedRoadDirections(cur_tile
) != DRD_NONE
&& road_owner
!= OWNER_TOWN
) {
1033 ret
= CheckOwnership(road_owner
);
1034 if (ret
.Failed()) return ret
;
1037 cost
.AddCost(RoadBuildCost(road_rt
) * (2 - num_pieces
));
1038 } else if (rt
!= INVALID_ROADTYPE
&& RoadTypeIsRoad(rt
)) {
1039 cost
.AddCost(RoadBuildCost(rt
) * 2);
1042 /* There is a tram, check if we can build road+tram stop over it. */
1043 RoadType tram_rt
= GetRoadType(cur_tile
, RTT_TRAM
);
1044 if (tram_rt
!= INVALID_ROADTYPE
) {
1045 Owner tram_owner
= GetRoadOwner(cur_tile
, RTT_TRAM
);
1046 if (Company::IsValidID(tram_owner
) &&
1047 (!_settings_game
.construction
.road_stop_on_competitor_road
||
1048 /* Disallow breaking end-of-line of someone else
1049 * so trams can still reverse on this tile. */
1050 HasExactlyOneBit(GetRoadBits(cur_tile
, RTT_TRAM
)))) {
1051 ret
= CheckOwnership(tram_owner
);
1052 if (ret
.Failed()) return ret
;
1054 uint num_pieces
= CountBits(GetRoadBits(cur_tile
, RTT_TRAM
));
1056 if (rt
!= INVALID_ROADTYPE
&& RoadTypeIsTram(rt
) && !HasPowerOnRoad(rt
, tram_rt
)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD
);
1058 cost
.AddCost(RoadBuildCost(tram_rt
) * (2 - num_pieces
));
1059 } else if (rt
!= INVALID_ROADTYPE
&& RoadTypeIsTram(rt
)) {
1060 cost
.AddCost(RoadBuildCost(rt
) * 2);
1062 } else if (rt
== INVALID_ROADTYPE
) {
1063 return_cmd_error(STR_ERROR_THERE_IS_NO_ROAD
);
1065 ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, cur_tile
);
1066 if (ret
.Failed()) return ret
;
1068 cost
.AddCost(RoadBuildCost(rt
) * 2);
1076 * Check whether we can expand the rail part of the given station.
1077 * @param st the station to expand
1078 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1079 * @return Succeeded or failed command.
1081 CommandCost
CanExpandRailStation(const BaseStation
*st
, TileArea
&new_ta
)
1083 TileArea cur_ta
= st
->train_station
;
1085 /* determine new size of train station region.. */
1086 int x
= std::min(TileX(cur_ta
.tile
), TileX(new_ta
.tile
));
1087 int y
= std::min(TileY(cur_ta
.tile
), TileY(new_ta
.tile
));
1088 new_ta
.w
= std::max(TileX(cur_ta
.tile
) + cur_ta
.w
, TileX(new_ta
.tile
) + new_ta
.w
) - x
;
1089 new_ta
.h
= std::max(TileY(cur_ta
.tile
) + cur_ta
.h
, TileY(new_ta
.tile
) + new_ta
.h
) - y
;
1090 new_ta
.tile
= TileXY(x
, y
);
1092 /* make sure the final size is not too big. */
1093 if (new_ta
.w
> _settings_game
.station
.station_spread
|| new_ta
.h
> _settings_game
.station
.station_spread
) {
1094 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1097 return CommandCost();
1100 static inline uint8_t *CreateSingle(uint8_t *layout
, int n
)
1103 do *layout
++ = 0; while (--i
);
1104 layout
[((n
- 1) >> 1) - n
] = 2;
1108 static inline uint8_t *CreateMulti(uint8_t *layout
, int n
, uint8_t b
)
1111 do *layout
++ = b
; while (--i
);
1114 layout
[n
- 1 - n
] = 0;
1120 * Create the station layout for the given number of tracks and platform length.
1121 * @param layout The layout to write to.
1122 * @param numtracks The number of tracks to write.
1123 * @param plat_len The length of the platforms.
1124 * @param statspec The specification of the station to (possibly) get the layout from.
1126 void GetStationLayout(uint8_t *layout
, uint numtracks
, uint plat_len
, const StationSpec
*statspec
)
1128 if (statspec
!= nullptr) {
1129 auto found
= statspec
->layouts
.find(GetStationLayoutKey(numtracks
, plat_len
));
1130 if (found
!= std::end(statspec
->layouts
)) {
1131 /* Custom layout defined, copy to buffer. */
1132 std::copy(std::begin(found
->second
), std::end(found
->second
), layout
);
1137 if (plat_len
== 1) {
1138 CreateSingle(layout
, numtracks
);
1140 if (numtracks
& 1) layout
= CreateSingle(layout
, plat_len
);
1141 int n
= numtracks
>> 1;
1144 layout
= CreateMulti(layout
, plat_len
, 4);
1145 layout
= CreateMulti(layout
, plat_len
, 6);
1151 * Find a nearby station that joins this station.
1152 * @tparam T the class to find a station for
1153 * @tparam error_message the error message when building a station on top of others
1154 * @tparam F the filter functor type
1155 * @param existing_station an existing station we build over
1156 * @param station_to_join the station to join to
1157 * @param adjacent whether adjacent stations are allowed
1158 * @param ta the area of the newly build station
1159 * @param st 'return' pointer for the found station
1160 * @return command cost with the error or 'okay'
1162 template <class T
, StringID error_message
, class F
>
1163 CommandCost
FindJoiningBaseStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, T
**st
, F filter
)
1165 assert(*st
== nullptr);
1166 bool check_surrounding
= true;
1168 if (existing_station
!= INVALID_STATION
) {
1169 if (adjacent
&& existing_station
!= station_to_join
) {
1170 /* You can't build an adjacent station over the top of one that
1171 * already exists. */
1172 return_cmd_error(error_message
);
1174 /* Extend the current station, and don't check whether it will
1175 * be near any other stations. */
1176 T
*candidate
= T::GetIfValid(existing_station
);
1177 if (candidate
!= nullptr && filter(candidate
)) *st
= candidate
;
1178 check_surrounding
= (*st
== nullptr);
1181 /* There's no station here. Don't check the tiles surrounding this
1182 * one if the company wanted to build an adjacent station. */
1183 if (adjacent
) check_surrounding
= false;
1186 if (check_surrounding
) {
1187 /* Make sure there is no more than one other station around us that is owned by us. */
1188 CommandCost ret
= GetStationAround(ta
, existing_station
, _current_company
, st
, filter
);
1189 if (ret
.Failed()) return ret
;
1193 if (*st
== nullptr && station_to_join
!= INVALID_STATION
) *st
= T::GetIfValid(station_to_join
);
1195 return CommandCost();
1199 * Find a nearby station that joins this station.
1200 * @param existing_station an existing station we build over
1201 * @param station_to_join the station to join to
1202 * @param adjacent whether adjacent stations are allowed
1203 * @param ta the area of the newly build station
1204 * @param st 'return' pointer for the found station
1205 * @return command cost with the error or 'okay'
1207 static CommandCost
FindJoiningStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, Station
**st
)
1209 return FindJoiningBaseStation
<Station
, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST
>(existing_station
, station_to_join
, adjacent
, ta
, st
, [](const Station
*) -> bool { return true; });
1213 * Find a nearby waypoint that joins this waypoint.
1214 * @param existing_waypoint an existing waypoint we build over
1215 * @param waypoint_to_join the waypoint to join to
1216 * @param adjacent whether adjacent waypoints are allowed
1217 * @param ta the area of the newly build waypoint
1218 * @param wp 'return' pointer for the found waypoint
1219 * @param is_road whether to find a road waypoint
1220 * @return command cost with the error or 'okay'
1222 CommandCost
FindJoiningWaypoint(StationID existing_waypoint
, StationID waypoint_to_join
, bool adjacent
, TileArea ta
, Waypoint
**wp
, bool is_road
)
1225 return FindJoiningBaseStation
<Waypoint
, STR_ERROR_MUST_REMOVE_ROADWAYPOINT_FIRST
>(existing_waypoint
, waypoint_to_join
, adjacent
, ta
, wp
, [](const Waypoint
*wp
) -> bool { return HasBit(wp
->waypoint_flags
, WPF_ROAD
); });
1227 return FindJoiningBaseStation
<Waypoint
, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST
>(existing_waypoint
, waypoint_to_join
, adjacent
, ta
, wp
, [](const Waypoint
*wp
) -> bool { return !HasBit(wp
->waypoint_flags
, WPF_ROAD
); });
1232 * Clear platform reservation during station building/removing.
1233 * @param v vehicle which holds reservation
1235 static void FreeTrainReservation(Train
*v
)
1237 FreeTrainTrackReservation(v
);
1238 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(v
->GetVehicleTrackdir()), false);
1240 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(ReverseTrackdir(v
->GetVehicleTrackdir())), false);
1244 * Restore platform reservation during station building/removing.
1245 * @param v vehicle which held reservation
1247 static void RestoreTrainReservation(Train
*v
)
1249 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(v
->GetVehicleTrackdir()), true);
1250 TryPathReserve(v
, true, true);
1252 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(ReverseTrackdir(v
->GetVehicleTrackdir())), true);
1256 * Calculates cost of new rail stations within the area.
1257 * @param tile_area Area to check.
1258 * @param flags Operation to perform.
1259 * @param axis Rail station axis.
1260 * @param station StationID to be queried and returned if available.
1261 * @param rt The rail type to check for (overbuilding rail stations over rail).
1262 * @param affected_vehicles List of trains with PBS reservations on the tiles
1263 * @param spec_class Station class.
1264 * @param spec_index Index into the station class.
1265 * @param plat_len Platform length.
1266 * @param numtracks Number of platforms.
1267 * @return The cost in case of success, or an error code if it failed.
1269 static CommandCost
CalculateRailStationCost(TileArea tile_area
, DoCommandFlag flags
, Axis axis
, StationID
*station
, RailType rt
, std::vector
<Train
*> &affected_vehicles
, StationClassID spec_class
, uint16_t spec_index
, uint8_t plat_len
, uint8_t numtracks
)
1271 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1272 bool length_price_ready
= true;
1273 uint8_t tracknum
= 0;
1275 for (TileIndex cur_tile
: tile_area
) {
1276 /* Clear the land below the station. */
1277 CommandCost ret
= CheckFlatLandRailStation(cur_tile
, tile_area
.tile
, allowed_z
, flags
, axis
, station
, rt
, affected_vehicles
, spec_class
, spec_index
, plat_len
, numtracks
);
1278 if (ret
.Failed()) return ret
;
1280 /* Only add _price[PR_BUILD_STATION_RAIL_LENGTH] once for each valid plat_len. */
1281 if (tracknum
== numtracks
) {
1282 length_price_ready
= true;
1288 /* AddCost for new or rotated rail stations. */
1289 if (!IsRailStationTile(cur_tile
) || (IsRailStationTile(cur_tile
) && GetRailStationAxis(cur_tile
) != axis
)) {
1291 cost
.AddCost(_price
[PR_BUILD_STATION_RAIL
]);
1292 cost
.AddCost(RailBuildCost(rt
));
1294 if (length_price_ready
) {
1295 cost
.AddCost(_price
[PR_BUILD_STATION_RAIL_LENGTH
]);
1296 length_price_ready
= false;
1305 * Get station tile flags for the given StationGfx.
1306 * @param gfx StationGfx of station tile.
1307 * @param statspec Station spec of station tile.
1308 * @return Tile flags to apply.
1310 static StationSpec::TileFlags
GetStationTileFlags(StationGfx gfx
, const StationSpec
*statspec
)
1312 /* Default stations do not draw pylons under roofs (gfx >= 4) */
1313 if (statspec
== nullptr || gfx
>= statspec
->tileflags
.size()) return gfx
< 4 ? StationSpec::TileFlags::Pylons
: StationSpec::TileFlags::None
;
1314 return statspec
->tileflags
[gfx
];
1318 * Set rail station tile flags for the given tile.
1319 * @param tile Tile to set flags on.
1320 * @param statspec Statspec of the tile.
1322 void SetRailStationTileFlags(TileIndex tile
, const StationSpec
*statspec
)
1324 const auto flags
= GetStationTileFlags(GetStationGfx(tile
), statspec
);
1325 SetStationTileBlocked(tile
, HasFlag(flags
, StationSpec::TileFlags::Blocked
));
1326 SetStationTileHavePylons(tile
, HasFlag(flags
, StationSpec::TileFlags::Pylons
));
1327 SetStationTileHaveWires(tile
, !HasFlag(flags
, StationSpec::TileFlags::NoWires
));
1331 * Build rail station
1332 * @param flags operation to perform
1333 * @param tile_org northern most position of station dragging/placement
1334 * @param rt railtype
1335 * @param axis orientation (Axis)
1336 * @param numtracks number of tracks
1337 * @param plat_len platform length
1338 * @param spec_class custom station class
1339 * @param spec_index custom station id
1340 * @param station_to_join station ID to join (NEW_STATION if build new one)
1341 * @param adjacent allow stations directly adjacent to other stations.
1342 * @return the cost of this operation or an error
1344 CommandCost
CmdBuildRailStation(DoCommandFlag flags
, TileIndex tile_org
, RailType rt
, Axis axis
, uint8_t numtracks
, uint8_t plat_len
, StationClassID spec_class
, uint16_t spec_index
, StationID station_to_join
, bool adjacent
)
1346 /* Does the authority allow this? */
1347 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile_org
, flags
);
1348 if (ret
.Failed()) return ret
;
1350 if (!ValParamRailType(rt
) || !IsValidAxis(axis
)) return CMD_ERROR
;
1352 /* Check if the given station class is valid */
1353 if (static_cast<uint
>(spec_class
) >= StationClass::GetClassCount()) return CMD_ERROR
;
1354 const StationClass
*cls
= StationClass::Get(spec_class
);
1355 if (IsWaypointClass(*cls
)) return CMD_ERROR
;
1356 if (spec_index
>= cls
->GetSpecCount()) return CMD_ERROR
;
1357 if (plat_len
== 0 || numtracks
== 0) return CMD_ERROR
;
1360 if (axis
== AXIS_X
) {
1368 bool reuse
= (station_to_join
!= NEW_STATION
);
1369 if (!reuse
) station_to_join
= INVALID_STATION
;
1370 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1372 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1374 if (h_org
> _settings_game
.station
.station_spread
|| w_org
> _settings_game
.station
.station_spread
) return CMD_ERROR
;
1376 /* these values are those that will be stored in train_tile and station_platforms */
1377 TileArea
new_location(tile_org
, w_org
, h_org
);
1379 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1380 StationID est
= INVALID_STATION
;
1381 std::vector
<Train
*> affected_vehicles
;
1382 /* Add construction and clearing expenses. */
1383 CommandCost cost
= CalculateRailStationCost(new_location
, flags
, axis
, &est
, rt
, affected_vehicles
, spec_class
, spec_index
, plat_len
, numtracks
);
1384 if (cost
.Failed()) return cost
;
1386 Station
*st
= nullptr;
1387 ret
= FindJoiningStation(est
, station_to_join
, adjacent
, new_location
, &st
);
1388 if (ret
.Failed()) return ret
;
1390 ret
= BuildStationPart(&st
, flags
, reuse
, new_location
, STATIONNAMING_RAIL
);
1391 if (ret
.Failed()) return ret
;
1393 if (st
!= nullptr && st
->train_station
.tile
!= INVALID_TILE
) {
1394 ret
= CanExpandRailStation(st
, new_location
);
1395 if (ret
.Failed()) return ret
;
1398 /* Check if we can allocate a custom stationspec to this station */
1399 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
1400 int specindex
= AllocateSpecToStation(statspec
, st
, (flags
& DC_EXEC
) != 0);
1401 if (specindex
== -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS
);
1403 if (statspec
!= nullptr) {
1404 /* Perform NewStation checks */
1406 /* Check if the station size is permitted */
1407 if (HasBit(statspec
->disallowed_platforms
, std::min(numtracks
- 1, 7))) return_cmd_error(STR_ERROR_STATION_DISALLOWED_NUMBER_TRACKS
);
1408 if (HasBit(statspec
->disallowed_lengths
, std::min(plat_len
- 1, 7))) return_cmd_error(STR_ERROR_STATION_DISALLOWED_LENGTH
);
1410 /* Check if the station is buildable */
1411 if (HasBit(statspec
->callback_mask
, CBM_STATION_AVAIL
)) {
1412 uint16_t cb_res
= GetStationCallback(CBID_STATION_AVAILABILITY
, 0, 0, statspec
, nullptr, INVALID_TILE
);
1413 if (cb_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(statspec
->grf_prop
.grffile
, CBID_STATION_AVAILABILITY
, cb_res
)) return CMD_ERROR
;
1417 if (flags
& DC_EXEC
) {
1418 st
->train_station
= new_location
;
1419 st
->AddFacility(FACIL_TRAIN
, new_location
.tile
);
1421 st
->rect
.BeforeAddRect(tile_org
, w_org
, h_org
, StationRect::ADD_TRY
);
1423 if (statspec
!= nullptr) {
1424 /* Include this station spec's animation trigger bitmask
1425 * in the station's cached copy. */
1426 st
->cached_anim_triggers
|= statspec
->animation
.triggers
;
1429 TileIndexDiff tile_delta
= TileOffsByAxis(axis
); // offset to go to the next platform tile
1430 TileIndexDiff track_delta
= TileOffsByAxis(OtherAxis(axis
)); // offset to go to the next track
1431 Track track
= AxisToTrack(axis
);
1433 std::vector
<uint8_t> layouts(numtracks
* plat_len
);
1434 GetStationLayout(layouts
.data(), numtracks
, plat_len
, statspec
);
1436 uint8_t numtracks_orig
= numtracks
;
1438 Company
*c
= Company::Get(st
->owner
);
1439 size_t layout_idx
= 0;
1440 TileIndex tile_track
= tile_org
;
1442 TileIndex tile
= tile_track
;
1445 uint8_t layout
= layouts
[layout_idx
++];
1446 if (IsRailStationTile(tile
) && HasStationReservation(tile
)) {
1447 /* Check for trains having a reservation for this tile. */
1448 Train
*v
= GetTrainForReservation(tile
, AxisToTrack(GetRailStationAxis(tile
)));
1450 affected_vehicles
.push_back(v
);
1451 FreeTrainReservation(v
);
1455 /* Railtype can change when overbuilding. */
1456 if (IsRailStationTile(tile
)) {
1457 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[GetRailType(tile
)]--;
1458 c
->infrastructure
.station
--;
1461 /* Remove animation if overbuilding */
1462 DeleteAnimatedTile(tile
);
1463 uint8_t old_specindex
= HasStationTileRail(tile
) ? GetCustomStationSpecIndex(tile
) : 0;
1464 MakeRailStation(tile
, st
->owner
, st
->index
, axis
, layout
& ~1, rt
);
1465 /* Free the spec if we overbuild something */
1466 DeallocateSpecFromStation(st
, old_specindex
);
1468 SetCustomStationSpecIndex(tile
, specindex
);
1469 SetStationTileRandomBits(tile
, GB(Random(), 0, 4));
1470 SetAnimationFrame(tile
, 0);
1472 if (statspec
!= nullptr) {
1473 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1474 uint32_t platinfo
= GetPlatformInfo(AXIS_X
, GetStationGfx(tile
), plat_len
, numtracks_orig
, plat_len
- w
, numtracks_orig
- numtracks
, false);
1476 /* As the station is not yet completely finished, the station does not yet exist. */
1477 uint16_t callback
= GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT
, platinfo
, 0, statspec
, nullptr, tile
);
1478 if (callback
!= CALLBACK_FAILED
) {
1479 if (callback
<= UINT8_MAX
) {
1480 SetStationGfx(tile
, (callback
& ~1) + axis
);
1482 ErrorUnknownCallbackResult(statspec
->grf_prop
.grffile
->grfid
, CBID_STATION_BUILD_TILE_LAYOUT
, callback
);
1486 /* Trigger station animation -- after building? */
1487 TriggerStationAnimation(st
, tile
, SAT_BUILT
);
1490 SetRailStationTileFlags(tile
, statspec
);
1492 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[rt
]++;
1493 c
->infrastructure
.station
++;
1497 AddTrackToSignalBuffer(tile_track
, track
, _current_company
);
1498 YapfNotifyTrackLayoutChange(tile_track
, track
);
1499 tile_track
+= track_delta
;
1500 } while (--numtracks
);
1502 for (uint i
= 0; i
< affected_vehicles
.size(); ++i
) {
1503 /* Restore reservations of trains. */
1504 RestoreTrainReservation(affected_vehicles
[i
]);
1507 /* Check whether we need to expand the reservation of trains already on the station. */
1508 TileArea update_reservation_area
;
1509 if (axis
== AXIS_X
) {
1510 update_reservation_area
= TileArea(tile_org
, 1, numtracks_orig
);
1512 update_reservation_area
= TileArea(tile_org
, numtracks_orig
, 1);
1515 for (TileIndex tile
: update_reservation_area
) {
1516 /* Don't even try to make eye candy parts reserved. */
1517 if (IsStationTileBlocked(tile
)) continue;
1519 DiagDirection dir
= AxisToDiagDir(axis
);
1520 TileIndexDiff tile_offset
= TileOffsByDiagDir(dir
);
1521 TileIndex platform_begin
= tile
;
1522 TileIndex platform_end
= tile
;
1524 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1525 for (TileIndex next_tile
= platform_begin
- tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_begin
); next_tile
-= tile_offset
) {
1526 platform_begin
= next_tile
;
1528 for (TileIndex next_tile
= platform_end
+ tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_end
); next_tile
+= tile_offset
) {
1529 platform_end
= next_tile
;
1532 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1533 bool reservation
= false;
1534 for (TileIndex t
= platform_begin
; !reservation
&& t
<= platform_end
; t
+= tile_offset
) {
1535 reservation
= HasStationReservation(t
);
1539 SetRailStationPlatformReservation(platform_begin
, dir
, true);
1543 st
->MarkTilesDirty(false);
1544 st
->AfterStationTileSetChange(true, STATION_RAIL
);
1550 static TileArea
MakeStationAreaSmaller(BaseStation
*st
, TileArea ta
, bool (*func
)(BaseStation
*, TileIndex
))
1555 if (ta
.w
!= 0 && ta
.h
!= 0) {
1556 /* check the left side, x = constant, y changes */
1557 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(0, i
));) {
1558 /* the left side is unused? */
1560 ta
.tile
+= TileDiffXY(1, 0);
1566 /* check the right side, x = constant, y changes */
1567 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(ta
.w
- 1, i
));) {
1568 /* the right side is unused? */
1575 /* check the upper side, y = constant, x changes */
1576 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(i
, 0));) {
1577 /* the left side is unused? */
1579 ta
.tile
+= TileDiffXY(0, 1);
1585 /* check the lower side, y = constant, x changes */
1586 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(i
, ta
.h
- 1));) {
1587 /* the left side is unused? */
1600 static bool TileBelongsToRailStation(BaseStation
*st
, TileIndex tile
)
1602 return st
->TileBelongsToRailStation(tile
);
1605 static void MakeRailStationAreaSmaller(BaseStation
*st
)
1607 st
->train_station
= MakeStationAreaSmaller(st
, st
->train_station
, TileBelongsToRailStation
);
1610 static bool TileBelongsToShipStation(BaseStation
*st
, TileIndex tile
)
1612 return IsDockTile(tile
) && GetStationIndex(tile
) == st
->index
;
1615 static void MakeShipStationAreaSmaller(Station
*st
)
1617 st
->ship_station
= MakeStationAreaSmaller(st
, st
->ship_station
, TileBelongsToShipStation
);
1618 UpdateStationDockingTiles(st
);
1621 static bool TileBelongsToRoadWaypointStation(BaseStation
*st
, TileIndex tile
)
1623 return IsRoadWaypointTile(tile
) && GetStationIndex(tile
) == st
->index
;
1626 void MakeRoadWaypointStationAreaSmaller(BaseStation
*st
, TileArea
&road_waypoint_area
)
1628 road_waypoint_area
= MakeStationAreaSmaller(st
, road_waypoint_area
, TileBelongsToRoadWaypointStation
);
1632 * Remove a number of tiles from any rail station within the area.
1633 * @param ta the area to clear station tile from.
1634 * @param affected_stations the stations affected.
1635 * @param flags the command flags.
1636 * @param removal_cost the cost for removing the tile, including the rail.
1637 * @param keep_rail whether to keep the rail of the station.
1638 * @tparam T the type of station to remove.
1639 * @return the number of cleared tiles or an error.
1642 CommandCost
RemoveFromRailBaseStation(TileArea ta
, std::vector
<T
*> &affected_stations
, DoCommandFlag flags
, Money removal_cost
, bool keep_rail
)
1644 /* Count of the number of tiles removed */
1646 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
1647 /* Accumulator for the errors seen during clearing. If no errors happen,
1648 * and the quantity is 0 there is no station. Otherwise it will be one
1649 * of the other error that got accumulated. */
1652 /* Do the action for every tile into the area */
1653 for (TileIndex tile
: ta
) {
1654 /* Make sure the specified tile is a rail station */
1655 if (!HasStationTileRail(tile
)) continue;
1657 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1658 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1660 if (ret
.Failed()) continue;
1662 /* Check ownership of station */
1663 T
*st
= T::GetByTile(tile
);
1664 if (st
== nullptr) continue;
1666 if (_current_company
!= OWNER_WATER
) {
1667 ret
= CheckOwnership(st
->owner
);
1669 if (ret
.Failed()) continue;
1672 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1675 if (keep_rail
|| IsStationTileBlocked(tile
)) {
1676 /* Don't refund the 'steel' of the track when we keep the
1677 * rail, or when the tile didn't have any rail at all. */
1678 total_cost
.AddCost(-_price
[PR_CLEAR_RAIL
]);
1681 if (flags
& DC_EXEC
) {
1682 /* read variables before the station tile is removed */
1683 uint specindex
= GetCustomStationSpecIndex(tile
);
1684 Track track
= GetRailStationTrack(tile
);
1685 Owner owner
= GetTileOwner(tile
);
1686 RailType rt
= GetRailType(tile
);
1689 if (HasStationReservation(tile
)) {
1690 v
= GetTrainForReservation(tile
, track
);
1691 if (v
!= nullptr) FreeTrainReservation(v
);
1694 bool build_rail
= keep_rail
&& !IsStationTileBlocked(tile
);
1695 if (!build_rail
&& !IsStationTileBlocked(tile
)) Company::Get(owner
)->infrastructure
.rail
[rt
]--;
1697 DoClearSquare(tile
);
1698 DeleteNewGRFInspectWindow(GSF_STATIONS
, tile
.base());
1699 if (build_rail
) MakeRailNormal(tile
, owner
, TrackToTrackBits(track
), rt
);
1700 Company::Get(owner
)->infrastructure
.station
--;
1701 DirtyCompanyInfrastructureWindows(owner
);
1703 st
->rect
.AfterRemoveTile(st
, tile
);
1704 AddTrackToSignalBuffer(tile
, track
, owner
);
1705 YapfNotifyTrackLayoutChange(tile
, track
);
1707 DeallocateSpecFromStation(st
, specindex
);
1709 include(affected_stations
, st
);
1711 if (v
!= nullptr) RestoreTrainReservation(v
);
1715 if (quantity
== 0) return error
.Failed() ? error
: CommandCost(STR_ERROR_THERE_IS_NO_STATION
);
1717 for (T
*st
: affected_stations
) {
1719 /* now we need to make the "spanned" area of the railway station smaller
1720 * if we deleted something at the edges.
1721 * we also need to adjust train_tile. */
1722 MakeRailStationAreaSmaller(st
);
1723 UpdateStationSignCoord(st
);
1725 /* if we deleted the whole station, delete the train facility. */
1726 if (st
->train_station
.tile
== INVALID_TILE
) {
1727 st
->facilities
&= ~FACIL_TRAIN
;
1728 SetWindowClassesDirty(WC_VEHICLE_ORDERS
);
1729 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1730 MarkCatchmentTilesDirty();
1731 st
->UpdateVirtCoord();
1732 DeleteStationIfEmpty(st
);
1736 total_cost
.AddCost(quantity
* removal_cost
);
1741 * Remove a single tile from a rail station.
1742 * This allows for custom-built station with holes and weird layouts
1743 * @param flags operation to perform
1744 * @param start tile of station piece to remove
1745 * @param end other edge of the rect to remove
1746 * @param keep_rail if set keep the rail
1747 * @return the cost of this operation or an error
1749 CommandCost
CmdRemoveFromRailStation(DoCommandFlag flags
, TileIndex start
, TileIndex end
, bool keep_rail
)
1751 if (end
== 0) end
= start
;
1752 if (start
>= Map::Size() || end
>= Map::Size()) return CMD_ERROR
;
1754 TileArea
ta(start
, end
);
1755 std::vector
<Station
*> affected_stations
;
1757 CommandCost ret
= RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_STATION_RAIL
], keep_rail
);
1758 if (ret
.Failed()) return ret
;
1760 /* Do all station specific functions here. */
1761 for (Station
*st
: affected_stations
) {
1763 if (st
->train_station
.tile
== INVALID_TILE
) SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1764 st
->MarkTilesDirty(false);
1765 MarkCatchmentTilesDirty();
1766 st
->RecomputeCatchment();
1769 /* Now apply the rail cost to the number that we deleted */
1774 * Remove a single tile from a waypoint.
1775 * This allows for custom-built waypoint with holes and weird layouts
1776 * @param flags operation to perform
1777 * @param start tile of waypoint piece to remove
1778 * @param end other edge of the rect to remove
1779 * @param keep_rail if set keep the rail
1780 * @return the cost of this operation or an error
1782 CommandCost
CmdRemoveFromRailWaypoint(DoCommandFlag flags
, TileIndex start
, TileIndex end
, bool keep_rail
)
1784 if (end
== 0) end
= start
;
1785 if (start
>= Map::Size() || end
>= Map::Size()) return CMD_ERROR
;
1787 TileArea
ta(start
, end
);
1788 std::vector
<Waypoint
*> affected_stations
;
1790 return RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
], keep_rail
);
1795 * Remove a rail station/waypoint
1796 * @param st The station/waypoint to remove the rail part from
1797 * @param flags operation to perform
1798 * @param removal_cost the cost for removing a tile
1799 * @tparam T the type of station to remove
1800 * @return cost or failure of operation
1803 CommandCost
RemoveRailStation(T
*st
, DoCommandFlag flags
, Money removal_cost
)
1805 /* Current company owns the station? */
1806 if (_current_company
!= OWNER_WATER
) {
1807 CommandCost ret
= CheckOwnership(st
->owner
);
1808 if (ret
.Failed()) return ret
;
1811 /* determine width and height of platforms */
1812 TileArea ta
= st
->train_station
;
1814 assert(ta
.w
!= 0 && ta
.h
!= 0);
1816 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1817 /* clear all areas of the station */
1818 for (TileIndex tile
: ta
) {
1819 /* only remove tiles that are actually train station tiles */
1820 if (st
->TileBelongsToRailStation(tile
)) {
1821 std::vector
<T
*> affected_stations
; // dummy
1822 CommandCost ret
= RemoveFromRailBaseStation(TileArea(tile
, 1, 1), affected_stations
, flags
, removal_cost
, false);
1823 if (ret
.Failed()) return ret
;
1832 * Remove a rail station
1833 * @param tile Tile of the station.
1834 * @param flags operation to perform
1835 * @return cost or failure of operation
1837 static CommandCost
RemoveRailStation(TileIndex tile
, DoCommandFlag flags
)
1839 /* if there is flooding, remove platforms tile by tile */
1840 if (_current_company
== OWNER_WATER
) {
1841 return Command
<CMD_REMOVE_FROM_RAIL_STATION
>::Do(DC_EXEC
, tile
, 0, false);
1844 Station
*st
= Station::GetByTile(tile
);
1845 CommandCost cost
= RemoveRailStation(st
, flags
, _price
[PR_CLEAR_STATION_RAIL
]);
1847 if (flags
& DC_EXEC
) st
->RecomputeCatchment();
1853 * Remove a rail waypoint
1854 * @param tile Tile of the waypoint.
1855 * @param flags operation to perform
1856 * @return cost or failure of operation
1858 static CommandCost
RemoveRailWaypoint(TileIndex tile
, DoCommandFlag flags
)
1860 /* if there is flooding, remove waypoints tile by tile */
1861 if (_current_company
== OWNER_WATER
) {
1862 return Command
<CMD_REMOVE_FROM_RAIL_WAYPOINT
>::Do(DC_EXEC
, tile
, 0, false);
1865 return RemoveRailStation(Waypoint::GetByTile(tile
), flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
]);
1870 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1871 * @param st The Station to do the whole procedure for
1872 * @return a pointer to where to link a new RoadStop*
1874 static RoadStop
**FindRoadStopSpot(bool truck_station
, Station
*st
)
1876 RoadStop
**primary_stop
= (truck_station
) ? &st
->truck_stops
: &st
->bus_stops
;
1878 if (*primary_stop
== nullptr) {
1879 /* we have no roadstop of the type yet, so write a "primary stop" */
1880 return primary_stop
;
1882 /* there are stops already, so append to the end of the list */
1883 RoadStop
*stop
= *primary_stop
;
1884 while (stop
->next
!= nullptr) stop
= stop
->next
;
1889 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
, int replacement_spec_index
= -1);
1890 CommandCost
RemoveRoadWaypointStop(TileIndex tile
, DoCommandFlag flags
, int replacement_spec_index
= -1);
1893 * Find a nearby station that joins this road stop.
1894 * @param existing_stop an existing road stop we build over
1895 * @param station_to_join the station to join to
1896 * @param adjacent whether adjacent stations are allowed
1897 * @param ta the area of the newly build station
1898 * @param st 'return' pointer for the found station
1899 * @return command cost with the error or 'okay'
1901 static CommandCost
FindJoiningRoadStop(StationID existing_stop
, StationID station_to_join
, bool adjacent
, TileArea ta
, Station
**st
)
1903 return FindJoiningBaseStation
<Station
, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST
>(existing_stop
, station_to_join
, adjacent
, ta
, st
, [](const Station
*) -> bool { return true; });
1907 * Calculates cost of new road stops within the area.
1908 * @param tile_area Area to check.
1909 * @param flags Operation to perform.
1910 * @param is_drive_through True if trying to build a drive-through station.
1911 * @param station_type Station type (bus, truck or road waypoint).
1912 * @param axis Axis of a drive-through road stop.
1913 * @param ddir Entrance direction (#DiagDirection) for normal stops. Converted to the axis for drive-through stops.
1914 * @param station StationID to be queried and returned if available.
1915 * @param rt Road type to build, may be INVALID_ROADTYPE if an existing road is required.
1916 * @param unit_cost The cost to build one road stop of the current type.
1917 * @return The cost in case of success, or an error code if it failed.
1919 CommandCost
CalculateRoadStopCost(TileArea tile_area
, DoCommandFlag flags
, bool is_drive_through
, StationType station_type
, Axis axis
, DiagDirection ddir
, StationID
*est
, RoadType rt
, Money unit_cost
)
1921 uint invalid_dirs
= 0;
1922 if (is_drive_through
) {
1923 SetBit(invalid_dirs
, AxisToDiagDir(axis
));
1924 SetBit(invalid_dirs
, ReverseDiagDir(AxisToDiagDir(axis
)));
1926 SetBit(invalid_dirs
, ddir
);
1929 /* Check every tile in the area. */
1931 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1932 for (TileIndex cur_tile
: tile_area
) {
1933 CommandCost ret
= CheckFlatLandRoadStop(cur_tile
, allowed_z
, flags
, invalid_dirs
, is_drive_through
, station_type
, axis
, est
, rt
);
1934 if (ret
.Failed()) return ret
;
1936 bool is_preexisting_roadstop
= IsTileType(cur_tile
, MP_STATION
) && IsAnyRoadStop(cur_tile
);
1938 /* Only add costs if a stop doesn't already exist in the location */
1939 if (!is_preexisting_roadstop
) {
1941 cost
.AddCost(unit_cost
);
1949 * Build a bus or truck stop.
1950 * @param flags Operation to perform.
1951 * @param tile Northernmost tile of the stop.
1952 * @param width Width of the road stop.
1953 * @param length Length of the road stop.
1954 * @param stop_type Type of road stop (bus/truck).
1955 * @param is_drive_through False for normal stops, true for drive-through.
1956 * @param ddir Entrance direction (#DiagDirection) for normal stops. Converted to the axis for drive-through stops.
1957 * @param rt The roadtype.
1958 * @param spec_class Road stop spec class.
1959 * @param spec_index Road stop spec index.
1960 * @param station_to_join Station ID to join (NEW_STATION if build new one).
1961 * @param adjacent Allow stations directly adjacent to other stations.
1962 * @return The cost of this operation or an error.
1964 CommandCost
CmdBuildRoadStop(DoCommandFlag flags
, TileIndex tile
, uint8_t width
, uint8_t length
, RoadStopType stop_type
, bool is_drive_through
,
1965 DiagDirection ddir
, RoadType rt
, RoadStopClassID spec_class
, uint16_t spec_index
, StationID station_to_join
, bool adjacent
)
1967 if (!ValParamRoadType(rt
) || !IsValidDiagDirection(ddir
) || stop_type
>= ROADSTOP_END
) return CMD_ERROR
;
1968 bool reuse
= (station_to_join
!= NEW_STATION
);
1969 if (!reuse
) station_to_join
= INVALID_STATION
;
1970 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1972 /* Check if the given station class is valid */
1973 if (static_cast<uint
>(spec_class
) >= RoadStopClass::GetClassCount()) return CMD_ERROR
;
1974 const RoadStopClass
*cls
= RoadStopClass::Get(spec_class
);
1975 if (IsWaypointClass(*cls
)) return CMD_ERROR
;
1976 if (spec_index
>= cls
->GetSpecCount()) return CMD_ERROR
;
1978 const RoadStopSpec
*roadstopspec
= cls
->GetSpec(spec_index
);
1979 if (roadstopspec
!= nullptr) {
1980 if (stop_type
== ROADSTOP_TRUCK
&& roadstopspec
->stop_type
!= ROADSTOPTYPE_FREIGHT
&& roadstopspec
->stop_type
!= ROADSTOPTYPE_ALL
) return CMD_ERROR
;
1981 if (stop_type
== ROADSTOP_BUS
&& roadstopspec
->stop_type
!= ROADSTOPTYPE_PASSENGER
&& roadstopspec
->stop_type
!= ROADSTOPTYPE_ALL
) return CMD_ERROR
;
1982 if (!is_drive_through
&& HasBit(roadstopspec
->flags
, RSF_DRIVE_THROUGH_ONLY
)) return CMD_ERROR
;
1985 /* Check if the requested road stop is too big */
1986 if (width
> _settings_game
.station
.station_spread
|| length
> _settings_game
.station
.station_spread
) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1987 /* Check for incorrect width / length. */
1988 if (width
== 0 || length
== 0) return CMD_ERROR
;
1989 /* Check if the first tile and the last tile are valid */
1990 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, length
- 1) == INVALID_TILE
) return CMD_ERROR
;
1992 TileArea
roadstop_area(tile
, width
, length
);
1994 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1996 /* Trams only have drive through stops */
1997 if (!is_drive_through
&& RoadTypeIsTram(rt
)) return CMD_ERROR
;
1999 Axis axis
= DiagDirToAxis(ddir
);
2001 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2002 if (ret
.Failed()) return ret
;
2004 bool is_truck_stop
= stop_type
!= ROADSTOP_BUS
;
2006 /* Total road stop cost. */
2008 if (roadstopspec
!= nullptr) {
2009 unit_cost
= roadstopspec
->GetBuildCost(is_truck_stop
? PR_BUILD_STATION_TRUCK
: PR_BUILD_STATION_BUS
);
2011 unit_cost
= _price
[is_truck_stop
? PR_BUILD_STATION_TRUCK
: PR_BUILD_STATION_BUS
];
2013 StationID est
= INVALID_STATION
;
2014 CommandCost cost
= CalculateRoadStopCost(roadstop_area
, flags
, is_drive_through
, is_truck_stop
? STATION_TRUCK
: STATION_BUS
, axis
, ddir
, &est
, rt
, unit_cost
);
2015 if (cost
.Failed()) return cost
;
2017 Station
*st
= nullptr;
2018 ret
= FindJoiningRoadStop(est
, station_to_join
, adjacent
, roadstop_area
, &st
);
2019 if (ret
.Failed()) return ret
;
2021 /* Check if this number of road stops can be allocated. */
2022 if (!RoadStop::CanAllocateItem(static_cast<size_t>(roadstop_area
.w
) * roadstop_area
.h
)) return_cmd_error(is_truck_stop
? STR_ERROR_TOO_MANY_TRUCK_STOPS
: STR_ERROR_TOO_MANY_BUS_STOPS
);
2024 ret
= BuildStationPart(&st
, flags
, reuse
, roadstop_area
, STATIONNAMING_ROAD
);
2025 if (ret
.Failed()) return ret
;
2027 /* Check if we can allocate a custom stationspec to this station */
2028 int specindex
= AllocateSpecToRoadStop(roadstopspec
, st
, (flags
& DC_EXEC
) != 0);
2029 if (specindex
== -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS
);
2031 if (roadstopspec
!= nullptr) {
2032 /* Perform NewGRF checks */
2034 /* Check if the road stop is buildable */
2035 if (HasBit(roadstopspec
->callback_mask
, CBM_ROAD_STOP_AVAIL
)) {
2036 uint16_t cb_res
= GetRoadStopCallback(CBID_STATION_AVAILABILITY
, 0, 0, roadstopspec
, nullptr, INVALID_TILE
, rt
, is_truck_stop
? STATION_TRUCK
: STATION_BUS
, 0);
2037 if (cb_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(roadstopspec
->grf_prop
.grffile
, CBID_STATION_AVAILABILITY
, cb_res
)) return CMD_ERROR
;
2041 if (flags
& DC_EXEC
) {
2042 /* Check every tile in the area. */
2043 for (TileIndex cur_tile
: roadstop_area
) {
2044 /* Get existing road types and owners before any tile clearing */
2045 RoadType road_rt
= MayHaveRoad(cur_tile
) ? GetRoadType(cur_tile
, RTT_ROAD
) : INVALID_ROADTYPE
;
2046 RoadType tram_rt
= MayHaveRoad(cur_tile
) ? GetRoadType(cur_tile
, RTT_TRAM
) : INVALID_ROADTYPE
;
2047 Owner road_owner
= road_rt
!= INVALID_ROADTYPE
? GetRoadOwner(cur_tile
, RTT_ROAD
) : _current_company
;
2048 Owner tram_owner
= tram_rt
!= INVALID_ROADTYPE
? GetRoadOwner(cur_tile
, RTT_TRAM
) : _current_company
;
2050 if (IsTileType(cur_tile
, MP_STATION
) && IsStationRoadStop(cur_tile
)) {
2051 RemoveRoadStop(cur_tile
, flags
, specindex
);
2054 if (roadstopspec
!= nullptr) {
2055 /* Include this road stop spec's animation trigger bitmask
2056 * in the station's cached copy. */
2057 st
->cached_roadstop_anim_triggers
|= roadstopspec
->animation
.triggers
;
2060 RoadStop
*road_stop
= new RoadStop(cur_tile
);
2061 /* Insert into linked list of RoadStops. */
2062 RoadStop
**currstop
= FindRoadStopSpot(is_truck_stop
, st
);
2063 *currstop
= road_stop
;
2065 if (is_truck_stop
) {
2066 st
->truck_station
.Add(cur_tile
);
2068 st
->bus_station
.Add(cur_tile
);
2071 /* Initialize an empty station. */
2072 st
->AddFacility(is_truck_stop
? FACIL_TRUCK_STOP
: FACIL_BUS_STOP
, cur_tile
);
2074 st
->rect
.BeforeAddTile(cur_tile
, StationRect::ADD_TRY
);
2076 RoadStopType rs_type
= is_truck_stop
? ROADSTOP_TRUCK
: ROADSTOP_BUS
;
2077 if (is_drive_through
) {
2078 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2080 if (IsNormalRoadTile(cur_tile
)) {
2081 UpdateCompanyRoadInfrastructure(road_rt
, road_owner
, -(int)CountBits(GetRoadBits(cur_tile
, RTT_ROAD
)));
2082 UpdateCompanyRoadInfrastructure(tram_rt
, tram_owner
, -(int)CountBits(GetRoadBits(cur_tile
, RTT_TRAM
)));
2085 if (road_rt
== INVALID_ROADTYPE
&& RoadTypeIsRoad(rt
)) road_rt
= rt
;
2086 if (tram_rt
== INVALID_ROADTYPE
&& RoadTypeIsTram(rt
)) tram_rt
= rt
;
2088 MakeDriveThroughRoadStop(cur_tile
, st
->owner
, road_owner
, tram_owner
, st
->index
, (rs_type
== ROADSTOP_BUS
? STATION_BUS
: STATION_TRUCK
), road_rt
, tram_rt
, axis
);
2089 road_stop
->MakeDriveThrough();
2091 if (road_rt
== INVALID_ROADTYPE
&& RoadTypeIsRoad(rt
)) road_rt
= rt
;
2092 if (tram_rt
== INVALID_ROADTYPE
&& RoadTypeIsTram(rt
)) tram_rt
= rt
;
2093 MakeRoadStop(cur_tile
, st
->owner
, st
->index
, rs_type
, road_rt
, tram_rt
, ddir
);
2095 UpdateCompanyRoadInfrastructure(road_rt
, road_owner
, ROAD_STOP_TRACKBIT_FACTOR
);
2096 UpdateCompanyRoadInfrastructure(tram_rt
, tram_owner
, ROAD_STOP_TRACKBIT_FACTOR
);
2097 Company::Get(st
->owner
)->infrastructure
.station
++;
2099 SetCustomRoadStopSpecIndex(cur_tile
, specindex
);
2100 if (roadstopspec
!= nullptr) {
2101 st
->SetRoadStopRandomBits(cur_tile
, GB(Random(), 0, 8));
2102 TriggerRoadStopAnimation(st
, cur_tile
, SAT_BUILT
);
2105 MarkTileDirtyByTile(cur_tile
);
2108 if (st
!= nullptr) {
2109 st
->AfterStationTileSetChange(true, is_truck_stop
? STATION_TRUCK
: STATION_BUS
);
2116 static Vehicle
*ClearRoadStopStatusEnum(Vehicle
*v
, void *)
2118 if (v
->type
== VEH_ROAD
) {
2119 /* Okay... we are a road vehicle on a drive through road stop.
2120 * But that road stop has just been removed, so we need to make
2121 * sure we are in a valid state... however, vehicles can also
2122 * turn on road stop tiles, so only clear the 'road stop' state
2123 * bits and only when the state was 'in road stop', otherwise
2124 * we'll end up clearing the turn around bits. */
2125 RoadVehicle
*rv
= RoadVehicle::From(v
);
2126 if (HasBit(rv
->state
, RVS_IN_DT_ROAD_STOP
)) rv
->state
&= RVSB_ROAD_STOP_TRACKDIR_MASK
;
2134 * Remove a bus station/truck stop
2135 * @param tile TileIndex been queried
2136 * @param flags operation to perform
2137 * @param replacement_spec_index replacement spec index to avoid deallocating, if < 0, tile is not being replaced
2138 * @return cost or failure of operation
2140 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
, int replacement_spec_index
)
2142 Station
*st
= Station::GetByTile(tile
);
2144 if (_current_company
!= OWNER_WATER
) {
2145 CommandCost ret
= CheckOwnership(st
->owner
);
2146 if (ret
.Failed()) return ret
;
2149 bool is_truck
= IsTruckStop(tile
);
2151 RoadStop
**primary_stop
;
2153 if (is_truck
) { // truck stop
2154 primary_stop
= &st
->truck_stops
;
2155 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_TRUCK
);
2157 primary_stop
= &st
->bus_stops
;
2158 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_BUS
);
2161 assert(cur_stop
!= nullptr);
2163 /* don't do the check for drive-through road stops when company bankrupts */
2164 if (IsDriveThroughStopTile(tile
) && (flags
& DC_BANKRUPT
)) {
2165 /* remove the 'going through road stop' status from all vehicles on that tile */
2166 if (flags
& DC_EXEC
) FindVehicleOnPos(tile
, nullptr, &ClearRoadStopStatusEnum
);
2168 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
2169 if (ret
.Failed()) return ret
;
2172 const RoadStopSpec
*spec
= GetRoadStopSpec(tile
);
2174 if (flags
& DC_EXEC
) {
2175 if (*primary_stop
== cur_stop
) {
2176 /* removed the first stop in the list */
2177 *primary_stop
= cur_stop
->next
;
2178 /* removed the only stop? */
2179 if (*primary_stop
== nullptr) {
2180 st
->facilities
&= (is_truck
? ~FACIL_TRUCK_STOP
: ~FACIL_BUS_STOP
);
2181 SetWindowClassesDirty(WC_VEHICLE_ORDERS
);
2184 /* tell the predecessor in the list to skip this stop */
2185 RoadStop
*pred
= *primary_stop
;
2186 while (pred
->next
!= cur_stop
) pred
= pred
->next
;
2187 pred
->next
= cur_stop
->next
;
2190 /* Update company infrastructure counts. */
2191 for (RoadTramType rtt
: _roadtramtypes
) {
2192 RoadType rt
= GetRoadType(tile
, rtt
);
2193 UpdateCompanyRoadInfrastructure(rt
, GetRoadOwner(tile
, rtt
), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR
));
2196 Company::Get(st
->owner
)->infrastructure
.station
--;
2197 DirtyCompanyInfrastructureWindows(st
->owner
);
2199 DeleteAnimatedTile(tile
);
2201 uint specindex
= GetCustomRoadStopSpecIndex(tile
);
2203 DeleteNewGRFInspectWindow(GSF_ROADSTOPS
, tile
.base());
2205 if (IsDriveThroughStopTile(tile
)) {
2206 /* Clears the tile for us */
2207 cur_stop
->ClearDriveThrough();
2209 DoClearSquare(tile
);
2214 /* Make sure no vehicle is going to the old roadstop. Narrow the search to any road vehicles with an order to
2215 * this station, then look for any currently heading to the tile. */
2216 StationID station_id
= st
->index
;
2217 FindVehiclesWithOrder(
2218 [](const Vehicle
*v
) { return v
->type
== VEH_ROAD
; },
2219 [station_id
](const Order
*order
) { return order
->IsType(OT_GOTO_STATION
) && order
->GetDestination() == station_id
; },
2220 [station_id
, tile
](Vehicle
*v
) {
2221 if (v
->current_order
.IsType(OT_GOTO_STATION
) && v
->dest_tile
== tile
) {
2222 v
->SetDestTile(v
->GetOrderStationLocation(station_id
));
2227 st
->rect
.AfterRemoveTile(st
, tile
);
2229 if (replacement_spec_index
< 0) st
->AfterStationTileSetChange(false, is_truck
? STATION_TRUCK
: STATION_BUS
);
2231 st
->RemoveRoadStopTileData(tile
);
2232 if ((int)specindex
!= replacement_spec_index
) DeallocateSpecFromRoadStop(st
, specindex
);
2234 /* Update the tile area of the truck/bus stop */
2236 st
->truck_station
.Clear();
2237 for (const RoadStop
*rs
= st
->truck_stops
; rs
!= nullptr; rs
= rs
->next
) st
->truck_station
.Add(rs
->xy
);
2239 st
->bus_station
.Clear();
2240 for (const RoadStop
*rs
= st
->bus_stops
; rs
!= nullptr; rs
= rs
->next
) st
->bus_station
.Add(rs
->xy
);
2244 Price category
= is_truck
? PR_CLEAR_STATION_TRUCK
: PR_CLEAR_STATION_BUS
;
2245 return CommandCost(EXPENSES_CONSTRUCTION
, spec
!= nullptr ? spec
->GetClearCost(category
) : _price
[category
]);
2249 * Remove a road waypoint
2250 * @param tile TileIndex been queried
2251 * @param flags operation to perform
2252 * @param replacement_spec_index replacement spec index to avoid deallocating, if < 0, tile is not being replaced
2253 * @return cost or failure of operation
2255 CommandCost
RemoveRoadWaypointStop(TileIndex tile
, DoCommandFlag flags
, int replacement_spec_index
)
2257 Waypoint
*wp
= Waypoint::GetByTile(tile
);
2259 if (_current_company
!= OWNER_WATER
) {
2260 CommandCost ret
= CheckOwnership(wp
->owner
);
2261 if (ret
.Failed()) return ret
;
2264 /* Ignore vehicles when the company goes bankrupt. The road will remain, any vehicles going to the waypoint will be removed. */
2265 if (!(flags
& DC_BANKRUPT
)) {
2266 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
2267 if (ret
.Failed()) return ret
;
2270 const RoadStopSpec
*spec
= GetRoadStopSpec(tile
);
2272 if (flags
& DC_EXEC
) {
2273 /* Update company infrastructure counts. */
2274 for (RoadTramType rtt
: _roadtramtypes
) {
2275 RoadType rt
= GetRoadType(tile
, rtt
);
2276 UpdateCompanyRoadInfrastructure(rt
, GetRoadOwner(tile
, rtt
), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR
));
2279 Company::Get(wp
->owner
)->infrastructure
.station
--;
2280 DirtyCompanyInfrastructureWindows(wp
->owner
);
2282 DeleteAnimatedTile(tile
);
2284 uint specindex
= GetCustomRoadStopSpecIndex(tile
);
2286 DeleteNewGRFInspectWindow(GSF_ROADSTOPS
, tile
.base());
2288 DoClearSquare(tile
);
2290 wp
->rect
.AfterRemoveTile(wp
, tile
);
2292 wp
->RemoveRoadStopTileData(tile
);
2293 if ((int)specindex
!= replacement_spec_index
) DeallocateSpecFromRoadStop(wp
, specindex
);
2295 if (replacement_spec_index
< 0) {
2296 MakeRoadWaypointStationAreaSmaller(wp
, wp
->road_waypoint_area
);
2298 UpdateStationSignCoord(wp
);
2300 /* if we deleted the whole waypoint, delete the road facility. */
2301 if (wp
->road_waypoint_area
.tile
== INVALID_TILE
) {
2302 wp
->facilities
&= ~(FACIL_BUS_STOP
| FACIL_TRUCK_STOP
);
2303 SetWindowWidgetDirty(WC_STATION_VIEW
, wp
->index
, WID_SV_ROADVEHS
);
2304 wp
->UpdateVirtCoord();
2305 DeleteStationIfEmpty(wp
);
2310 return CommandCost(EXPENSES_CONSTRUCTION
, spec
!= nullptr ? spec
->GetClearCost(PR_CLEAR_STATION_TRUCK
) : _price
[PR_CLEAR_STATION_TRUCK
]);
2314 * Remove a tile area of road stop or road waypoints
2315 * @param flags operation to perform
2316 * @param roadstop_area tile area of road stop or road waypoint tiles to remove
2317 * @param station_type station type to remove
2318 * @param remove_road Remove roads of drive-through stops?
2319 * @return the cost of this operation or an error
2321 static CommandCost
RemoveGenericRoadStop(DoCommandFlag flags
, const TileArea
&roadstop_area
, StationType station_type
, bool remove_road
)
2323 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2324 CommandCost
last_error(STR_ERROR_THERE_IS_NO_STATION
);
2325 bool had_success
= false;
2327 for (TileIndex cur_tile
: roadstop_area
) {
2328 /* Make sure the specified tile is a road stop of the correct type */
2329 if (!IsTileType(cur_tile
, MP_STATION
) || !IsAnyRoadStop(cur_tile
) || GetStationType(cur_tile
) != station_type
) continue;
2331 /* Save information on to-be-restored roads before the stop is removed. */
2332 RoadBits road_bits
= ROAD_NONE
;
2333 RoadType road_type
[] = { INVALID_ROADTYPE
, INVALID_ROADTYPE
};
2334 Owner road_owner
[] = { OWNER_NONE
, OWNER_NONE
};
2335 if (IsDriveThroughStopTile(cur_tile
)) {
2336 for (RoadTramType rtt
: _roadtramtypes
) {
2337 road_type
[rtt
] = GetRoadType(cur_tile
, rtt
);
2338 if (road_type
[rtt
] == INVALID_ROADTYPE
) continue;
2339 road_owner
[rtt
] = GetRoadOwner(cur_tile
, rtt
);
2340 /* If we don't want to preserve our roads then restore only roads of others. */
2341 if (remove_road
&& road_owner
[rtt
] == _current_company
) road_type
[rtt
] = INVALID_ROADTYPE
;
2343 road_bits
= AxisToRoadBits(GetDriveThroughStopAxis(cur_tile
));
2347 if (station_type
== STATION_ROADWAYPOINT
) {
2348 ret
= RemoveRoadWaypointStop(cur_tile
, flags
);
2350 ret
= RemoveRoadStop(cur_tile
, flags
);
2359 /* Restore roads. */
2360 if ((flags
& DC_EXEC
) && (road_type
[RTT_ROAD
] != INVALID_ROADTYPE
|| road_type
[RTT_TRAM
] != INVALID_ROADTYPE
)) {
2361 MakeRoadNormal(cur_tile
, road_bits
, road_type
[RTT_ROAD
], road_type
[RTT_TRAM
], ClosestTownFromTile(cur_tile
, UINT_MAX
)->index
,
2362 road_owner
[RTT_ROAD
], road_owner
[RTT_TRAM
]);
2364 /* Update company infrastructure counts. */
2365 int count
= CountBits(road_bits
);
2366 UpdateCompanyRoadInfrastructure(road_type
[RTT_ROAD
], road_owner
[RTT_ROAD
], count
);
2367 UpdateCompanyRoadInfrastructure(road_type
[RTT_TRAM
], road_owner
[RTT_TRAM
], count
);
2371 return had_success
? cost
: last_error
;
2375 * Remove bus or truck stops.
2376 * @param flags Operation to perform.
2377 * @param tile Northernmost tile of the removal area.
2378 * @param width Width of the removal area.
2379 * @param height Height of the removal area.
2380 * @param stop_type Type of stop (bus/truck).
2381 * @param remove_road Remove roads of drive-through stops?
2382 * @return The cost of this operation or an error.
2384 CommandCost
CmdRemoveRoadStop(DoCommandFlag flags
, TileIndex tile
, uint8_t width
, uint8_t height
, RoadStopType stop_type
, bool remove_road
)
2386 if (stop_type
>= ROADSTOP_END
) return CMD_ERROR
;
2387 /* Check for incorrect width / height. */
2388 if (width
== 0 || height
== 0) return CMD_ERROR
;
2389 /* Check if the first tile and the last tile are valid */
2390 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, height
- 1) == INVALID_TILE
) return CMD_ERROR
;
2391 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2392 if (remove_road
&& (flags
& DC_BANKRUPT
)) return CMD_ERROR
;
2394 TileArea
roadstop_area(tile
, width
, height
);
2396 return RemoveGenericRoadStop(flags
, roadstop_area
, stop_type
== ROADSTOP_BUS
? STATION_BUS
: STATION_TRUCK
, remove_road
);
2400 * Remove road waypoints.
2401 * @param flags operation to perform
2402 * @param start tile of road waypoint piece to remove
2403 * @param end other edge of the rect to remove
2404 * @return the cost of this operation or an error
2406 CommandCost
CmdRemoveFromRoadWaypoint(DoCommandFlag flags
, TileIndex start
, TileIndex end
)
2408 if (end
== 0) end
= start
;
2409 if (start
>= Map::Size() || end
>= Map::Size()) return CMD_ERROR
;
2411 TileArea
roadstop_area(start
, end
);
2413 return RemoveGenericRoadStop(flags
, roadstop_area
, STATION_ROADWAYPOINT
, false);
2417 * Get a possible noise reduction factor based on distance from town center.
2418 * The further you get, the less noise you generate.
2419 * So all those folks at city council can now happily slee... work in their offices
2420 * @param as airport information
2421 * @param distance minimum distance between town and airport
2422 * @return the noise that will be generated, according to distance
2424 uint8_t GetAirportNoiseLevelForDistance(const AirportSpec
*as
, uint distance
)
2426 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2427 * So no need to go any further*/
2428 if (as
->noise_level
< 2) return as
->noise_level
;
2430 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2431 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2432 * Basically, it says that the less tolerant a town is, the bigger the distance before
2433 * an actual decrease can be granted */
2434 uint8_t town_tolerance_distance
= 8 + (_settings_game
.difficulty
.town_council_tolerance
* 4);
2436 /* now, we want to have the distance segmented using the distance judged bareable by town
2437 * This will give us the coefficient of reduction the distance provides. */
2438 uint noise_reduction
= distance
/ town_tolerance_distance
;
2440 /* If the noise reduction equals the airport noise itself, don't give it for free.
2441 * Otherwise, simply reduce the airport's level. */
2442 return noise_reduction
>= as
->noise_level
? 1 : as
->noise_level
- noise_reduction
;
2446 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2447 * If two towns have the same distance, town with lower index is returned.
2448 * @param as airport's description
2449 * @param rotation airport's rotation
2450 * @param tile origin tile (top corner of the airport)
2451 * @param it An iterator over all airport tiles (consumed)
2452 * @param[out] mindist Minimum distance to town
2453 * @return nearest town to airport
2455 Town
*AirportGetNearestTown(const AirportSpec
*as
, Direction rotation
, TileIndex tile
, TileIterator
&&it
, uint
&mindist
)
2457 assert(Town::GetNumItems() > 0);
2459 Town
*nearest
= nullptr;
2461 auto width
= as
->size_x
;
2462 auto height
= as
->size_y
;
2463 if (rotation
== DIR_E
|| rotation
== DIR_W
) std::swap(width
, height
);
2465 uint perimeter_min_x
= TileX(tile
);
2466 uint perimeter_min_y
= TileY(tile
);
2467 uint perimeter_max_x
= perimeter_min_x
+ width
- 1;
2468 uint perimeter_max_y
= perimeter_min_y
+ height
- 1;
2470 mindist
= UINT_MAX
- 1; // prevent overflow
2472 for (TileIndex cur_tile
= *it
; cur_tile
!= INVALID_TILE
; cur_tile
= ++it
) {
2473 assert(IsInsideBS(TileX(cur_tile
), perimeter_min_x
, width
));
2474 assert(IsInsideBS(TileY(cur_tile
), perimeter_min_y
, height
));
2475 if (TileX(cur_tile
) == perimeter_min_x
|| TileX(cur_tile
) == perimeter_max_x
|| TileY(cur_tile
) == perimeter_min_y
|| TileY(cur_tile
) == perimeter_max_y
) {
2476 Town
*t
= CalcClosestTownFromTile(cur_tile
, mindist
+ 1);
2477 if (t
== nullptr) continue;
2479 uint dist
= DistanceManhattan(t
->xy
, cur_tile
);
2480 if (dist
== mindist
&& t
->index
< nearest
->index
) nearest
= t
;
2481 if (dist
< mindist
) {
2492 * Finds the town nearest to given existing airport. Based on minimal manhattan distance to any airport's tile.
2493 * If two towns have the same distance, town with lower index is returned.
2494 * @param station existing station with airport
2495 * @param[out] mindist Minimum distance to town
2496 * @return nearest town to airport
2498 static Town
*AirportGetNearestTown(const Station
*st
, uint
&mindist
)
2500 return AirportGetNearestTown(st
->airport
.GetSpec(), st
->airport
.rotation
, st
->airport
.tile
, AirportTileIterator(st
), mindist
);
2504 /** Recalculate the noise generated by the airports of each town */
2505 void UpdateAirportsNoise()
2507 for (Town
*t
: Town::Iterate()) t
->noise_reached
= 0;
2509 for (const Station
*st
: Station::Iterate()) {
2510 if (st
->airport
.tile
!= INVALID_TILE
&& st
->airport
.type
!= AT_OILRIG
) {
2512 Town
*nearest
= AirportGetNearestTown(st
, dist
);
2513 nearest
->noise_reached
+= GetAirportNoiseLevelForDistance(st
->airport
.GetSpec(), dist
);
2520 * @param flags operation to perform
2521 * @param tile tile where airport will be built
2522 * @param airport_type airport type, @see airport.h
2523 * @param layout airport layout
2524 * @param station_to_join station ID to join (NEW_STATION if build new one)
2525 * @param allow_adjacent allow airports directly adjacent to other airports.
2526 * @return the cost of this operation or an error
2528 CommandCost
CmdBuildAirport(DoCommandFlag flags
, TileIndex tile
, uint8_t airport_type
, uint8_t layout
, StationID station_to_join
, bool allow_adjacent
)
2530 bool reuse
= (station_to_join
!= NEW_STATION
);
2531 if (!reuse
) station_to_join
= INVALID_STATION
;
2532 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2534 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2536 if (airport_type
>= NUM_AIRPORTS
) return CMD_ERROR
;
2538 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2539 if (ret
.Failed()) return ret
;
2541 /* Check if a valid, buildable airport was chosen for construction */
2542 const AirportSpec
*as
= AirportSpec::Get(airport_type
);
2543 if (!as
->IsAvailable() || layout
>= as
->layouts
.size()) return CMD_ERROR
;
2544 if (!as
->IsWithinMapBounds(layout
, tile
)) return CMD_ERROR
;
2546 Direction rotation
= as
->layouts
[layout
].rotation
;
2549 if (rotation
== DIR_E
|| rotation
== DIR_W
) Swap(w
, h
);
2550 TileArea airport_area
= TileArea(tile
, w
, h
);
2552 if (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
) {
2553 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
2556 AirportTileTableIterator
tile_iter(as
->layouts
[layout
].tiles
.data(), tile
);
2557 CommandCost cost
= CheckFlatLandAirport(tile_iter
, flags
);
2558 if (cost
.Failed()) return cost
;
2560 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2562 Town
*nearest
= AirportGetNearestTown(as
, rotation
, tile
, std::move(tile_iter
), dist
);
2563 uint newnoise_level
= GetAirportNoiseLevelForDistance(as
, dist
);
2565 /* Check if local auth would allow a new airport */
2566 StringID authority_refuse_message
= STR_NULL
;
2567 Town
*authority_refuse_town
= nullptr;
2569 if (_settings_game
.economy
.station_noise_level
) {
2570 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2571 if ((nearest
->noise_reached
+ newnoise_level
) > nearest
->MaxTownNoise()) {
2572 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE
;
2573 authority_refuse_town
= nearest
;
2575 } else if (_settings_game
.difficulty
.town_council_tolerance
!= TOWN_COUNCIL_PERMISSIVE
) {
2576 Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
2578 for (const Station
*st
: Station::Iterate()) {
2579 if (st
->town
== t
&& (st
->facilities
& FACIL_AIRPORT
) && st
->airport
.type
!= AT_OILRIG
) num
++;
2582 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT
;
2583 authority_refuse_town
= t
;
2587 if (authority_refuse_message
!= STR_NULL
) {
2588 SetDParam(0, authority_refuse_town
->index
);
2589 return_cmd_error(authority_refuse_message
);
2592 Station
*st
= nullptr;
2593 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, allow_adjacent
, airport_area
, &st
);
2594 if (ret
.Failed()) return ret
;
2597 if (st
== nullptr && distant_join
) st
= Station::GetIfValid(station_to_join
);
2599 ret
= BuildStationPart(&st
, flags
, reuse
, airport_area
, (GetAirport(airport_type
)->flags
& AirportFTAClass::AIRPLANES
) ? STATIONNAMING_AIRPORT
: STATIONNAMING_HELIPORT
);
2600 if (ret
.Failed()) return ret
;
2602 if (st
!= nullptr && st
->airport
.tile
!= INVALID_TILE
) {
2603 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT
);
2606 for (AirportTileTableIterator
iter(as
->layouts
[layout
].tiles
.data(), tile
); iter
!= INVALID_TILE
; ++iter
) {
2607 cost
.AddCost(_price
[PR_BUILD_STATION_AIRPORT
]);
2610 if (flags
& DC_EXEC
) {
2611 /* Always add the noise, so there will be no need to recalculate when option toggles */
2612 nearest
->noise_reached
+= newnoise_level
;
2614 st
->AddFacility(FACIL_AIRPORT
, tile
);
2615 st
->airport
.type
= airport_type
;
2616 st
->airport
.layout
= layout
;
2617 st
->airport
.flags
= 0;
2618 st
->airport
.rotation
= rotation
;
2620 st
->rect
.BeforeAddRect(tile
, w
, h
, StationRect::ADD_TRY
);
2622 for (AirportTileTableIterator
iter(as
->layouts
[layout
].tiles
.data(), tile
); iter
!= INVALID_TILE
; ++iter
) {
2624 MakeAirport(t
, st
->owner
, st
->index
, iter
.GetStationGfx(), WATER_CLASS_INVALID
);
2625 SetStationTileRandomBits(t
, GB(Random(), 0, 4));
2626 st
->airport
.Add(iter
);
2628 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter
.GetStationGfx()))->animation
.status
!= ANIM_STATUS_NO_ANIMATION
) AddAnimatedTile(t
);
2631 /* Only call the animation trigger after all tiles have been built */
2632 for (AirportTileTableIterator
iter(as
->layouts
[layout
].tiles
.data(), tile
); iter
!= INVALID_TILE
; ++iter
) {
2633 AirportTileAnimationTrigger(st
, iter
, AAT_BUILT
);
2636 UpdateAirplanesOnNewStation(st
);
2638 Company::Get(st
->owner
)->infrastructure
.airport
++;
2640 st
->AfterStationTileSetChange(true, STATION_AIRPORT
);
2641 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2643 if (_settings_game
.economy
.station_noise_level
) {
2644 SetWindowDirty(WC_TOWN_VIEW
, nearest
->index
);
2653 * @param tile TileIndex been queried
2654 * @param flags operation to perform
2655 * @return cost or failure of operation
2657 static CommandCost
RemoveAirport(TileIndex tile
, DoCommandFlag flags
)
2659 Station
*st
= Station::GetByTile(tile
);
2661 if (_current_company
!= OWNER_WATER
) {
2662 CommandCost ret
= CheckOwnership(st
->owner
);
2663 if (ret
.Failed()) return ret
;
2666 tile
= st
->airport
.tile
;
2668 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2670 for (const Aircraft
*a
: Aircraft::Iterate()) {
2671 if (!a
->IsNormalAircraft()) continue;
2672 if (a
->targetairport
== st
->index
&& a
->state
!= FLYING
) {
2673 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY
);
2677 if (flags
& DC_EXEC
) {
2678 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2679 TileIndex tile_cur
= st
->airport
.GetHangarTile(i
);
2680 OrderBackup::Reset(tile_cur
, false);
2681 CloseWindowById(WC_VEHICLE_DEPOT
, tile_cur
);
2684 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2685 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2686 * need of recalculation */
2688 Town
*nearest
= AirportGetNearestTown(st
, dist
);
2689 nearest
->noise_reached
-= GetAirportNoiseLevelForDistance(st
->airport
.GetSpec(), dist
);
2691 if (_settings_game
.economy
.station_noise_level
) {
2692 SetWindowDirty(WC_TOWN_VIEW
, nearest
->index
);
2696 for (TileIndex tile_cur
: st
->airport
) {
2697 if (!st
->TileBelongsToAirport(tile_cur
)) continue;
2699 CommandCost ret
= EnsureNoVehicleOnGround(tile_cur
);
2700 if (ret
.Failed()) return ret
;
2702 cost
.AddCost(_price
[PR_CLEAR_STATION_AIRPORT
]);
2704 if (flags
& DC_EXEC
) {
2705 DeleteAnimatedTile(tile_cur
);
2706 DoClearSquare(tile_cur
);
2707 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
.base());
2711 if (flags
& DC_EXEC
) {
2712 /* Clear the persistent storage. */
2713 delete st
->airport
.psa
;
2715 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2717 st
->airport
.Clear();
2718 st
->facilities
&= ~FACIL_AIRPORT
;
2719 SetWindowClassesDirty(WC_VEHICLE_ORDERS
);
2721 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2723 Company::Get(st
->owner
)->infrastructure
.airport
--;
2725 st
->AfterStationTileSetChange(false, STATION_AIRPORT
);
2727 DeleteNewGRFInspectWindow(GSF_AIRPORTS
, st
->index
);
2734 * Open/close an airport to incoming aircraft.
2735 * @param flags Operation to perform.
2736 * @param station_id Station ID of the airport.
2737 * @return the cost of this operation or an error
2739 CommandCost
CmdOpenCloseAirport(DoCommandFlag flags
, StationID station_id
)
2741 if (!Station::IsValidID(station_id
)) return CMD_ERROR
;
2742 Station
*st
= Station::Get(station_id
);
2744 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->owner
== OWNER_NONE
) return CMD_ERROR
;
2746 CommandCost ret
= CheckOwnership(st
->owner
);
2747 if (ret
.Failed()) return ret
;
2749 if (flags
& DC_EXEC
) {
2750 st
->airport
.flags
^= AIRPORT_CLOSED_block
;
2751 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_CLOSE_AIRPORT
);
2753 return CommandCost();
2757 * Tests whether the company's vehicles have this station in orders
2758 * @param station station ID
2759 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2760 * @param company company ID
2762 bool HasStationInUse(StationID station
, bool include_company
, CompanyID company
)
2764 for (const OrderList
*orderlist
: OrderList::Iterate()) {
2765 const Vehicle
*v
= orderlist
->GetFirstSharedVehicle();
2766 assert(v
!= nullptr);
2767 if ((v
->owner
== company
) != include_company
) continue;
2769 for (const Order
*order
= orderlist
->GetFirstOrder(); order
!= nullptr; order
= order
->next
) {
2770 if (order
->GetDestination() == station
&& (order
->IsType(OT_GOTO_STATION
) || order
->IsType(OT_GOTO_WAYPOINT
))) {
2778 static const TileIndexDiffC _dock_tileoffs_chkaround
[] = {
2784 static const uint8_t _dock_w_chk
[4] = { 2, 1, 2, 1 };
2785 static const uint8_t _dock_h_chk
[4] = { 1, 2, 1, 2 };
2788 * Build a dock/haven.
2789 * @param flags operation to perform
2790 * @param tile tile where dock will be built
2791 * @param station_to_join station ID to join (NEW_STATION if build new one)
2792 * @param adjacent allow docks directly adjacent to other docks.
2793 * @return the cost of this operation or an error
2795 CommandCost
CmdBuildDock(DoCommandFlag flags
, TileIndex tile
, StationID station_to_join
, bool adjacent
)
2797 bool reuse
= (station_to_join
!= NEW_STATION
);
2798 if (!reuse
) station_to_join
= INVALID_STATION
;
2799 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2801 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2803 DiagDirection direction
= GetInclinedSlopeDirection(GetTileSlope(tile
));
2804 if (direction
== INVALID_DIAGDIR
) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2805 direction
= ReverseDiagDir(direction
);
2807 /* Docks cannot be placed on rapids */
2808 if (HasTileWaterGround(tile
)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2810 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2811 if (ret
.Failed()) return ret
;
2813 if (IsBridgeAbove(tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2815 CommandCost
cost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_STATION_DOCK
]);
2816 ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
2817 if (ret
.Failed()) return ret
;
2820 TileIndex tile_cur
= tile
+ TileOffsByDiagDir(direction
);
2822 if (!HasTileWaterGround(tile_cur
) || !IsTileFlat(tile_cur
)) {
2823 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2826 if (IsBridgeAbove(tile_cur
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2828 /* Get the water class of the water tile before it is cleared.*/
2829 WaterClass wc
= GetWaterClass(tile_cur
);
2831 bool add_cost
= !IsWaterTile(tile_cur
);
2832 ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile_cur
);
2833 if (ret
.Failed()) return ret
;
2834 if (add_cost
) cost
.AddCost(ret
);
2836 tile_cur
+= TileOffsByDiagDir(direction
);
2837 if (!IsTileType(tile_cur
, MP_WATER
) || !IsTileFlat(tile_cur
)) {
2838 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2841 TileArea dock_area
= TileArea(tile
+ ToTileIndexDiff(_dock_tileoffs_chkaround
[direction
]),
2842 _dock_w_chk
[direction
], _dock_h_chk
[direction
]);
2845 Station
*st
= nullptr;
2846 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, adjacent
, dock_area
, &st
);
2847 if (ret
.Failed()) return ret
;
2850 if (st
== nullptr && distant_join
) st
= Station::GetIfValid(station_to_join
);
2852 ret
= BuildStationPart(&st
, flags
, reuse
, dock_area
, STATIONNAMING_DOCK
);
2853 if (ret
.Failed()) return ret
;
2855 if (flags
& DC_EXEC
) {
2856 st
->ship_station
.Add(tile
);
2857 TileIndex flat_tile
= tile
+ TileOffsByDiagDir(direction
);
2858 st
->ship_station
.Add(flat_tile
);
2859 st
->AddFacility(FACIL_DOCK
, tile
);
2861 st
->rect
.BeforeAddRect(dock_area
.tile
, dock_area
.w
, dock_area
.h
, StationRect::ADD_TRY
);
2863 /* If the water part of the dock is on a canal, update infrastructure counts.
2864 * This is needed as we've cleared that tile before.
2865 * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
2866 * See: MakeWaterKeepingClass() */
2867 if (wc
== WATER_CLASS_CANAL
&& !(HasTileWaterClass(flat_tile
) && GetWaterClass(flat_tile
) == WATER_CLASS_CANAL
&& IsTileOwner(flat_tile
, _current_company
))) {
2868 Company::Get(st
->owner
)->infrastructure
.water
++;
2870 Company::Get(st
->owner
)->infrastructure
.station
+= 2;
2872 MakeDock(tile
, st
->owner
, st
->index
, direction
, wc
);
2873 UpdateStationDockingTiles(st
);
2875 st
->AfterStationTileSetChange(true, STATION_DOCK
);
2881 void RemoveDockingTile(TileIndex t
)
2883 for (DiagDirection d
= DIAGDIR_BEGIN
; d
!= DIAGDIR_END
; d
++) {
2884 TileIndex tile
= t
+ TileOffsByDiagDir(d
);
2885 if (!IsValidTile(tile
)) continue;
2887 if (IsTileType(tile
, MP_STATION
)) {
2888 Station
*st
= Station::GetByTile(tile
);
2889 if (st
!= nullptr) UpdateStationDockingTiles(st
);
2890 } else if (IsTileType(tile
, MP_INDUSTRY
)) {
2891 Station
*neutral
= Industry::GetByTile(tile
)->neutral_station
;
2892 if (neutral
!= nullptr) UpdateStationDockingTiles(neutral
);
2898 * Clear docking tile status from tiles around a removed dock, if the tile has
2899 * no neighbours which would keep it as a docking tile.
2900 * @param tile Ex-dock tile to check.
2902 void ClearDockingTilesCheckingNeighbours(TileIndex tile
)
2904 assert(IsValidTile(tile
));
2906 /* Clear and maybe re-set docking tile */
2907 for (DiagDirection d
= DIAGDIR_BEGIN
; d
!= DIAGDIR_END
; d
++) {
2908 TileIndex docking_tile
= tile
+ TileOffsByDiagDir(d
);
2909 if (!IsValidTile(docking_tile
)) continue;
2911 if (IsPossibleDockingTile(docking_tile
)) {
2912 SetDockingTile(docking_tile
, false);
2913 CheckForDockingTile(docking_tile
);
2919 * Find the part of a dock that is land-based
2920 * @param t Dock tile to find land part of
2921 * @return tile of land part of dock
2923 static TileIndex
FindDockLandPart(TileIndex t
)
2925 assert(IsDockTile(t
));
2927 StationGfx gfx
= GetStationGfx(t
);
2928 if (gfx
< GFX_DOCK_BASE_WATER_PART
) return t
;
2930 for (DiagDirection d
= DIAGDIR_BEGIN
; d
!= DIAGDIR_END
; d
++) {
2931 TileIndex tile
= t
+ TileOffsByDiagDir(d
);
2932 if (!IsValidTile(tile
)) continue;
2933 if (!IsDockTile(tile
)) continue;
2934 if (GetStationGfx(tile
) < GFX_DOCK_BASE_WATER_PART
&& tile
+ TileOffsByDiagDir(GetDockDirection(tile
)) == t
) return tile
;
2937 return INVALID_TILE
;
2942 * @param tile TileIndex been queried
2943 * @param flags operation to perform
2944 * @return cost or failure of operation
2946 static CommandCost
RemoveDock(TileIndex tile
, DoCommandFlag flags
)
2948 Station
*st
= Station::GetByTile(tile
);
2949 CommandCost ret
= CheckOwnership(st
->owner
);
2950 if (ret
.Failed()) return ret
;
2952 if (!IsDockTile(tile
)) return CMD_ERROR
;
2954 TileIndex tile1
= FindDockLandPart(tile
);
2955 if (tile1
== INVALID_TILE
) return CMD_ERROR
;
2956 TileIndex tile2
= tile1
+ TileOffsByDiagDir(GetDockDirection(tile1
));
2958 ret
= EnsureNoVehicleOnGround(tile1
);
2959 if (ret
.Succeeded()) ret
= EnsureNoVehicleOnGround(tile2
);
2960 if (ret
.Failed()) return ret
;
2962 if (flags
& DC_EXEC
) {
2963 DoClearSquare(tile1
);
2964 MarkTileDirtyByTile(tile1
);
2965 MakeWaterKeepingClass(tile2
, st
->owner
);
2967 st
->rect
.AfterRemoveTile(st
, tile1
);
2968 st
->rect
.AfterRemoveTile(st
, tile2
);
2970 MakeShipStationAreaSmaller(st
);
2971 if (st
->ship_station
.tile
== INVALID_TILE
) {
2972 st
->ship_station
.Clear();
2973 st
->docking_station
.Clear();
2974 st
->facilities
&= ~FACIL_DOCK
;
2975 SetWindowClassesDirty(WC_VEHICLE_ORDERS
);
2978 Company::Get(st
->owner
)->infrastructure
.station
-= 2;
2980 st
->AfterStationTileSetChange(false, STATION_DOCK
);
2982 ClearDockingTilesCheckingNeighbours(tile1
);
2983 ClearDockingTilesCheckingNeighbours(tile2
);
2985 for (Ship
*s
: Ship::Iterate()) {
2986 /* Find all ships going to our dock. */
2987 if (s
->current_order
.GetDestination() != st
->index
) {
2991 /* Find ships that are marked as "loading" but are no longer on a
2992 * docking tile. Force them to leave the station (as they were loading
2993 * on the removed dock). */
2994 if (s
->current_order
.IsType(OT_LOADING
) && !(IsDockingTile(s
->tile
) && IsShipDestinationTile(s
->tile
, st
->index
))) {
2998 /* If we no longer have a dock, mark the order as invalid and send
2999 * the ship to the next order (or, if there is none, make it
3000 * wander the world). */
3001 if (s
->current_order
.IsType(OT_GOTO_STATION
) && !(st
->facilities
& FACIL_DOCK
)) {
3002 s
->SetDestTile(s
->GetOrderStationLocation(st
->index
));
3007 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_STATION_DOCK
]);
3010 #include "table/station_land.h"
3013 * Get station tile layout for a station type and its station gfx.
3014 * @param st Station type to draw.
3015 * @param gfx StationGfx of tile to draw.
3016 * @return Tile layout to draw.
3018 const DrawTileSprites
*GetStationTileLayout(StationType st
, uint8_t gfx
)
3020 const auto &layouts
= _station_display_datas
[st
];
3021 if (gfx
>= layouts
.size()) gfx
&= 1;
3022 return layouts
.data() + gfx
;
3026 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
3027 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
3028 * is set to the overlay to draw.
3029 * @param ti Positional info for the tile to decide snowyness etc. May be nullptr.
3030 * @param[in,out] ground Groundsprite to draw.
3031 * @param[out] overlay_offset Overlay to draw.
3032 * @return true if overlay can be drawn.
3034 bool SplitGroundSpriteForOverlay(const TileInfo
*ti
, SpriteID
*ground
, RailTrackOffset
*overlay_offset
)
3038 case SPR_RAIL_TRACK_X
:
3039 case SPR_MONO_TRACK_X
:
3040 case SPR_MGLV_TRACK_X
:
3041 snow_desert
= false;
3042 *overlay_offset
= RTO_X
;
3045 case SPR_RAIL_TRACK_Y
:
3046 case SPR_MONO_TRACK_Y
:
3047 case SPR_MGLV_TRACK_Y
:
3048 snow_desert
= false;
3049 *overlay_offset
= RTO_Y
;
3052 case SPR_RAIL_TRACK_X_SNOW
:
3053 case SPR_MONO_TRACK_X_SNOW
:
3054 case SPR_MGLV_TRACK_X_SNOW
:
3056 *overlay_offset
= RTO_X
;
3059 case SPR_RAIL_TRACK_Y_SNOW
:
3060 case SPR_MONO_TRACK_Y_SNOW
:
3061 case SPR_MGLV_TRACK_Y_SNOW
:
3063 *overlay_offset
= RTO_Y
;
3070 if (ti
!= nullptr) {
3071 /* Decide snow/desert from tile */
3072 switch (_settings_game
.game_creation
.landscape
) {
3074 snow_desert
= (uint
)ti
->z
> GetSnowLine() * TILE_HEIGHT
;
3078 snow_desert
= GetTropicZone(ti
->tile
) == TROPICZONE_DESERT
;
3086 *ground
= snow_desert
? SPR_FLAT_SNOW_DESERT_TILE
: SPR_FLAT_GRASS_TILE
;
3090 static void DrawTile_Station(TileInfo
*ti
)
3092 const NewGRFSpriteLayout
*layout
= nullptr;
3093 DrawTileSprites tmp_rail_layout
;
3094 const DrawTileSprites
*t
= nullptr;
3095 int32_t total_offset
;
3096 const RailTypeInfo
*rti
= nullptr;
3097 uint32_t relocation
= 0;
3098 uint32_t ground_relocation
= 0;
3099 BaseStation
*st
= nullptr;
3100 const StationSpec
*statspec
= nullptr;
3101 uint tile_layout
= 0;
3103 if (HasStationRail(ti
->tile
)) {
3104 rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
3105 total_offset
= rti
->GetRailtypeSpriteOffset();
3107 if (IsCustomStationSpecIndex(ti
->tile
)) {
3108 /* look for customization */
3109 st
= BaseStation::GetByTile(ti
->tile
);
3110 statspec
= st
->speclist
[GetCustomStationSpecIndex(ti
->tile
)].spec
;
3112 if (statspec
!= nullptr) {
3113 tile_layout
= GetStationGfx(ti
->tile
);
3115 if (HasBit(statspec
->callback_mask
, CBM_STATION_DRAW_TILE_LAYOUT
)) {
3116 uint16_t callback
= GetStationCallback(CBID_STATION_DRAW_TILE_LAYOUT
, 0, 0, statspec
, st
, ti
->tile
);
3117 if (callback
!= CALLBACK_FAILED
) tile_layout
= (callback
& ~1) + GetRailStationAxis(ti
->tile
);
3120 /* Ensure the chosen tile layout is valid for this custom station */
3121 if (!statspec
->renderdata
.empty()) {
3122 layout
= &statspec
->renderdata
[tile_layout
< statspec
->renderdata
.size() ? tile_layout
: (uint
)GetRailStationAxis(ti
->tile
)];
3123 if (!layout
->NeedsPreprocessing()) {
3134 StationGfx gfx
= GetStationGfx(ti
->tile
);
3135 if (IsAirport(ti
->tile
)) {
3136 gfx
= GetAirportGfx(ti
->tile
);
3137 if (gfx
>= NEW_AIRPORTTILE_OFFSET
) {
3138 const AirportTileSpec
*ats
= AirportTileSpec::Get(gfx
);
3139 if (ats
->grf_prop
.spritegroup
[0] != nullptr && DrawNewAirportTile(ti
, Station::GetByTile(ti
->tile
), ats
)) {
3142 /* No sprite group (or no valid one) found, meaning no graphics associated.
3143 * Use the substitute one instead */
3144 assert(ats
->grf_prop
.subst_id
!= INVALID_AIRPORTTILE
);
3145 gfx
= ats
->grf_prop
.subst_id
;
3148 case APT_RADAR_GRASS_FENCE_SW
:
3149 t
= &_station_display_datas_airport_radar_grass_fence_sw
[GetAnimationFrame(ti
->tile
)];
3151 case APT_GRASS_FENCE_NE_FLAG
:
3152 t
= &_station_display_datas_airport_flag_grass_fence_ne
[GetAnimationFrame(ti
->tile
)];
3154 case APT_RADAR_FENCE_SW
:
3155 t
= &_station_display_datas_airport_radar_fence_sw
[GetAnimationFrame(ti
->tile
)];
3157 case APT_RADAR_FENCE_NE
:
3158 t
= &_station_display_datas_airport_radar_fence_ne
[GetAnimationFrame(ti
->tile
)];
3160 case APT_GRASS_FENCE_NE_FLAG_2
:
3161 t
= &_station_display_datas_airport_flag_grass_fence_ne_2
[GetAnimationFrame(ti
->tile
)];
3166 Owner owner
= GetTileOwner(ti
->tile
);
3169 if (Company::IsValidID(owner
)) {
3170 palette
= COMPANY_SPRITE_COLOUR(owner
);
3172 /* Some stations are not owner by a company, namely oil rigs */
3173 palette
= PALETTE_TO_GREY
;
3176 if (layout
== nullptr && (t
== nullptr || t
->seq
== nullptr)) t
= GetStationTileLayout(GetStationType(ti
->tile
), gfx
);
3178 /* don't show foundation for docks */
3179 if (ti
->tileh
!= SLOPE_FLAT
&& !IsDock(ti
->tile
)) {
3180 if (statspec
!= nullptr && HasBit(statspec
->flags
, SSF_CUSTOM_FOUNDATIONS
)) {
3181 /* Station has custom foundations.
3182 * Check whether the foundation continues beyond the tile's upper sides. */
3184 auto [slope
, z
] = GetFoundationPixelSlope(ti
->tile
);
3185 if (!HasFoundationNW(ti
->tile
, slope
, z
)) SetBit(edge_info
, 0);
3186 if (!HasFoundationNE(ti
->tile
, slope
, z
)) SetBit(edge_info
, 1);
3187 SpriteID image
= GetCustomStationFoundationRelocation(statspec
, st
, ti
->tile
, tile_layout
, edge_info
);
3188 if (image
== 0) goto draw_default_foundation
;
3190 if (HasBit(statspec
->flags
, SSF_EXTENDED_FOUNDATIONS
)) {
3191 /* Station provides extended foundations. */
3193 static const uint8_t foundation_parts
[] = {
3194 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3195 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3196 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3197 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3200 AddSortableSpriteToDraw(image
+ foundation_parts
[ti
->tileh
], PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
3202 /* Draw simple foundations, built up from 8 possible foundation sprites. */
3204 /* Each set bit represents one of the eight composite sprites to be drawn.
3205 * 'Invalid' entries will not drawn but are included for completeness. */
3206 static const uint8_t composite_foundation_parts
[] = {
3207 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
3208 0x00, 0xD1, 0xE4, 0xE0,
3209 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
3210 0xCA, 0xC9, 0xC4, 0xC0,
3211 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
3212 0xD2, 0x91, 0xE4, 0xA0,
3213 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
3217 uint8_t parts
= composite_foundation_parts
[ti
->tileh
];
3219 /* If foundations continue beyond the tile's upper sides then
3220 * mask out the last two pieces. */
3221 if (HasBit(edge_info
, 0)) ClrBit(parts
, 6);
3222 if (HasBit(edge_info
, 1)) ClrBit(parts
, 7);
3225 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
3226 * correct offset for the childsprites.
3227 * So, draw the (completely empty) sprite of the default foundations. */
3228 goto draw_default_foundation
;
3231 StartSpriteCombine();
3232 for (int i
= 0; i
< 8; i
++) {
3233 if (HasBit(parts
, i
)) {
3234 AddSortableSpriteToDraw(image
+ i
, PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
3240 OffsetGroundSprite(0, -8);
3241 ti
->z
+= ApplyPixelFoundationToSlope(FOUNDATION_LEVELED
, ti
->tileh
);
3243 draw_default_foundation
:
3244 DrawFoundation(ti
, FOUNDATION_LEVELED
);
3248 bool draw_ground
= false;
3250 if (IsBuoy(ti
->tile
)) {
3251 DrawWaterClassGround(ti
);
3252 SpriteID sprite
= GetCanalSprite(CF_BUOY
, ti
->tile
);
3253 if (sprite
!= 0) total_offset
= sprite
- SPR_IMG_BUOY
;
3254 } else if (IsDock(ti
->tile
) || (IsOilRig(ti
->tile
) && IsTileOnWater(ti
->tile
))) {
3255 if (ti
->tileh
== SLOPE_FLAT
) {
3256 DrawWaterClassGround(ti
);
3258 assert(IsDock(ti
->tile
));
3259 TileIndex water_tile
= ti
->tile
+ TileOffsByDiagDir(GetDockDirection(ti
->tile
));
3260 WaterClass wc
= HasTileWaterClass(water_tile
) ? GetWaterClass(water_tile
) : WATER_CLASS_INVALID
;
3261 if (wc
== WATER_CLASS_SEA
) {
3262 DrawShoreTile(ti
->tileh
);
3264 DrawClearLandTile(ti
, 3);
3267 } else if (IsRoadWaypointTile(ti
->tile
)) {
3268 RoadBits bits
= AxisToRoadBits(GetDriveThroughStopAxis(ti
->tile
));
3269 RoadType road_rt
= GetRoadTypeRoad(ti
->tile
);
3270 RoadType tram_rt
= GetRoadTypeTram(ti
->tile
);
3271 RoadBits road
= (road_rt
!= INVALID_ROADTYPE
) ? bits
: ROAD_NONE
;
3272 RoadBits tram
= (tram_rt
!= INVALID_ROADTYPE
) ? bits
: ROAD_NONE
;
3273 const RoadTypeInfo
*road_rti
= (road_rt
!= INVALID_ROADTYPE
) ? GetRoadTypeInfo(road_rt
) : nullptr;
3274 const RoadTypeInfo
*tram_rti
= (tram_rt
!= INVALID_ROADTYPE
) ? GetRoadTypeInfo(tram_rt
) : nullptr;
3276 if (ti
->tileh
!= SLOPE_FLAT
) {
3277 DrawFoundation(ti
, FOUNDATION_LEVELED
);
3280 DrawRoadGroundSprites(ti
, road
, tram
, road_rti
, tram_rti
, GetRoadWaypointRoadside(ti
->tile
), IsRoadWaypointOnSnowOrDesert(ti
->tile
));
3282 if (layout
!= nullptr) {
3283 /* Sprite layout which needs preprocessing */
3284 bool separate_ground
= HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
);
3285 uint32_t var10_values
= layout
->PrepareLayout(total_offset
, rti
->fallback_railtype
, 0, 0, separate_ground
);
3286 for (uint8_t var10
: SetBitIterator(var10_values
)) {
3287 uint32_t var10_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, var10
);
3288 layout
->ProcessRegisters(var10
, var10_relocation
, separate_ground
);
3290 tmp_rail_layout
.seq
= layout
->GetLayout(&tmp_rail_layout
.ground
);
3291 t
= &tmp_rail_layout
;
3293 } else if (statspec
!= nullptr) {
3294 /* Simple sprite layout */
3295 ground_relocation
= relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 0);
3296 if (HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
)) {
3297 ground_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 1);
3299 ground_relocation
+= rti
->fallback_railtype
;
3305 if (draw_ground
&& !IsAnyRoadStop(ti
->tile
)) {
3306 SpriteID image
= t
->ground
.sprite
;
3307 PaletteID pal
= t
->ground
.pal
;
3308 RailTrackOffset overlay_offset
;
3309 if (rti
!= nullptr && rti
->UsesOverlay() && SplitGroundSpriteForOverlay(ti
, &image
, &overlay_offset
)) {
3310 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
);
3311 DrawGroundSprite(image
, PAL_NONE
);
3312 DrawGroundSprite(ground
+ overlay_offset
, PAL_NONE
);
3314 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationReservation(ti
->tile
)) {
3315 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
3316 DrawGroundSprite(overlay
+ overlay_offset
, PALETTE_CRASH
);
3319 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
3320 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
3321 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
));
3323 /* PBS debugging, draw reserved tracks darker */
3324 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationRail(ti
->tile
) && HasStationReservation(ti
->tile
)) {
3325 DrawGroundSprite(GetRailStationAxis(ti
->tile
) == AXIS_X
? rti
->base_sprites
.single_x
: rti
->base_sprites
.single_y
, PALETTE_CRASH
);
3330 if (HasStationRail(ti
->tile
) && HasRailCatenaryDrawn(GetRailType(ti
->tile
))) DrawRailCatenary(ti
);
3332 if (IsAnyRoadStop(ti
->tile
)) {
3333 RoadType road_rt
= GetRoadTypeRoad(ti
->tile
);
3334 RoadType tram_rt
= GetRoadTypeTram(ti
->tile
);
3335 const RoadTypeInfo
*road_rti
= road_rt
== INVALID_ROADTYPE
? nullptr : GetRoadTypeInfo(road_rt
);
3336 const RoadTypeInfo
*tram_rti
= tram_rt
== INVALID_ROADTYPE
? nullptr : GetRoadTypeInfo(tram_rt
);
3338 StationGfx view
= GetStationGfx(ti
->tile
);
3339 StationType type
= GetStationType(ti
->tile
);
3341 const RoadStopSpec
*stopspec
= GetRoadStopSpec(ti
->tile
);
3342 RoadStopDrawMode stop_draw_mode
{};
3343 if (stopspec
!= nullptr) {
3344 stop_draw_mode
= stopspec
->draw_mode
;
3345 st
= BaseStation::GetByTile(ti
->tile
);
3346 RoadStopResolverObject
object(stopspec
, st
, ti
->tile
, INVALID_ROADTYPE
, type
, view
);
3347 const SpriteGroup
*group
= object
.Resolve();
3348 if (group
!= nullptr && group
->type
== SGT_TILELAYOUT
) {
3349 if (HasBit(stopspec
->flags
, RSF_DRAW_MODE_REGISTER
)) {
3350 stop_draw_mode
= static_cast<RoadStopDrawMode
>(GetRegister(0x100));
3352 if (type
== STATION_ROADWAYPOINT
&& (stop_draw_mode
& ROADSTOP_DRAW_MODE_WAYP_GROUND
)) {
3355 t
= ((const TileLayoutSpriteGroup
*)group
)->ProcessRegisters(nullptr);
3359 /* Draw ground sprite */
3361 SpriteID image
= t
->ground
.sprite
;
3362 PaletteID pal
= t
->ground
.pal
;
3363 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
3364 if (GB(image
, 0, SPRITE_WIDTH
) != 0) {
3365 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
3366 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
));
3370 if (IsDriveThroughStopTile(ti
->tile
)) {
3371 if (type
!= STATION_ROADWAYPOINT
&& (stopspec
== nullptr || (stop_draw_mode
& ROADSTOP_DRAW_MODE_OVERLAY
) != 0)) {
3372 uint sprite_offset
= GetDriveThroughStopAxis(ti
->tile
) == AXIS_X
? 1 : 0;
3373 DrawRoadOverlays(ti
, PAL_NONE
, road_rti
, tram_rti
, sprite_offset
, sprite_offset
);
3376 /* Non-drivethrough road stops are only valid for roads. */
3377 assert(road_rt
!= INVALID_ROADTYPE
&& tram_rt
== INVALID_ROADTYPE
);
3379 if ((stopspec
== nullptr || (stop_draw_mode
& ROADSTOP_DRAW_MODE_ROAD
) != 0) && road_rti
->UsesOverlay()) {
3380 SpriteID ground
= GetCustomRoadSprite(road_rti
, ti
->tile
, ROTSG_ROADSTOP
);
3381 DrawGroundSprite(ground
+ view
, PAL_NONE
);
3385 if (stopspec
== nullptr || !HasBit(stopspec
->flags
, RSF_NO_CATENARY
)) {
3386 /* Draw road, tram catenary */
3387 DrawRoadCatenary(ti
);
3391 if (IsRailWaypoint(ti
->tile
)) {
3392 /* Don't offset the waypoint graphics; they're always the same. */
3396 DrawRailTileSeq(ti
, t
, TO_BUILDINGS
, total_offset
, relocation
, palette
);
3399 void StationPickerDrawSprite(int x
, int y
, StationType st
, RailType railtype
, RoadType roadtype
, int image
)
3401 int32_t total_offset
= 0;
3402 PaletteID pal
= COMPANY_SPRITE_COLOUR(_local_company
);
3403 const DrawTileSprites
*t
= GetStationTileLayout(st
, image
);
3404 const RailTypeInfo
*railtype_info
= nullptr;
3406 if (railtype
!= INVALID_RAILTYPE
) {
3407 railtype_info
= GetRailTypeInfo(railtype
);
3408 total_offset
= railtype_info
->GetRailtypeSpriteOffset();
3411 SpriteID img
= t
->ground
.sprite
;
3412 RailTrackOffset overlay_offset
;
3413 if (railtype_info
!= nullptr && railtype_info
->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img
, &overlay_offset
)) {
3414 SpriteID ground
= GetCustomRailSprite(railtype_info
, INVALID_TILE
, RTSG_GROUND
);
3415 DrawSprite(img
, PAL_NONE
, x
, y
);
3416 DrawSprite(ground
+ overlay_offset
, PAL_NONE
, x
, y
);
3418 DrawSprite(img
+ total_offset
, HasBit(img
, PALETTE_MODIFIER_COLOUR
) ? pal
: PAL_NONE
, x
, y
);
3421 if (roadtype
!= INVALID_ROADTYPE
) {
3422 const RoadTypeInfo
*roadtype_info
= GetRoadTypeInfo(roadtype
);
3424 /* Drive-through stop */
3425 uint sprite_offset
= 5 - image
;
3427 /* Road underlay takes precedence over tram */
3428 if (roadtype_info
->UsesOverlay()) {
3429 SpriteID ground
= GetCustomRoadSprite(roadtype_info
, INVALID_TILE
, ROTSG_GROUND
);
3430 DrawSprite(ground
+ sprite_offset
, PAL_NONE
, x
, y
);
3432 SpriteID overlay
= GetCustomRoadSprite(roadtype_info
, INVALID_TILE
, ROTSG_OVERLAY
);
3433 if (overlay
) DrawSprite(overlay
+ sprite_offset
, PAL_NONE
, x
, y
);
3434 } else if (RoadTypeIsTram(roadtype
)) {
3435 DrawSprite(SPR_TRAMWAY_TRAM
+ sprite_offset
, PAL_NONE
, x
, y
);
3439 if (RoadTypeIsRoad(roadtype
) && roadtype_info
->UsesOverlay()) {
3440 SpriteID ground
= GetCustomRoadSprite(roadtype_info
, INVALID_TILE
, ROTSG_ROADSTOP
);
3441 DrawSprite(ground
+ image
, PAL_NONE
, x
, y
);
3446 /* Default waypoint has no railtype specific sprites */
3447 DrawRailTileSeqInGUI(x
, y
, t
, (st
== STATION_WAYPOINT
|| st
== STATION_ROADWAYPOINT
) ? 0 : total_offset
, 0, pal
);
3450 static int GetSlopePixelZ_Station(TileIndex tile
, uint
, uint
, bool)
3452 return GetTileMaxPixelZ(tile
);
3455 static Foundation
GetFoundation_Station(TileIndex
, Slope tileh
)
3457 return FlatteningFoundation(tileh
);
3460 static void FillTileDescRoadStop(TileIndex tile
, TileDesc
*td
)
3462 RoadType road_rt
= GetRoadTypeRoad(tile
);
3463 RoadType tram_rt
= GetRoadTypeTram(tile
);
3464 Owner road_owner
= INVALID_OWNER
;
3465 Owner tram_owner
= INVALID_OWNER
;
3466 if (road_rt
!= INVALID_ROADTYPE
) {
3467 const RoadTypeInfo
*rti
= GetRoadTypeInfo(road_rt
);
3468 td
->roadtype
= rti
->strings
.name
;
3469 td
->road_speed
= rti
->max_speed
/ 2;
3470 road_owner
= GetRoadOwner(tile
, RTT_ROAD
);
3473 if (tram_rt
!= INVALID_ROADTYPE
) {
3474 const RoadTypeInfo
*rti
= GetRoadTypeInfo(tram_rt
);
3475 td
->tramtype
= rti
->strings
.name
;
3476 td
->tram_speed
= rti
->max_speed
/ 2;
3477 tram_owner
= GetRoadOwner(tile
, RTT_TRAM
);
3480 if (IsDriveThroughStopTile(tile
)) {
3481 /* Is there a mix of owners? */
3482 if ((tram_owner
!= INVALID_OWNER
&& tram_owner
!= td
->owner
[0]) ||
3483 (road_owner
!= INVALID_OWNER
&& road_owner
!= td
->owner
[0])) {
3485 if (road_owner
!= INVALID_OWNER
) {
3486 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_ROAD_OWNER
;
3487 td
->owner
[i
] = road_owner
;
3490 if (tram_owner
!= INVALID_OWNER
) {
3491 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_TRAM_OWNER
;
3492 td
->owner
[i
] = tram_owner
;
3498 void FillTileDescRailStation(TileIndex tile
, TileDesc
*td
)
3500 const StationSpec
*spec
= GetStationSpec(tile
);
3502 if (spec
!= nullptr) {
3503 td
->station_class
= StationClass::Get(spec
->class_index
)->name
;
3504 td
->station_name
= spec
->name
;
3506 if (spec
->grf_prop
.grffile
!= nullptr) {
3507 const GRFConfig
*gc
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
);
3508 td
->grf
= gc
->GetName();
3512 const RailTypeInfo
*rti
= GetRailTypeInfo(GetRailType(tile
));
3513 td
->rail_speed
= rti
->max_speed
;
3514 td
->railtype
= rti
->strings
.name
;
3517 void FillTileDescAirport(TileIndex tile
, TileDesc
*td
)
3519 const AirportSpec
*as
= Station::GetByTile(tile
)->airport
.GetSpec();
3520 td
->airport_class
= AirportClass::Get(as
->class_index
)->name
;
3521 td
->airport_name
= as
->name
;
3523 const AirportTileSpec
*ats
= AirportTileSpec::GetByTile(tile
);
3524 td
->airport_tile_name
= ats
->name
;
3526 if (as
->grf_prop
.grffile
!= nullptr) {
3527 const GRFConfig
*gc
= GetGRFConfig(as
->grf_prop
.grffile
->grfid
);
3528 td
->grf
= gc
->GetName();
3529 } else if (ats
->grf_prop
.grffile
!= nullptr) {
3530 const GRFConfig
*gc
= GetGRFConfig(ats
->grf_prop
.grffile
->grfid
);
3531 td
->grf
= gc
->GetName();
3535 static void GetTileDesc_Station(TileIndex tile
, TileDesc
*td
)
3537 td
->owner
[0] = GetTileOwner(tile
);
3538 td
->build_date
= BaseStation::GetByTile(tile
)->build_date
;
3540 if (IsAnyRoadStop(tile
)) FillTileDescRoadStop(tile
, td
);
3541 if (HasStationRail(tile
)) FillTileDescRailStation(tile
, td
);
3542 if (IsAirport(tile
)) FillTileDescAirport(tile
, td
);
3545 switch (GetStationType(tile
)) {
3546 default: NOT_REACHED();
3547 case STATION_RAIL
: str
= STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION
; break;
3548 case STATION_AIRPORT
:
3549 str
= (IsHangar(tile
) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR
: STR_LAI_STATION_DESCRIPTION_AIRPORT
);
3551 case STATION_TRUCK
: str
= STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA
; break;
3552 case STATION_BUS
: str
= STR_LAI_STATION_DESCRIPTION_BUS_STATION
; break;
3553 case STATION_OILRIG
: {
3554 const Industry
*i
= Station::GetByTile(tile
)->industry
;
3555 const IndustrySpec
*is
= GetIndustrySpec(i
->type
);
3556 td
->owner
[0] = i
->owner
;
3558 if (is
->grf_prop
.grffile
!= nullptr) td
->grf
= GetGRFConfig(is
->grf_prop
.grffile
->grfid
)->GetName();
3561 case STATION_DOCK
: str
= STR_LAI_STATION_DESCRIPTION_SHIP_DOCK
; break;
3562 case STATION_BUOY
: str
= STR_LAI_STATION_DESCRIPTION_BUOY
; break;
3563 case STATION_WAYPOINT
: str
= STR_LAI_STATION_DESCRIPTION_WAYPOINT
; break;
3564 case STATION_ROADWAYPOINT
: str
= STR_LAI_STATION_DESCRIPTION_WAYPOINT
; break;
3570 static TrackStatus
GetTileTrackStatus_Station(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
3572 TrackBits trackbits
= TRACK_BIT_NONE
;
3575 case TRANSPORT_RAIL
:
3576 if (HasStationRail(tile
) && !IsStationTileBlocked(tile
)) {
3577 trackbits
= TrackToTrackBits(GetRailStationTrack(tile
));
3581 case TRANSPORT_WATER
:
3582 /* buoy is coded as a station, it is always on open water */
3584 trackbits
= TRACK_BIT_ALL
;
3585 /* remove tracks that connect NE map edge */
3586 if (TileX(tile
) == 0) trackbits
&= ~(TRACK_BIT_X
| TRACK_BIT_UPPER
| TRACK_BIT_RIGHT
);
3587 /* remove tracks that connect NW map edge */
3588 if (TileY(tile
) == 0) trackbits
&= ~(TRACK_BIT_Y
| TRACK_BIT_LEFT
| TRACK_BIT_UPPER
);
3592 case TRANSPORT_ROAD
:
3593 if (IsAnyRoadStop(tile
)) {
3594 RoadTramType rtt
= (RoadTramType
)sub_mode
;
3595 if (!HasTileRoadType(tile
, rtt
)) break;
3597 if (IsBayRoadStopTile(tile
)) {
3598 DiagDirection dir
= GetBayRoadStopDir(tile
);
3599 if (side
!= INVALID_DIAGDIR
&& dir
!= side
) break;
3600 trackbits
= DiagDirToDiagTrackBits(dir
);
3602 Axis axis
= GetDriveThroughStopAxis(tile
);
3603 if (side
!= INVALID_DIAGDIR
&& axis
!= DiagDirToAxis(side
)) break;
3604 trackbits
= AxisToTrackBits(axis
);
3613 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits
), TRACKDIR_BIT_NONE
);
3617 static void TileLoop_Station(TileIndex tile
)
3619 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3620 * hardcoded.....not good */
3621 switch (GetStationType(tile
)) {
3622 case STATION_AIRPORT
:
3623 AirportTileAnimationTrigger(Station::GetByTile(tile
), tile
, AAT_TILELOOP
);
3627 if (!IsTileFlat(tile
)) break; // only handle water part
3630 case STATION_OILRIG
: //(station part)
3632 TileLoop_Water(tile
);
3635 case STATION_ROADWAYPOINT
: {
3636 switch (_settings_game
.game_creation
.landscape
) {
3638 if (IsRoadWaypointOnSnowOrDesert(tile
) != (GetTileZ(tile
) > GetSnowLine())) {
3639 ToggleRoadWaypointOnSnowOrDesert(tile
);
3640 MarkTileDirtyByTile(tile
);
3645 if (GetTropicZone(tile
) == TROPICZONE_DESERT
&& !IsRoadWaypointOnSnowOrDesert(tile
)) {
3646 ToggleRoadWaypointOnSnowOrDesert(tile
);
3647 MarkTileDirtyByTile(tile
);
3654 HouseZonesBits new_zone
= HZB_TOWN_EDGE
;
3655 const Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
3657 new_zone
= GetTownRadiusGroup(t
, tile
);
3660 /* Adjust road ground type depending on 'new_zone' */
3661 Roadside new_rs
= new_zone
> HZB_TOWN_EDGE
? ROADSIDE_PAVED
: ROADSIDE_GRASS
;
3662 Roadside cur_rs
= GetRoadWaypointRoadside(tile
);
3664 if (new_rs
!= cur_rs
) {
3665 SetRoadWaypointRoadside(tile
, cur_rs
== ROADSIDE_BARREN
? new_rs
: ROADSIDE_BARREN
);
3666 MarkTileDirtyByTile(tile
);
3676 static void AnimateTile_Station(TileIndex tile
)
3678 if (HasStationRail(tile
)) {
3679 AnimateStationTile(tile
);
3683 if (IsAirport(tile
)) {
3684 AnimateAirportTile(tile
);
3688 if (IsAnyRoadStopTile(tile
)) {
3689 AnimateRoadStopTile(tile
);
3695 static bool ClickTile_Station(TileIndex tile
)
3697 const BaseStation
*bst
= BaseStation::GetByTile(tile
);
3699 if (bst
->facilities
& FACIL_WAYPOINT
) {
3700 ShowWaypointWindow(Waypoint::From(bst
));
3701 } else if (IsHangar(tile
)) {
3702 const Station
*st
= Station::From(bst
);
3703 ShowDepotWindow(st
->airport
.GetHangarTile(st
->airport
.GetHangarNum(tile
)), VEH_AIRCRAFT
);
3705 ShowStationViewWindow(bst
->index
);
3710 static VehicleEnterTileStatus
VehicleEnter_Station(Vehicle
*v
, TileIndex tile
, int x
, int y
)
3712 if (v
->type
== VEH_TRAIN
) {
3713 StationID station_id
= GetStationIndex(tile
);
3714 if (!v
->current_order
.ShouldStopAtStation(v
, station_id
)) return VETSB_CONTINUE
;
3715 if (!IsRailStation(tile
) || !v
->IsFrontEngine()) return VETSB_CONTINUE
;
3719 int stop
= GetTrainStopLocation(station_id
, tile
, Train::From(v
), &station_ahead
, &station_length
);
3721 /* Stop whenever that amount of station ahead + the distance from the
3722 * begin of the platform to the stop location is longer than the length
3723 * of the platform. Station ahead 'includes' the current tile where the
3724 * vehicle is on, so we need to subtract that. */
3725 if (stop
+ station_ahead
- (int)TILE_SIZE
>= station_length
) return VETSB_CONTINUE
;
3727 DiagDirection dir
= DirToDiagDir(v
->direction
);
3732 if (DiagDirToAxis(dir
) != AXIS_X
) Swap(x
, y
);
3733 if (y
== TILE_SIZE
/ 2) {
3734 if (dir
!= DIAGDIR_SE
&& dir
!= DIAGDIR_SW
) x
= TILE_SIZE
- 1 - x
;
3735 stop
&= TILE_SIZE
- 1;
3738 return VETSB_ENTERED_STATION
| (VehicleEnterTileStatus
)(station_id
<< VETS_STATION_ID_OFFSET
); // enter station
3739 } else if (x
< stop
) {
3740 v
->vehstatus
|= VS_TRAIN_SLOWING
;
3741 uint16_t spd
= std::max(0, (stop
- x
) * 20 - 15);
3742 if (spd
< v
->cur_speed
) v
->cur_speed
= spd
;
3745 } else if (v
->type
== VEH_ROAD
) {
3746 RoadVehicle
*rv
= RoadVehicle::From(v
);
3747 if (rv
->state
< RVSB_IN_ROAD_STOP
&& !IsReversingRoadTrackdir((Trackdir
)rv
->state
) && rv
->frame
== 0) {
3748 if (IsStationRoadStop(tile
) && rv
->IsFrontEngine()) {
3749 /* Attempt to allocate a parking bay in a road stop */
3750 return RoadStop::GetByTile(tile
, GetRoadStopType(tile
))->Enter(rv
) ? VETSB_CONTINUE
: VETSB_CANNOT_ENTER
;
3755 return VETSB_CONTINUE
;
3759 * Run the watched cargo callback for all houses in the catchment area.
3760 * @param st Station.
3762 void TriggerWatchedCargoCallbacks(Station
*st
)
3764 /* Collect cargoes accepted since the last big tick. */
3765 CargoTypes cargoes
= 0;
3766 for (CargoID cid
= 0; cid
< NUM_CARGO
; cid
++) {
3767 if (HasBit(st
->goods
[cid
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
)) SetBit(cargoes
, cid
);
3770 /* Anything to do? */
3771 if (cargoes
== 0) return;
3773 /* Loop over all houses in the catchment. */
3774 BitmapTileIterator
it(st
->catchment_tiles
);
3775 for (TileIndex tile
= it
; tile
!= INVALID_TILE
; tile
= ++it
) {
3776 if (IsTileType(tile
, MP_HOUSE
)) {
3777 WatchedCargoCallback(tile
, cargoes
);
3783 * This function is called for each station once every 250 ticks.
3784 * Not all stations will get the tick at the same time.
3785 * @param st the station receiving the tick.
3786 * @return true if the station is still valid (wasn't deleted)
3788 static bool StationHandleBigTick(BaseStation
*st
)
3790 if (!st
->IsInUse()) {
3791 if (++st
->delete_ctr
>= 8) delete st
;
3795 if (Station::IsExpected(st
)) {
3796 TriggerWatchedCargoCallbacks(Station::From(st
));
3798 for (GoodsEntry
&ge
: Station::From(st
)->goods
) {
3799 ClrBit(ge
.status
, GoodsEntry::GES_ACCEPTED_BIGTICK
);
3804 if ((st
->facilities
& FACIL_WAYPOINT
) == 0) UpdateStationAcceptance(Station::From(st
), true);
3809 static inline void byte_inc_sat(uint8_t *p
)
3816 * Truncate the cargo by a specific amount.
3817 * @param cs The type of cargo to perform the truncation for.
3818 * @param ge The goods entry, of the station, to truncate.
3819 * @param amount The amount to truncate the cargo by.
3821 static void TruncateCargo(const CargoSpec
*cs
, GoodsEntry
*ge
, uint amount
= UINT_MAX
)
3823 /* If truncating also punish the source stations' ratings to
3824 * decrease the flow of incoming cargo. */
3826 StationCargoAmountMap waiting_per_source
;
3827 ge
->cargo
.Truncate(amount
, &waiting_per_source
);
3828 for (StationCargoAmountMap::iterator
i(waiting_per_source
.begin()); i
!= waiting_per_source
.end(); ++i
) {
3829 Station
*source_station
= Station::GetIfValid(i
->first
);
3830 if (source_station
== nullptr) continue;
3832 GoodsEntry
&source_ge
= source_station
->goods
[cs
->Index()];
3833 source_ge
.max_waiting_cargo
= std::max(source_ge
.max_waiting_cargo
, i
->second
);
3837 static void UpdateStationRating(Station
*st
)
3839 bool waiting_changed
= false;
3841 byte_inc_sat(&st
->time_since_load
);
3842 byte_inc_sat(&st
->time_since_unload
);
3844 for (const CargoSpec
*cs
: CargoSpec::Iterate()) {
3845 GoodsEntry
*ge
= &st
->goods
[cs
->Index()];
3846 /* Slowly increase the rating back to its original level in the case we
3847 * didn't deliver cargo yet to this station. This happens when a bribe
3848 * failed while you didn't moved that cargo yet to a station. */
3849 if (!ge
->HasRating() && ge
->rating
< INITIAL_STATION_RATING
) {
3853 /* Only change the rating if we are moving this cargo */
3854 if (ge
->HasRating()) {
3855 byte_inc_sat(&ge
->time_since_pickup
);
3856 if (ge
->time_since_pickup
== 255 && _settings_game
.order
.selectgoods
) {
3857 ClrBit(ge
->status
, GoodsEntry::GES_RATING
);
3859 TruncateCargo(cs
, ge
);
3860 waiting_changed
= true;
3866 uint waiting
= ge
->cargo
.AvailableCount();
3868 /* num_dests is at least 1 if there is any cargo as
3869 * INVALID_STATION is also a destination.
3871 uint num_dests
= (uint
)ge
->cargo
.Packets()->MapSize();
3873 /* Average amount of cargo per next hop, but prefer solitary stations
3874 * with only one or two next hops. They are allowed to have more
3875 * cargo waiting per next hop.
3876 * With manual cargo distribution waiting_avg = waiting / 2 as then
3877 * INVALID_STATION is the only destination.
3879 uint waiting_avg
= waiting
/ (num_dests
+ 1);
3881 if (_cheats
.station_rating
.value
) {
3882 ge
->rating
= rating
= MAX_STATION_RATING
;
3884 } else if (HasBit(cs
->callback_mask
, CBM_CARGO_STATION_RATING_CALC
)) {
3885 /* Perform custom station rating. If it succeeds the speed, days in transit and
3886 * waiting cargo ratings must not be executed. */
3888 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3889 uint last_speed
= ge
->HasVehicleEverTriedLoading() ? ge
->last_speed
: 0xFF;
3891 uint32_t var18
= ClampTo
<uint8_t>(ge
->time_since_pickup
)
3892 | (ClampTo
<uint16_t>(ge
->max_waiting_cargo
) << 8)
3893 | (ClampTo
<uint8_t>(last_speed
) << 24);
3894 /* Convert to the 'old' vehicle types */
3895 uint32_t var10
= (st
->last_vehicle_type
== VEH_INVALID
) ? 0x0 : (st
->last_vehicle_type
+ 0x10);
3896 uint16_t callback
= GetCargoCallback(CBID_CARGO_STATION_RATING_CALC
, var10
, var18
, cs
);
3897 if (callback
!= CALLBACK_FAILED
) {
3899 rating
= GB(callback
, 0, 14);
3901 /* Simulate a 15 bit signed value */
3902 if (HasBit(callback
, 14)) rating
-= 0x4000;
3907 int b
= ge
->last_speed
- 85;
3908 if (b
>= 0) rating
+= b
>> 2;
3910 uint8_t waittime
= ge
->time_since_pickup
;
3911 if (st
->last_vehicle_type
== VEH_SHIP
) waittime
>>= 2;
3912 if (waittime
<= 21) rating
+= 25;
3913 if (waittime
<= 12) rating
+= 25;
3914 if (waittime
<= 6) rating
+= 45;
3915 if (waittime
<= 3) rating
+= 35;
3918 if (ge
->max_waiting_cargo
<= 1500) rating
+= 55;
3919 if (ge
->max_waiting_cargo
<= 1000) rating
+= 35;
3920 if (ge
->max_waiting_cargo
<= 600) rating
+= 10;
3921 if (ge
->max_waiting_cargo
<= 300) rating
+= 20;
3922 if (ge
->max_waiting_cargo
<= 100) rating
+= 10;
3925 if (Company::IsValidID(st
->owner
) && HasBit(st
->town
->statues
, st
->owner
)) rating
+= 26;
3927 uint8_t age
= ge
->last_age
;
3928 if (age
< 3) rating
+= 10;
3929 if (age
< 2) rating
+= 10;
3930 if (age
< 1) rating
+= 13;
3933 int or_
= ge
->rating
; // old rating
3935 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3936 ge
->rating
= rating
= or_
+ Clamp(ClampTo
<uint8_t>(rating
) - or_
, -2, 2);
3938 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3939 * remove some random amount of goods from the station */
3940 if (rating
<= 64 && waiting_avg
>= 100) {
3941 int dec
= Random() & 0x1F;
3942 if (waiting_avg
< 200) dec
&= 7;
3943 waiting
-= (dec
+ 1) * num_dests
;
3944 waiting_changed
= true;
3947 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3948 if (rating
<= 127 && waiting
!= 0) {
3949 uint32_t r
= Random();
3950 if (rating
<= (int)GB(r
, 0, 7)) {
3951 /* Need to have int, otherwise it will just overflow etc. */
3952 waiting
= std::max((int)waiting
- (int)((GB(r
, 8, 2) - 1) * num_dests
), 0);
3953 waiting_changed
= true;
3957 /* At some point we really must cap the cargo. Previously this
3958 * was a strict 4095, but now we'll have a less strict, but
3959 * increasingly aggressive truncation of the amount of cargo. */
3960 static const uint WAITING_CARGO_THRESHOLD
= 1 << 12;
3961 static const uint WAITING_CARGO_CUT_FACTOR
= 1 << 6;
3962 static const uint MAX_WAITING_CARGO
= 1 << 15;
3964 if (waiting
> WAITING_CARGO_THRESHOLD
) {
3965 uint difference
= waiting
- WAITING_CARGO_THRESHOLD
;
3966 waiting
-= (difference
/ WAITING_CARGO_CUT_FACTOR
);
3968 waiting
= std::min(waiting
, MAX_WAITING_CARGO
);
3969 waiting_changed
= true;
3972 /* We can't truncate cargo that's already reserved for loading.
3973 * Thus StoredCount() here. */
3974 if (waiting_changed
&& waiting
< ge
->cargo
.AvailableCount()) {
3975 /* Feed back the exact own waiting cargo at this station for the
3976 * next rating calculation. */
3977 ge
->max_waiting_cargo
= 0;
3979 TruncateCargo(cs
, ge
, ge
->cargo
.AvailableCount() - waiting
);
3981 /* If the average number per next hop is low, be more forgiving. */
3982 ge
->max_waiting_cargo
= waiting_avg
;
3988 StationID index
= st
->index
;
3989 if (waiting_changed
) {
3990 SetWindowDirty(WC_STATION_VIEW
, index
); // update whole window
3992 SetWindowWidgetDirty(WC_STATION_VIEW
, index
, WID_SV_ACCEPT_RATING_LIST
); // update only ratings list
3997 * Reroute cargo of type c at station st or in any vehicles unloading there.
3998 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3999 * @param st Station to be rerouted at.
4000 * @param c Type of cargo.
4001 * @param avoid Original next hop of cargo, avoid this.
4002 * @param avoid2 Another station to be avoided when rerouting.
4004 void RerouteCargo(Station
*st
, CargoID c
, StationID avoid
, StationID avoid2
)
4006 GoodsEntry
&ge
= st
->goods
[c
];
4008 /* Reroute cargo in station. */
4009 ge
.cargo
.Reroute(UINT_MAX
, &ge
.cargo
, avoid
, avoid2
, &ge
);
4011 /* Reroute cargo staged to be transferred. */
4012 for (Vehicle
*v
: st
->loading_vehicles
) {
4013 for (Vehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
4014 if (u
->cargo_type
!= c
) continue;
4015 u
->cargo
.Reroute(UINT_MAX
, &u
->cargo
, avoid
, avoid2
, &ge
);
4021 * Check all next hops of cargo packets in this station for existence of a
4022 * a valid link they may use to travel on. Reroute any cargo not having a valid
4023 * link and remove timed out links found like this from the linkgraph. We're
4024 * not all links here as that is expensive and useless. A link no one is using
4025 * doesn't hurt either.
4026 * @param from Station to check.
4028 void DeleteStaleLinks(Station
*from
)
4030 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
4031 const bool auto_distributed
= (_settings_game
.linkgraph
.GetDistributionType(c
) != DT_MANUAL
);
4032 GoodsEntry
&ge
= from
->goods
[c
];
4033 LinkGraph
*lg
= LinkGraph::GetIfValid(ge
.link_graph
);
4034 if (lg
== nullptr) continue;
4035 std::vector
<NodeID
> to_remove
{};
4036 for (Edge
&edge
: (*lg
)[ge
.node
].edges
) {
4037 Station
*to
= Station::Get((*lg
)[edge
.dest_node
].station
);
4038 assert(to
->goods
[c
].node
== edge
.dest_node
);
4039 assert(TimerGameEconomy::date
>= edge
.LastUpdate());
4040 auto timeout
= TimerGameEconomy::Date(LinkGraph::MIN_TIMEOUT_DISTANCE
+ (DistanceManhattan(from
->xy
, to
->xy
) >> 3));
4041 if (TimerGameEconomy::date
- edge
.LastUpdate() > timeout
) {
4042 bool updated
= false;
4044 if (auto_distributed
) {
4045 /* Have all vehicles refresh their next hops before deciding to
4046 * remove the node. */
4047 std::vector
<Vehicle
*> vehicles
;
4048 for (OrderList
*l
: OrderList::Iterate()) {
4049 bool found_from
= false;
4050 bool found_to
= false;
4051 for (Order
*order
= l
->GetFirstOrder(); order
!= nullptr; order
= order
->next
) {
4052 if (!order
->IsType(OT_GOTO_STATION
) && !order
->IsType(OT_IMPLICIT
)) continue;
4053 if (order
->GetDestination() == from
->index
) {
4055 if (found_to
) break;
4056 } else if (order
->GetDestination() == to
->index
) {
4058 if (found_from
) break;
4061 if (!found_to
|| !found_from
) continue;
4062 vehicles
.push_back(l
->GetFirstSharedVehicle());
4065 auto iter
= vehicles
.begin();
4066 while (iter
!= vehicles
.end()) {
4068 /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
4069 if (!v
->IsStoppedInDepot() || TimerGameEconomy::date
- v
->date_of_last_service
<= LinkGraph::STALE_LINK_DEPOT_TIMEOUT
) {
4070 LinkRefresher::Run(v
, false); // Don't allow merging. Otherwise lg might get deleted.
4072 if (edge
.LastUpdate() == TimerGameEconomy::date
) {
4077 Vehicle
*next_shared
= v
->NextShared();
4079 *iter
= next_shared
;
4082 iter
= vehicles
.erase(iter
);
4085 if (iter
== vehicles
.end()) iter
= vehicles
.begin();
4090 /* If it's still considered dead remove it. */
4091 to_remove
.emplace_back(to
->goods
[c
].node
);
4092 ge
.flows
.DeleteFlows(to
->index
);
4093 RerouteCargo(from
, c
, to
->index
, from
->index
);
4095 } else if (edge
.last_unrestricted_update
!= EconomyTime::INVALID_DATE
&& TimerGameEconomy::date
- edge
.last_unrestricted_update
> timeout
) {
4097 ge
.flows
.RestrictFlows(to
->index
);
4098 RerouteCargo(from
, c
, to
->index
, from
->index
);
4099 } else if (edge
.last_restricted_update
!= EconomyTime::INVALID_DATE
&& TimerGameEconomy::date
- edge
.last_restricted_update
> timeout
) {
4103 /* Remove dead edges. */
4104 for (NodeID r
: to_remove
) (*lg
)[ge
.node
].RemoveEdge(r
);
4106 assert(TimerGameEconomy::date
>= lg
->LastCompression());
4107 if (TimerGameEconomy::date
- lg
->LastCompression() > LinkGraph::COMPRESSION_INTERVAL
) {
4114 * Increase capacity for a link stat given by station cargo and next hop.
4115 * @param st Station to get the link stats from.
4116 * @param cargo Cargo to increase stat for.
4117 * @param next_station_id Station the consist will be travelling to next.
4118 * @param capacity Capacity to add to link stat.
4119 * @param usage Usage to add to link stat.
4120 * @param mode Update mode to be applied.
4122 void IncreaseStats(Station
*st
, CargoID cargo
, StationID next_station_id
, uint capacity
, uint usage
, uint32_t time
, EdgeUpdateMode mode
)
4124 GoodsEntry
&ge1
= st
->goods
[cargo
];
4125 Station
*st2
= Station::Get(next_station_id
);
4126 GoodsEntry
&ge2
= st2
->goods
[cargo
];
4127 LinkGraph
*lg
= nullptr;
4128 if (ge1
.link_graph
== INVALID_LINK_GRAPH
) {
4129 if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
4130 if (LinkGraph::CanAllocateItem()) {
4131 lg
= new LinkGraph(cargo
);
4132 LinkGraphSchedule::instance
.Queue(lg
);
4133 ge2
.link_graph
= lg
->index
;
4134 ge2
.node
= lg
->AddNode(st2
);
4136 Debug(misc
, 0, "Can't allocate link graph");
4139 lg
= LinkGraph::Get(ge2
.link_graph
);
4142 ge1
.link_graph
= lg
->index
;
4143 ge1
.node
= lg
->AddNode(st
);
4145 } else if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
4146 lg
= LinkGraph::Get(ge1
.link_graph
);
4147 ge2
.link_graph
= lg
->index
;
4148 ge2
.node
= lg
->AddNode(st2
);
4150 lg
= LinkGraph::Get(ge1
.link_graph
);
4151 if (ge1
.link_graph
!= ge2
.link_graph
) {
4152 LinkGraph
*lg2
= LinkGraph::Get(ge2
.link_graph
);
4153 if (lg
->Size() < lg2
->Size()) {
4154 LinkGraphSchedule::instance
.Unqueue(lg
);
4155 lg2
->Merge(lg
); // Updates GoodsEntries of lg
4158 LinkGraphSchedule::instance
.Unqueue(lg2
);
4159 lg
->Merge(lg2
); // Updates GoodsEntries of lg2
4163 if (lg
!= nullptr) {
4164 (*lg
)[ge1
.node
].UpdateEdge(ge2
.node
, capacity
, usage
, time
, mode
);
4169 * Increase capacity for all link stats associated with vehicles in the given consist.
4170 * @param st Station to get the link stats from.
4171 * @param front First vehicle in the consist.
4172 * @param next_station_id Station the consist will be travelling to next.
4174 void IncreaseStats(Station
*st
, const Vehicle
*front
, StationID next_station_id
, uint32_t time
)
4176 for (const Vehicle
*v
= front
; v
!= nullptr; v
= v
->Next()) {
4177 if (v
->refit_cap
> 0) {
4178 /* The cargo count can indeed be higher than the refit_cap if
4179 * wagons have been auto-replaced and subsequently auto-
4180 * refitted to a higher capacity. The cargo gets redistributed
4181 * among the wagons in that case.
4182 * As usage is not such an important figure anyway we just
4183 * ignore the additional cargo then.*/
4184 IncreaseStats(st
, v
->cargo_type
, next_station_id
, v
->refit_cap
,
4185 std::min
<uint
>(v
->refit_cap
, v
->cargo
.StoredCount()), time
, EUM_INCREASE
);
4190 /* called for every station each tick */
4191 static void StationHandleSmallTick(BaseStation
*st
)
4193 if ((st
->facilities
& FACIL_WAYPOINT
) != 0 || !st
->IsInUse()) return;
4195 uint8_t b
= st
->delete_ctr
+ 1;
4196 if (b
>= Ticks::STATION_RATING_TICKS
) b
= 0;
4199 if (b
== 0) UpdateStationRating(Station::From(st
));
4202 void OnTick_Station()
4204 if (_game_mode
== GM_EDITOR
) return;
4206 for (BaseStation
*st
: BaseStation::Iterate()) {
4207 StationHandleSmallTick(st
);
4209 /* Clean up the link graph about once a week. */
4210 if (Station::IsExpected(st
) && (TimerGameTick::counter
+ st
->index
) % Ticks::STATION_LINKGRAPH_TICKS
== 0) {
4211 DeleteStaleLinks(Station::From(st
));
4214 /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */
4215 if ((TimerGameTick::counter
+ st
->index
) % Ticks::STATION_ACCEPTANCE_TICKS
== 0) {
4216 /* Stop processing this station if it was deleted */
4217 if (!StationHandleBigTick(st
)) continue;
4220 /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */
4221 if ((TimerGameTick::counter
+ st
->index
) % Ticks::STATION_ACCEPTANCE_TICKS
== 0) {
4222 TriggerStationAnimation(st
, st
->xy
, SAT_250_TICKS
);
4223 TriggerRoadStopAnimation(st
, st
->xy
, SAT_250_TICKS
);
4224 if (Station::IsExpected(st
)) AirportAnimationTrigger(Station::From(st
), AAT_STATION_250_TICKS
);
4229 /** Economy monthly loop for stations. */
4230 static IntervalTimer
<TimerGameEconomy
> _economy_stations_monthly({TimerGameEconomy::MONTH
, TimerGameEconomy::Priority::STATION
}, [](auto)
4232 for (Station
*st
: Station::Iterate()) {
4233 for (GoodsEntry
&ge
: st
->goods
) {
4234 SB(ge
.status
, GoodsEntry::GES_LAST_MONTH
, 1, GB(ge
.status
, GoodsEntry::GES_CURRENT_MONTH
, 1));
4235 ClrBit(ge
.status
, GoodsEntry::GES_CURRENT_MONTH
);
4240 void ModifyStationRatingAround(TileIndex tile
, Owner owner
, int amount
, uint radius
)
4242 ForAllStationsRadius(tile
, radius
, [&](Station
*st
) {
4243 if (st
->owner
== owner
&& DistanceManhattan(tile
, st
->xy
) <= radius
) {
4244 for (GoodsEntry
&ge
: st
->goods
) {
4245 if (ge
.status
!= 0) {
4246 ge
.rating
= ClampTo
<uint8_t>(ge
.rating
+ amount
);
4253 static uint
UpdateStationWaiting(Station
*st
, CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
)
4255 /* We can't allocate a CargoPacket? Then don't do anything
4256 * at all; i.e. just discard the incoming cargo. */
4257 if (!CargoPacket::CanAllocateItem()) return 0;
4259 GoodsEntry
&ge
= st
->goods
[type
];
4260 amount
+= ge
.amount_fract
;
4261 ge
.amount_fract
= GB(amount
, 0, 8);
4264 /* No new "real" cargo item yet. */
4265 if (amount
== 0) return 0;
4267 StationID next
= ge
.GetVia(st
->index
);
4268 ge
.cargo
.Append(new CargoPacket(st
->index
, amount
, source_type
, source_id
), next
);
4269 LinkGraph
*lg
= nullptr;
4270 if (ge
.link_graph
== INVALID_LINK_GRAPH
) {
4271 if (LinkGraph::CanAllocateItem()) {
4272 lg
= new LinkGraph(type
);
4273 LinkGraphSchedule::instance
.Queue(lg
);
4274 ge
.link_graph
= lg
->index
;
4275 ge
.node
= lg
->AddNode(st
);
4277 Debug(misc
, 0, "Can't allocate link graph");
4280 lg
= LinkGraph::Get(ge
.link_graph
);
4282 if (lg
!= nullptr) (*lg
)[ge
.node
].UpdateSupply(amount
);
4284 if (!ge
.HasRating()) {
4285 InvalidateWindowData(WC_STATION_LIST
, st
->owner
);
4286 SetBit(ge
.status
, GoodsEntry::GES_RATING
);
4289 TriggerStationRandomisation(st
, st
->xy
, SRT_NEW_CARGO
, type
);
4290 TriggerStationAnimation(st
, st
->xy
, SAT_NEW_CARGO
, type
);
4291 AirportAnimationTrigger(st
, AAT_STATION_NEW_CARGO
, type
);
4292 TriggerRoadStopRandomisation(st
, st
->xy
, RSRT_NEW_CARGO
, type
);
4293 TriggerRoadStopAnimation(st
, st
->xy
, SAT_NEW_CARGO
, type
);
4296 SetWindowDirty(WC_STATION_VIEW
, st
->index
);
4297 st
->MarkTilesDirty(true);
4301 static bool IsUniqueStationName(const std::string
&name
)
4303 for (const Station
*st
: Station::Iterate()) {
4304 if (!st
->name
.empty() && st
->name
== name
) return false;
4312 * @param flags operation to perform
4313 * @param station_id station ID that is to be renamed
4314 * @param text the new name or an empty string when resetting to the default
4315 * @return the cost of this operation or an error
4317 CommandCost
CmdRenameStation(DoCommandFlag flags
, StationID station_id
, const std::string
&text
)
4319 Station
*st
= Station::GetIfValid(station_id
);
4320 if (st
== nullptr) return CMD_ERROR
;
4322 CommandCost ret
= CheckOwnership(st
->owner
);
4323 if (ret
.Failed()) return ret
;
4325 bool reset
= text
.empty();
4328 if (Utf8StringLength(text
) >= MAX_LENGTH_STATION_NAME_CHARS
) return CMD_ERROR
;
4329 if (!IsUniqueStationName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
4332 if (flags
& DC_EXEC
) {
4333 st
->cached_name
.clear();
4340 st
->UpdateVirtCoord();
4341 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 1);
4344 return CommandCost();
4347 static void AddNearbyStationsByCatchment(TileIndex tile
, StationList
*stations
, StationList
&nearby
)
4349 for (Station
*st
: nearby
) {
4350 if (st
->TileIsInCatchment(tile
)) stations
->insert(st
);
4355 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
4356 * @return pointer to a StationList containing all stations found
4358 const StationList
*StationFinder::GetStations()
4360 if (this->tile
!= INVALID_TILE
) {
4361 if (IsTileType(this->tile
, MP_HOUSE
)) {
4362 /* Town nearby stations need to be filtered per tile. */
4363 assert(this->w
== 1 && this->h
== 1);
4364 AddNearbyStationsByCatchment(this->tile
, &this->stations
, Town::GetByTile(this->tile
)->stations_near
);
4366 ForAllStationsAroundTiles(*this, [this](Station
*st
, TileIndex
) {
4367 this->stations
.insert(st
);
4371 this->tile
= INVALID_TILE
;
4373 return &this->stations
;
4377 static bool CanMoveGoodsToStation(const Station
*st
, CargoID type
)
4379 /* Is the station reserved exclusively for somebody else? */
4380 if (st
->owner
!= OWNER_NONE
&& st
->town
->exclusive_counter
> 0 && st
->town
->exclusivity
!= st
->owner
) return false;
4382 /* Lowest possible rating, better not to give cargo anymore. */
4383 if (st
->goods
[type
].rating
== 0) return false;
4385 /* Selectively servicing stations, and not this one. */
4386 if (_settings_game
.order
.selectgoods
&& !st
->goods
[type
].HasVehicleEverTriedLoading()) return false;
4388 if (IsCargoInClass(type
, CC_PASSENGERS
)) {
4389 /* Passengers are never served by just a truck stop. */
4390 if (st
->facilities
== FACIL_TRUCK_STOP
) return false;
4392 /* Non-passengers are never served by just a bus stop. */
4393 if (st
->facilities
== FACIL_BUS_STOP
) return false;
4398 uint
MoveGoodsToStation(CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
, const StationList
*all_stations
, Owner exclusivity
)
4400 /* Return if nothing to do. Also the rounding below fails for 0. */
4401 if (all_stations
->empty()) return 0;
4402 if (amount
== 0) return 0;
4404 Station
*first_station
= nullptr;
4405 typedef std::pair
<Station
*, uint
> StationInfo
;
4406 std::vector
<StationInfo
> used_stations
;
4408 for (Station
*st
: *all_stations
) {
4409 if (exclusivity
!= INVALID_OWNER
&& exclusivity
!= st
->owner
) continue;
4410 if (!CanMoveGoodsToStation(st
, type
)) continue;
4412 /* Avoid allocating a vector if there is only one station to significantly
4413 * improve performance in this common case. */
4414 if (first_station
== nullptr) {
4418 if (used_stations
.empty()) {
4419 used_stations
.reserve(2);
4420 used_stations
.emplace_back(first_station
, 0);
4422 used_stations
.emplace_back(st
, 0);
4425 /* no stations around at all? */
4426 if (first_station
== nullptr) return 0;
4428 if (used_stations
.empty()) {
4429 /* only one station around */
4430 amount
*= first_station
->goods
[type
].rating
+ 1;
4431 return UpdateStationWaiting(first_station
, type
, amount
, source_type
, source_id
);
4434 uint company_best
[OWNER_NONE
+ 1] = {}; // best rating for each company, including OWNER_NONE
4435 uint company_sum
[OWNER_NONE
+ 1] = {}; // sum of ratings for each company
4436 uint best_rating
= 0;
4437 uint best_sum
= 0; // sum of best ratings for each company
4439 for (auto &p
: used_stations
) {
4440 auto owner
= p
.first
->owner
;
4441 auto rating
= p
.first
->goods
[type
].rating
;
4442 if (rating
> company_best
[owner
]) {
4443 best_sum
+= rating
- company_best
[owner
]; // it's usually faster than iterating companies later
4444 company_best
[owner
] = rating
;
4445 if (rating
> best_rating
) best_rating
= rating
;
4447 company_sum
[owner
] += rating
;
4450 /* From now we'll calculate with fractional cargo amounts.
4451 * First determine how much cargo we really have. */
4452 amount
*= best_rating
+ 1;
4455 for (auto &p
: used_stations
) {
4456 uint owner
= p
.first
->owner
;
4457 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4458 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4459 p
.second
= amount
* company_best
[owner
] * p
.first
->goods
[type
].rating
/ best_sum
/ company_sum
[owner
];
4463 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4464 if (amount
> moving
) {
4465 std::stable_sort(used_stations
.begin(), used_stations
.end(), [type
](const StationInfo
&a
, const StationInfo
&b
) {
4466 return b
.first
->goods
[type
].rating
< a
.first
->goods
[type
].rating
;
4469 assert(amount
- moving
<= used_stations
.size());
4470 for (uint i
= 0; i
< amount
- moving
; i
++) {
4471 used_stations
[i
].second
++;
4476 for (auto &p
: used_stations
) {
4477 moved
+= UpdateStationWaiting(p
.first
, type
, p
.second
, source_type
, source_id
);
4483 void UpdateStationDockingTiles(Station
*st
)
4485 st
->docking_station
.Clear();
4487 /* For neutral stations, start with the industry area instead of dock area */
4488 const TileArea
*area
= st
->industry
!= nullptr ? &st
->industry
->location
: &st
->ship_station
;
4490 if (area
->tile
== INVALID_TILE
) return;
4492 int x
= TileX(area
->tile
);
4493 int y
= TileY(area
->tile
);
4495 /* Expand the area by a tile on each side while
4496 * making sure that we remain inside the map. */
4497 int x2
= std::min
<int>(x
+ area
->w
+ 1, Map::SizeX());
4498 int x1
= std::max
<int>(x
- 1, 0);
4500 int y2
= std::min
<int>(y
+ area
->h
+ 1, Map::SizeY());
4501 int y1
= std::max
<int>(y
- 1, 0);
4503 TileArea
ta(TileXY(x1
, y1
), TileXY(x2
- 1, y2
- 1));
4504 for (TileIndex tile
: ta
) {
4505 if (IsValidTile(tile
) && IsPossibleDockingTile(tile
)) CheckForDockingTile(tile
);
4509 void BuildOilRig(TileIndex tile
)
4511 if (!Station::CanAllocateItem()) {
4512 Debug(misc
, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile
);
4516 Station
*st
= new Station(tile
);
4517 _station_kdtree
.Insert(st
->index
);
4518 st
->town
= ClosestTownFromTile(tile
, UINT_MAX
);
4520 st
->string_id
= GenerateStationName(st
, tile
, STATIONNAMING_OILRIG
);
4522 assert(IsTileType(tile
, MP_INDUSTRY
));
4523 /* Mark industry as associated both ways */
4524 st
->industry
= Industry::GetByTile(tile
);
4525 st
->industry
->neutral_station
= st
;
4526 DeleteAnimatedTile(tile
);
4527 MakeOilrig(tile
, st
->index
, GetWaterClass(tile
));
4529 st
->owner
= OWNER_NONE
;
4530 st
->airport
.type
= AT_OILRIG
;
4531 st
->airport
.Add(tile
);
4532 st
->ship_station
.Add(tile
);
4533 st
->facilities
= FACIL_AIRPORT
| FACIL_DOCK
;
4534 st
->build_date
= TimerGameCalendar::date
;
4535 UpdateStationDockingTiles(st
);
4537 st
->rect
.BeforeAddTile(tile
, StationRect::ADD_FORCE
);
4539 st
->UpdateVirtCoord();
4541 /* An industry tile has now been replaced with a station tile, this may change the overlap between station catchments and industry tiles.
4542 * Recalculate the station catchment for all stations currently in the industry's nearby list.
4543 * Clear the industry's station nearby list first because Station::RecomputeCatchment cannot remove nearby industries in this case. */
4544 if (_settings_game
.station
.serve_neutral_industries
) {
4545 StationList nearby
= std::move(st
->industry
->stations_near
);
4546 st
->industry
->stations_near
.clear();
4547 for (Station
*near
: nearby
) {
4548 near
->RecomputeCatchment(true);
4549 UpdateStationAcceptance(near
, true);
4553 st
->RecomputeCatchment();
4554 UpdateStationAcceptance(st
, false);
4557 void DeleteOilRig(TileIndex tile
)
4559 Station
*st
= Station::GetByTile(tile
);
4561 MakeWaterKeepingClass(tile
, OWNER_NONE
);
4563 /* The oil rig station is not supposed to be shared with anything else */
4564 assert(st
->facilities
== (FACIL_AIRPORT
| FACIL_DOCK
) && st
->airport
.type
== AT_OILRIG
);
4565 if (st
->industry
!= nullptr && st
->industry
->neutral_station
== st
) {
4566 /* Don't leave dangling neutral station pointer */
4567 st
->industry
->neutral_station
= nullptr;
4572 static void ChangeTileOwner_Station(TileIndex tile
, Owner old_owner
, Owner new_owner
)
4574 if (IsAnyRoadStopTile(tile
)) {
4575 for (RoadTramType rtt
: _roadtramtypes
) {
4576 /* Update all roadtypes, no matter if they are present */
4577 if (GetRoadOwner(tile
, rtt
) == old_owner
) {
4578 RoadType rt
= GetRoadType(tile
, rtt
);
4579 if (rt
!= INVALID_ROADTYPE
) {
4580 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4581 Company::Get(old_owner
)->infrastructure
.road
[rt
] -= 2;
4582 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.road
[rt
] += 2;
4584 SetRoadOwner(tile
, rtt
, new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
);
4589 if (!IsTileOwner(tile
, old_owner
)) return;
4591 if (new_owner
!= INVALID_OWNER
) {
4592 /* Update company infrastructure counts. Only do it here
4593 * if the new owner is valid as otherwise the clear
4594 * command will do it for us. No need to dirty windows
4595 * here, we'll redraw the whole screen anyway.*/
4596 Company
*old_company
= Company::Get(old_owner
);
4597 Company
*new_company
= Company::Get(new_owner
);
4599 /* Update counts for underlying infrastructure. */
4600 switch (GetStationType(tile
)) {
4602 case STATION_WAYPOINT
:
4603 if (!IsStationTileBlocked(tile
)) {
4604 old_company
->infrastructure
.rail
[GetRailType(tile
)]--;
4605 new_company
->infrastructure
.rail
[GetRailType(tile
)]++;
4611 case STATION_ROADWAYPOINT
:
4612 /* Road stops were already handled above. */
4617 if (GetWaterClass(tile
) == WATER_CLASS_CANAL
) {
4618 old_company
->infrastructure
.water
--;
4619 new_company
->infrastructure
.water
++;
4627 /* Update station tile count. */
4628 if (!IsBuoy(tile
) && !IsAirport(tile
)) {
4629 old_company
->infrastructure
.station
--;
4630 new_company
->infrastructure
.station
++;
4633 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4634 SetTileOwner(tile
, new_owner
);
4635 InvalidateWindowClassesData(WC_STATION_LIST
, 0);
4637 if (IsDriveThroughStopTile(tile
)) {
4638 /* Remove the drive-through road stop */
4639 if (IsRoadWaypoint(tile
)) {
4640 Command
<CMD_REMOVE_FROM_ROAD_WAYPOINT
>::Do(DC_EXEC
| DC_BANKRUPT
, tile
, tile
);
4642 Command
<CMD_REMOVE_ROAD_STOP
>::Do(DC_EXEC
| DC_BANKRUPT
, tile
, 1, 1, (GetStationType(tile
) == STATION_TRUCK
) ? ROADSTOP_TRUCK
: ROADSTOP_BUS
, false);
4644 assert(IsTileType(tile
, MP_ROAD
));
4645 /* Change owner of tile and all roadtypes */
4646 ChangeTileOwner(tile
, old_owner
, new_owner
);
4648 Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_EXEC
| DC_BANKRUPT
, tile
);
4649 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4650 * Update owner of buoy if it was not removed (was in orders).
4651 * Do not update when owned by OWNER_WATER (sea and rivers). */
4652 if ((IsTileType(tile
, MP_WATER
) || IsBuoyTile(tile
)) && IsTileOwner(tile
, old_owner
)) SetTileOwner(tile
, OWNER_NONE
);
4658 * Check if a drive-through road stop tile can be cleared.
4659 * Road stops built on town-owned roads check the conditions
4660 * that would allow clearing of the original road.
4661 * @param tile The road stop tile to check.
4662 * @param flags Command flags.
4663 * @return A succeeded command if the road can be removed, a failed command with the relevant error message otherwise.
4665 static CommandCost
CanRemoveRoadWithStop(TileIndex tile
, DoCommandFlag flags
)
4667 /* Water flooding can always clear road stops. */
4668 if (_current_company
== OWNER_WATER
) return CommandCost();
4672 if (GetRoadTypeTram(tile
) != INVALID_ROADTYPE
) {
4673 Owner tram_owner
= GetRoadOwner(tile
, RTT_TRAM
);
4674 if (tram_owner
!= OWNER_NONE
) {
4675 ret
= CheckOwnership(tram_owner
);
4676 if (ret
.Failed()) return ret
;
4680 if (GetRoadTypeRoad(tile
) != INVALID_ROADTYPE
) {
4681 Owner road_owner
= GetRoadOwner(tile
, RTT_ROAD
);
4682 if (road_owner
== OWNER_TOWN
) {
4683 ret
= CheckAllowRemoveRoad(tile
, GetAnyRoadBits(tile
, RTT_ROAD
), OWNER_TOWN
, RTT_ROAD
, flags
);
4684 if (ret
.Failed()) return ret
;
4685 } else if (road_owner
!= OWNER_NONE
) {
4686 ret
= CheckOwnership(road_owner
);
4687 if (ret
.Failed()) return ret
;
4691 return CommandCost();
4695 * Clear a single tile of a station.
4696 * @param tile The tile to clear.
4697 * @param flags The DoCommand flags related to the "command".
4698 * @return The cost, or error of clearing.
4700 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
)
4702 if (flags
& DC_AUTO
) {
4703 switch (GetStationType(tile
)) {
4705 case STATION_RAIL
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD
);
4706 case STATION_WAYPOINT
: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
4707 case STATION_AIRPORT
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
4708 case STATION_TRUCK
: return_cmd_error(HasTileRoadType(tile
, RTT_TRAM
) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST
: STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST
);
4709 case STATION_BUS
: return_cmd_error(HasTileRoadType(tile
, RTT_TRAM
) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST
: STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST
);
4710 case STATION_ROADWAYPOINT
: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
4711 case STATION_BUOY
: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY
);
4712 case STATION_DOCK
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST
);
4713 case STATION_OILRIG
:
4714 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG
);
4715 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY
);
4719 switch (GetStationType(tile
)) {
4720 case STATION_RAIL
: return RemoveRailStation(tile
, flags
);
4721 case STATION_WAYPOINT
: return RemoveRailWaypoint(tile
, flags
);
4722 case STATION_AIRPORT
: return RemoveAirport(tile
, flags
);
4723 case STATION_TRUCK
: [[fallthrough
]];
4725 if (IsDriveThroughStopTile(tile
)) {
4726 CommandCost remove_road
= CanRemoveRoadWithStop(tile
, flags
);
4727 if (remove_road
.Failed()) return remove_road
;
4729 return RemoveRoadStop(tile
, flags
);
4730 case STATION_ROADWAYPOINT
: {
4731 CommandCost remove_road
= CanRemoveRoadWithStop(tile
, flags
);
4732 if (remove_road
.Failed()) return remove_road
;
4733 return RemoveRoadWaypointStop(tile
, flags
);
4735 case STATION_BUOY
: return RemoveBuoy(tile
, flags
);
4736 case STATION_DOCK
: return RemoveDock(tile
, flags
);
4743 static CommandCost
TerraformTile_Station(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
4745 if (_settings_game
.construction
.build_on_slopes
&& AutoslopeEnabled()) {
4746 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4747 * TTDP does not call it.
4749 if (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
)) {
4750 switch (GetStationType(tile
)) {
4751 case STATION_WAYPOINT
:
4752 case STATION_RAIL
: {
4753 if (!AutoslopeCheckForAxis(tile
, z_new
, tileh_new
, GetRailStationAxis(tile
))) break;
4754 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4757 case STATION_AIRPORT
:
4758 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4762 case STATION_ROADWAYPOINT
: {
4763 if (IsDriveThroughStopTile(tile
)) {
4764 if (!AutoslopeCheckForAxis(tile
, z_new
, tileh_new
, GetDriveThroughStopAxis(tile
))) break;
4766 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, GetBayRoadStopDir(tile
))) break;
4768 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4775 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
4779 * Get flow for a station.
4780 * @param st Station to get flow for.
4781 * @return Flow for st.
4783 uint
FlowStat::GetShare(StationID st
) const
4786 for (const auto &it
: this->shares
) {
4787 if (it
.second
== st
) {
4788 return it
.first
- prev
;
4797 * Get a station a package can be routed to, but exclude the given ones.
4798 * @param excluded StationID not to be selected.
4799 * @param excluded2 Another StationID not to be selected.
4800 * @return A station ID from the shares map.
4802 StationID
FlowStat::GetVia(StationID excluded
, StationID excluded2
) const
4804 if (this->unrestricted
== 0) return INVALID_STATION
;
4805 assert(!this->shares
.empty());
4806 SharesMap::const_iterator it
= this->shares
.upper_bound(RandomRange(this->unrestricted
));
4807 assert(it
!= this->shares
.end() && it
->first
<= this->unrestricted
);
4808 if (it
->second
!= excluded
&& it
->second
!= excluded2
) return it
->second
;
4810 /* We've hit one of the excluded stations.
4811 * Draw another share, from outside its range. */
4813 uint end
= it
->first
;
4814 uint begin
= (it
== this->shares
.begin() ? 0 : (--it
)->first
);
4815 uint interval
= end
- begin
;
4816 if (interval
>= this->unrestricted
) return INVALID_STATION
; // Only one station in the map.
4817 uint new_max
= this->unrestricted
- interval
;
4818 uint rand
= RandomRange(new_max
);
4819 SharesMap::const_iterator it2
= (rand
< begin
) ? this->shares
.upper_bound(rand
) :
4820 this->shares
.upper_bound(rand
+ interval
);
4821 assert(it2
!= this->shares
.end() && it2
->first
<= this->unrestricted
);
4822 if (it2
->second
!= excluded
&& it2
->second
!= excluded2
) return it2
->second
;
4824 /* We've hit the second excluded station.
4825 * Same as before, only a bit more complicated. */
4827 uint end2
= it2
->first
;
4828 uint begin2
= (it2
== this->shares
.begin() ? 0 : (--it2
)->first
);
4829 uint interval2
= end2
- begin2
;
4830 if (interval2
>= new_max
) return INVALID_STATION
; // Only the two excluded stations in the map.
4831 new_max
-= interval2
;
4832 if (begin
> begin2
) {
4833 Swap(begin
, begin2
);
4835 Swap(interval
, interval2
);
4837 rand
= RandomRange(new_max
);
4838 SharesMap::const_iterator it3
= this->shares
.upper_bound(this->unrestricted
);
4840 it3
= this->shares
.upper_bound(rand
);
4841 } else if (rand
< begin2
- interval
) {
4842 it3
= this->shares
.upper_bound(rand
+ interval
);
4844 it3
= this->shares
.upper_bound(rand
+ interval
+ interval2
);
4846 assert(it3
!= this->shares
.end() && it3
->first
<= this->unrestricted
);
4851 * Reduce all flows to minimum capacity so that they don't get in the way of
4852 * link usage statistics too much. Keep them around, though, to continue
4853 * routing any remaining cargo.
4855 void FlowStat::Invalidate()
4857 assert(!this->shares
.empty());
4858 SharesMap new_shares
;
4860 for (const auto &it
: this->shares
) {
4861 new_shares
[++i
] = it
.second
;
4862 if (it
.first
== this->unrestricted
) this->unrestricted
= i
;
4864 this->shares
.swap(new_shares
);
4865 assert(!this->shares
.empty() && this->unrestricted
<= (--this->shares
.end())->first
);
4869 * Change share for specified station. By specifying INT_MIN as parameter you
4870 * can erase a share. Newly added flows will be unrestricted.
4871 * @param st Next Hop to be removed.
4872 * @param flow Share to be added or removed.
4874 void FlowStat::ChangeShare(StationID st
, int flow
)
4876 /* We assert only before changing as afterwards the shares can actually
4877 * be empty. In that case the whole flow stat must be deleted then. */
4878 assert(!this->shares
.empty());
4880 uint removed_shares
= 0;
4881 uint added_shares
= 0;
4882 uint last_share
= 0;
4883 SharesMap new_shares
;
4884 for (const auto &it
: this->shares
) {
4885 if (it
.second
== st
) {
4887 uint share
= it
.first
- last_share
;
4888 if (flow
== INT_MIN
|| (uint
)(-flow
) >= share
) {
4889 removed_shares
+= share
;
4890 if (it
.first
<= this->unrestricted
) this->unrestricted
-= share
;
4891 if (flow
!= INT_MIN
) flow
+= share
;
4892 last_share
= it
.first
;
4893 continue; // remove the whole share
4895 removed_shares
+= (uint
)(-flow
);
4897 added_shares
+= (uint
)(flow
);
4899 if (it
.first
<= this->unrestricted
) this->unrestricted
+= flow
;
4901 /* If we don't continue above the whole flow has been added or
4905 new_shares
[it
.first
+ added_shares
- removed_shares
] = it
.second
;
4906 last_share
= it
.first
;
4909 new_shares
[last_share
+ (uint
)flow
] = st
;
4910 if (this->unrestricted
< last_share
) {
4911 this->ReleaseShare(st
);
4913 this->unrestricted
+= flow
;
4916 this->shares
.swap(new_shares
);
4920 * Restrict a flow by moving it to the end of the map and decreasing the amount
4921 * of unrestricted flow.
4922 * @param st Station of flow to be restricted.
4924 void FlowStat::RestrictShare(StationID st
)
4926 assert(!this->shares
.empty());
4928 uint last_share
= 0;
4929 SharesMap new_shares
;
4930 for (auto &it
: this->shares
) {
4932 if (it
.first
> this->unrestricted
) return; // Not present or already restricted.
4933 if (it
.second
== st
) {
4934 flow
= it
.first
- last_share
;
4935 this->unrestricted
-= flow
;
4937 new_shares
[it
.first
] = it
.second
;
4940 new_shares
[it
.first
- flow
] = it
.second
;
4942 last_share
= it
.first
;
4944 if (flow
== 0) return;
4945 new_shares
[last_share
+ flow
] = st
;
4946 this->shares
.swap(new_shares
);
4947 assert(!this->shares
.empty());
4951 * Release ("unrestrict") a flow by moving it to the begin of the map and
4952 * increasing the amount of unrestricted flow.
4953 * @param st Station of flow to be released.
4955 void FlowStat::ReleaseShare(StationID st
)
4957 assert(!this->shares
.empty());
4959 uint next_share
= 0;
4961 for (SharesMap::reverse_iterator
it(this->shares
.rbegin()); it
!= this->shares
.rend(); ++it
) {
4962 if (it
->first
< this->unrestricted
) return; // Note: not <= as the share may hit the limit.
4964 flow
= next_share
- it
->first
;
4965 this->unrestricted
+= flow
;
4968 if (it
->first
== this->unrestricted
) return; // !found -> Limit not hit.
4969 if (it
->second
== st
) found
= true;
4971 next_share
= it
->first
;
4973 if (flow
== 0) return;
4974 SharesMap new_shares
;
4975 new_shares
[flow
] = st
;
4976 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4977 if (it
->second
!= st
) {
4978 new_shares
[flow
+ it
->first
] = it
->second
;
4983 this->shares
.swap(new_shares
);
4984 assert(!this->shares
.empty());
4988 * Scale all shares from link graph's runtime to monthly values.
4989 * @param runtime Time the link graph has been running without compression.
4990 * @pre runtime must be greater than 0 as we don't want infinite flow values.
4992 void FlowStat::ScaleToMonthly(uint runtime
)
4994 assert(runtime
> 0);
4995 SharesMap new_shares
;
4997 for (auto i
: this->shares
) {
4998 share
= std::max(share
+ 1, i
.first
* 30 / runtime
);
4999 new_shares
[share
] = i
.second
;
5000 if (this->unrestricted
== i
.first
) this->unrestricted
= share
;
5002 this->shares
.swap(new_shares
);
5006 * Add some flow from "origin", going via "via".
5007 * @param origin Origin of the flow.
5008 * @param via Next hop.
5009 * @param flow Amount of flow to be added.
5011 void FlowStatMap::AddFlow(StationID origin
, StationID via
, uint flow
)
5013 FlowStatMap::iterator origin_it
= this->find(origin
);
5014 if (origin_it
== this->end()) {
5015 this->emplace(origin
, FlowStat(via
, flow
));
5017 origin_it
->second
.ChangeShare(via
, flow
);
5018 assert(!origin_it
->second
.GetShares()->empty());
5023 * Pass on some flow, remembering it as invalid, for later subtraction from
5024 * locally consumed flow. This is necessary because we can't have negative
5025 * flows and we don't want to sort the flows before adding them up.
5026 * @param origin Origin of the flow.
5027 * @param via Next hop.
5028 * @param flow Amount of flow to be passed.
5030 void FlowStatMap::PassOnFlow(StationID origin
, StationID via
, uint flow
)
5032 FlowStatMap::iterator prev_it
= this->find(origin
);
5033 if (prev_it
== this->end()) {
5034 FlowStat
fs(via
, flow
);
5035 fs
.AppendShare(INVALID_STATION
, flow
);
5036 this->emplace(origin
, fs
);
5038 prev_it
->second
.ChangeShare(via
, flow
);
5039 prev_it
->second
.ChangeShare(INVALID_STATION
, flow
);
5040 assert(!prev_it
->second
.GetShares()->empty());
5045 * Subtract invalid flows from locally consumed flow.
5046 * @param self ID of own station.
5048 void FlowStatMap::FinalizeLocalConsumption(StationID self
)
5050 for (auto &i
: *this) {
5051 FlowStat
&fs
= i
.second
;
5052 uint local
= fs
.GetShare(INVALID_STATION
);
5053 if (local
> INT_MAX
) { // make sure it fits in an int
5054 fs
.ChangeShare(self
, -INT_MAX
);
5055 fs
.ChangeShare(INVALID_STATION
, -INT_MAX
);
5058 fs
.ChangeShare(self
, -(int)local
);
5059 fs
.ChangeShare(INVALID_STATION
, -(int)local
);
5061 /* If the local share is used up there must be a share for some
5062 * remote station. */
5063 assert(!fs
.GetShares()->empty());
5068 * Delete all flows at a station for specific cargo and destination.
5069 * @param via Remote station of flows to be deleted.
5070 * @return IDs of source stations for which the complete FlowStat, not only a
5071 * share, has been erased.
5073 StationIDStack
FlowStatMap::DeleteFlows(StationID via
)
5076 for (FlowStatMap::iterator f_it
= this->begin(); f_it
!= this->end();) {
5077 FlowStat
&s_flows
= f_it
->second
;
5078 s_flows
.ChangeShare(via
, INT_MIN
);
5079 if (s_flows
.GetShares()->empty()) {
5080 ret
.Push(f_it
->first
);
5081 this->erase(f_it
++);
5090 * Restrict all flows at a station for specific cargo and destination.
5091 * @param via Remote station of flows to be restricted.
5093 void FlowStatMap::RestrictFlows(StationID via
)
5095 for (auto &it
: *this) {
5096 it
.second
.RestrictShare(via
);
5101 * Release all flows at a station for specific cargo and destination.
5102 * @param via Remote station of flows to be released.
5104 void FlowStatMap::ReleaseFlows(StationID via
)
5106 for (auto &it
: *this) {
5107 it
.second
.ReleaseShare(via
);
5112 * Get the sum of all flows from this FlowStatMap.
5113 * @return sum of all flows.
5115 uint
FlowStatMap::GetFlow() const
5118 for (const auto &it
: *this) {
5119 ret
+= (--(it
.second
.GetShares()->end()))->first
;
5125 * Get the sum of flows via a specific station from this FlowStatMap.
5126 * @param via Remote station to look for.
5127 * @return all flows for 'via' added up.
5129 uint
FlowStatMap::GetFlowVia(StationID via
) const
5132 for (const auto &it
: *this) {
5133 ret
+= it
.second
.GetShare(via
);
5139 * Get the sum of flows from a specific station from this FlowStatMap.
5140 * @param from Origin station to look for.
5141 * @return all flows from 'from' added up.
5143 uint
FlowStatMap::GetFlowFrom(StationID from
) const
5145 FlowStatMap::const_iterator i
= this->find(from
);
5146 if (i
== this->end()) return 0;
5147 return (--(i
->second
.GetShares()->end()))->first
;
5151 * Get the flow from a specific station via a specific other station.
5152 * @param from Origin station to look for.
5153 * @param via Remote station to look for.
5154 * @return flow share originating at 'from' and going to 'via'.
5156 uint
FlowStatMap::GetFlowFromVia(StationID from
, StationID via
) const
5158 FlowStatMap::const_iterator i
= this->find(from
);
5159 if (i
== this->end()) return 0;
5160 return i
->second
.GetShare(via
);
5163 extern const TileTypeProcs _tile_type_station_procs
= {
5164 DrawTile_Station
, // draw_tile_proc
5165 GetSlopePixelZ_Station
, // get_slope_z_proc
5166 ClearTile_Station
, // clear_tile_proc
5167 nullptr, // add_accepted_cargo_proc
5168 GetTileDesc_Station
, // get_tile_desc_proc
5169 GetTileTrackStatus_Station
, // get_tile_track_status_proc
5170 ClickTile_Station
, // click_tile_proc
5171 AnimateTile_Station
, // animate_tile_proc
5172 TileLoop_Station
, // tile_loop_proc
5173 ChangeTileOwner_Station
, // change_tile_owner_proc
5174 nullptr, // add_produced_cargo_proc
5175 VehicleEnter_Station
, // vehicle_enter_tile_proc
5176 GetFoundation_Station
, // get_foundation_proc
5177 TerraformTile_Station
, // terraform_tile_proc