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 "cmd_helper.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_func.h"
32 #include "clear_func.h"
33 #include "date_func.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_kdtree.h"
40 #include "roadstop_base.h"
41 #include "newgrf_railtype.h"
42 #include "newgrf_roadtype.h"
43 #include "waypoint_base.h"
44 #include "waypoint_func.h"
47 #include "core/random_func.hpp"
48 #include "company_base.h"
49 #include "table/airporttile_ids.h"
50 #include "newgrf_airporttiles.h"
51 #include "order_backup.h"
52 #include "newgrf_house.h"
53 #include "company_gui.h"
54 #include "linkgraph/linkgraph_base.h"
55 #include "linkgraph/refresh.h"
56 #include "widgets/station_widget.h"
57 #include "tunnelbridge_map.h"
59 #include "table/strings.h"
61 #include "safeguards.h"
64 * Static instance of FlowStat::SharesMap.
65 * Note: This instance is created on task start.
66 * Lazy creation on first usage results in a data race between the CDist threads.
68 /* static */ const FlowStat::SharesMap
FlowStat::empty_sharesmap
;
71 * Check whether the given tile is a hangar.
72 * @param t the tile to of whether it is a hangar.
73 * @pre IsTileType(t, MP_STATION)
74 * @return true if and only if the tile is a hangar.
76 bool IsHangar(TileIndex t
)
78 assert(IsTileType(t
, MP_STATION
));
80 /* If the tile isn't an airport there's no chance it's a hangar. */
81 if (!IsAirport(t
)) return false;
83 const Station
*st
= Station::GetByTile(t
);
84 const AirportSpec
*as
= st
->airport
.GetSpec();
86 for (uint i
= 0; i
< as
->nof_depots
; i
++) {
87 if (st
->airport
.GetHangarTile(i
) == t
) return true;
94 * Look for a station owned by the given company around the given tile area.
95 * @param ta the area to search over
96 * @param closest_station the closest owned station found so far
97 * @param company the company whose stations to look for
98 * @param st to 'return' the found station
99 * @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
102 CommandCost
GetStationAround(TileArea ta
, StationID closest_station
, CompanyID company
, T
**st
)
106 /* check around to see if there are any stations there owned by the company */
107 TILE_AREA_LOOP(tile_cur
, ta
) {
108 if (IsTileType(tile_cur
, MP_STATION
)) {
109 StationID t
= GetStationIndex(tile_cur
);
110 if (!T::IsValidID(t
) || Station::Get(t
)->owner
!= company
) continue;
111 if (closest_station
== INVALID_STATION
) {
113 } else if (closest_station
!= t
) {
114 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
118 *st
= (closest_station
== INVALID_STATION
) ? nullptr : T::Get(closest_station
);
119 return CommandCost();
123 * Function to check whether the given tile matches some criterion.
124 * @param tile the tile to check
125 * @return true if it matches, false otherwise
127 typedef bool (*CMSAMatcher
)(TileIndex tile
);
130 * Counts the numbers of tiles matching a specific type in the area around
131 * @param tile the center tile of the 'count area'
132 * @param cmp the comparator/matcher (@see CMSAMatcher)
133 * @return the number of matching tiles around
135 static int CountMapSquareAround(TileIndex tile
, CMSAMatcher cmp
)
139 for (int dx
= -3; dx
<= 3; dx
++) {
140 for (int dy
= -3; dy
<= 3; dy
++) {
141 TileIndex t
= TileAddWrap(tile
, dx
, dy
);
142 if (t
!= INVALID_TILE
&& cmp(t
)) num
++;
150 * Check whether the tile is a mine.
151 * @param tile the tile to investigate.
152 * @return true if and only if the tile is a mine
154 static bool CMSAMine(TileIndex tile
)
157 if (!IsTileType(tile
, MP_INDUSTRY
)) return false;
159 const Industry
*ind
= Industry::GetByTile(tile
);
161 /* No extractive industry */
162 if ((GetIndustrySpec(ind
->type
)->life_type
& INDUSTRYLIFE_EXTRACTIVE
) == 0) return false;
164 for (uint i
= 0; i
< lengthof(ind
->produced_cargo
); i
++) {
165 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
166 * Also the production of passengers and mail is ignored. */
167 if (ind
->produced_cargo
[i
] != CT_INVALID
&&
168 (CargoSpec::Get(ind
->produced_cargo
[i
])->classes
& (CC_LIQUID
| CC_PASSENGERS
| CC_MAIL
)) == 0) {
177 * Check whether the tile is water.
178 * @param tile the tile to investigate.
179 * @return true if and only if the tile is a water tile
181 static bool CMSAWater(TileIndex tile
)
183 return IsTileType(tile
, MP_WATER
) && IsWater(tile
);
187 * Check whether the tile is a tree.
188 * @param tile the tile to investigate.
189 * @return true if and only if the tile is a tree tile
191 static bool CMSATree(TileIndex tile
)
193 return IsTileType(tile
, MP_TREES
);
196 #define M(x) ((x) - STR_SV_STNAME)
201 STATIONNAMING_AIRPORT
,
202 STATIONNAMING_OILRIG
,
204 STATIONNAMING_HELIPORT
,
207 /** Information to handle station action 0 property 24 correctly */
208 struct StationNameInformation
{
209 uint32 free_names
; ///< Current bitset of free names (we can remove names).
210 bool *indtypes
; ///< Array of bools telling whether an industry type has been found.
214 * Find a station action 0 property 24 station name, or reduce the
215 * free_names if needed.
216 * @param tile the tile to search
217 * @param user_data the StationNameInformation to base the search on
218 * @return true if the tile contains an industry that has not given
219 * its name to one of the other stations in town.
221 static bool FindNearIndustryName(TileIndex tile
, void *user_data
)
223 /* All already found industry types */
224 StationNameInformation
*sni
= (StationNameInformation
*)user_data
;
225 if (!IsTileType(tile
, MP_INDUSTRY
)) return false;
227 /* If the station name is undefined it means that it doesn't name a station */
228 IndustryType indtype
= GetIndustryType(tile
);
229 if (GetIndustrySpec(indtype
)->station_name
== STR_UNDEFINED
) return false;
231 /* In all cases if an industry that provides a name is found two of
232 * the standard names will be disabled. */
233 sni
->free_names
&= ~(1 << M(STR_SV_STNAME_OILFIELD
) | 1 << M(STR_SV_STNAME_MINES
));
234 return !sni
->indtypes
[indtype
];
237 static StringID
GenerateStationName(Station
*st
, TileIndex tile
, StationNaming name_class
)
239 static const uint32 _gen_station_name_bits
[] = {
240 0, // STATIONNAMING_RAIL
241 0, // STATIONNAMING_ROAD
242 1U << M(STR_SV_STNAME_AIRPORT
), // STATIONNAMING_AIRPORT
243 1U << M(STR_SV_STNAME_OILFIELD
), // STATIONNAMING_OILRIG
244 1U << M(STR_SV_STNAME_DOCKS
), // STATIONNAMING_DOCK
245 1U << M(STR_SV_STNAME_HELIPORT
), // STATIONNAMING_HELIPORT
248 const Town
*t
= st
->town
;
249 uint32 free_names
= UINT32_MAX
;
251 bool indtypes
[NUM_INDUSTRYTYPES
];
252 memset(indtypes
, 0, sizeof(indtypes
));
254 for (const Station
*s
: Station::Iterate()) {
255 if (s
!= st
&& s
->town
== t
) {
256 if (s
->indtype
!= IT_INVALID
) {
257 indtypes
[s
->indtype
] = true;
258 StringID name
= GetIndustrySpec(s
->indtype
)->station_name
;
259 if (name
!= STR_UNDEFINED
) {
260 /* Filter for other industrytypes with the same name */
261 for (IndustryType it
= 0; it
< NUM_INDUSTRYTYPES
; it
++) {
262 const IndustrySpec
*indsp
= GetIndustrySpec(it
);
263 if (indsp
->enabled
&& indsp
->station_name
== name
) indtypes
[it
] = true;
268 uint str
= M(s
->string_id
);
270 if (str
== M(STR_SV_STNAME_FOREST
)) {
271 str
= M(STR_SV_STNAME_WOODS
);
273 ClrBit(free_names
, str
);
278 TileIndex indtile
= tile
;
279 StationNameInformation sni
= { free_names
, indtypes
};
280 if (CircularTileSearch(&indtile
, 7, FindNearIndustryName
, &sni
)) {
281 /* An industry has been found nearby */
282 IndustryType indtype
= GetIndustryType(indtile
);
283 const IndustrySpec
*indsp
= GetIndustrySpec(indtype
);
284 /* STR_NULL means it only disables oil rig/mines */
285 if (indsp
->station_name
!= STR_NULL
) {
286 st
->indtype
= indtype
;
287 return STR_SV_STNAME_FALLBACK
;
291 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
292 free_names
= sni
.free_names
;
294 /* check default names */
295 uint32 tmp
= free_names
& _gen_station_name_bits
[name_class
];
296 if (tmp
!= 0) return STR_SV_STNAME
+ FindFirstBit(tmp
);
299 if (HasBit(free_names
, M(STR_SV_STNAME_MINES
))) {
300 if (CountMapSquareAround(tile
, CMSAMine
) >= 2) {
301 return STR_SV_STNAME_MINES
;
305 /* check close enough to town to get central as name? */
306 if (DistanceMax(tile
, t
->xy
) < 8) {
307 if (HasBit(free_names
, M(STR_SV_STNAME
))) return STR_SV_STNAME
;
309 if (HasBit(free_names
, M(STR_SV_STNAME_CENTRAL
))) return STR_SV_STNAME_CENTRAL
;
313 if (HasBit(free_names
, M(STR_SV_STNAME_LAKESIDE
)) &&
314 DistanceFromEdge(tile
) < 20 &&
315 CountMapSquareAround(tile
, CMSAWater
) >= 5) {
316 return STR_SV_STNAME_LAKESIDE
;
320 if (HasBit(free_names
, M(STR_SV_STNAME_WOODS
)) && (
321 CountMapSquareAround(tile
, CMSATree
) >= 8 ||
322 CountMapSquareAround(tile
, IsTileForestIndustry
) >= 2)
324 return _settings_game
.game_creation
.landscape
== LT_TROPIC
? STR_SV_STNAME_FOREST
: STR_SV_STNAME_WOODS
;
327 /* check elevation compared to town */
328 int z
= GetTileZ(tile
);
329 int z2
= GetTileZ(t
->xy
);
331 if (HasBit(free_names
, M(STR_SV_STNAME_VALLEY
))) return STR_SV_STNAME_VALLEY
;
333 if (HasBit(free_names
, M(STR_SV_STNAME_HEIGHTS
))) return STR_SV_STNAME_HEIGHTS
;
336 /* check direction compared to town */
337 static const int8 _direction_and_table
[] = {
338 ~( (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
339 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
340 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
341 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) ),
344 free_names
&= _direction_and_table
[
345 (TileX(tile
) < TileX(t
->xy
)) +
346 (TileY(tile
) < TileY(t
->xy
)) * 2];
348 tmp
= free_names
& ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 12) | (1 << 26) | (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30));
349 return (tmp
== 0) ? STR_SV_STNAME_FALLBACK
: (STR_SV_STNAME
+ FindFirstBit(tmp
));
354 * Find the closest deleted station of the current company
355 * @param tile the tile to search from.
356 * @return the closest station or nullptr if too far.
358 static Station
*GetClosestDeletedStation(TileIndex tile
)
362 Station
*best_station
= nullptr;
363 ForAllStationsRadius(tile
, threshold
, [&](Station
*st
) {
364 if (!st
->IsInUse() && st
->owner
== _current_company
) {
365 uint cur_dist
= DistanceManhattan(tile
, st
->xy
);
367 if (cur_dist
< threshold
) {
368 threshold
= cur_dist
;
370 } else if (cur_dist
== threshold
&& best_station
!= nullptr) {
371 /* In case of a tie, lowest station ID wins */
372 if (st
->index
< best_station
->index
) best_station
= st
;
381 void Station::GetTileArea(TileArea
*ta
, StationType type
) const
385 *ta
= this->train_station
;
388 case STATION_AIRPORT
:
393 *ta
= this->truck_station
;
397 *ta
= this->bus_station
;
402 *ta
= this->docking_station
;
405 default: NOT_REACHED();
413 * Update the virtual coords needed to draw the station sign.
415 void Station::UpdateVirtCoord()
417 Point pt
= RemapCoords2(TileX(this->xy
) * TILE_SIZE
, TileY(this->xy
) * TILE_SIZE
);
419 pt
.y
-= 32 * ZOOM_LVL_BASE
;
420 if ((this->facilities
& FACIL_AIRPORT
) && this->airport
.type
== AT_OILRIG
) pt
.y
-= 16 * ZOOM_LVL_BASE
;
422 if (this->sign
.kdtree_valid
) _viewport_sign_kdtree
.Remove(ViewportSignKdtreeItem::MakeStation(this->index
));
424 SetDParam(0, this->index
);
425 SetDParam(1, this->facilities
);
426 this->sign
.UpdatePosition(pt
.x
, pt
.y
, STR_VIEWPORT_STATION
);
428 _viewport_sign_kdtree
.Insert(ViewportSignKdtreeItem::MakeStation(this->index
));
430 SetWindowDirty(WC_STATION_VIEW
, this->index
);
434 * Move the station main coordinate somewhere else.
435 * @param new_xy new tile location of the sign
437 void Station::MoveSign(TileIndex new_xy
)
439 if (this->xy
== new_xy
) return;
441 _station_kdtree
.Remove(this->index
);
443 this->BaseStation::MoveSign(new_xy
);
445 _station_kdtree
.Insert(this->index
);
448 /** Update the virtual coords needed to draw the station sign for all stations. */
449 void UpdateAllStationVirtCoords()
451 for (BaseStation
*st
: BaseStation::Iterate()) {
452 st
->UpdateVirtCoord();
456 void BaseStation::FillCachedName() const
458 char buf
[MAX_LENGTH_STATION_NAME_CHARS
* MAX_CHAR_LENGTH
];
459 int64 args_array
[] = { this->index
};
460 StringParameters
tmp_params(args_array
);
461 char *end
= GetStringWithArgs(buf
, Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME
: STR_STATION_NAME
, &tmp_params
, lastof(buf
));
462 this->cached_name
.assign(buf
, end
);
465 void ClearAllStationCachedNames()
467 for (BaseStation
*st
: BaseStation::Iterate()) {
468 st
->cached_name
.clear();
473 * Get a mask of the cargo types that the station accepts.
474 * @param st Station to query
475 * @return the expected mask
477 static CargoTypes
GetAcceptanceMask(const Station
*st
)
481 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
482 if (HasBit(st
->goods
[i
].status
, GoodsEntry::GES_ACCEPTANCE
)) SetBit(mask
, i
);
488 * Items contains the two cargo names that are to be accepted or rejected.
489 * msg is the string id of the message to display.
491 static void ShowRejectOrAcceptNews(const Station
*st
, uint num_items
, CargoID
*cargo
, StringID msg
)
493 for (uint i
= 0; i
< num_items
; i
++) {
494 SetDParam(i
+ 1, CargoSpec::Get(cargo
[i
])->name
);
497 SetDParam(0, st
->index
);
498 AddNewsItem(msg
, NT_ACCEPTANCE
, NF_INCOLOUR
| NF_SMALL
, NR_STATION
, st
->index
);
502 * Get the cargo types being produced around the tile (in a rectangle).
503 * @param tile Northtile of area
504 * @param w X extent of the area
505 * @param h Y extent of the area
506 * @param rad Search radius in addition to the given area
508 CargoArray
GetProductionAroundTiles(TileIndex tile
, int w
, int h
, int rad
)
511 std::set
<IndustryID
> industries
;
512 TileArea ta
= TileArea(tile
, w
, h
).Expand(rad
);
514 /* Loop over all tiles to get the produced cargo of
515 * everything except industries */
516 TILE_AREA_LOOP(tile
, ta
) {
517 if (IsTileType(tile
, MP_INDUSTRY
)) industries
.insert(GetIndustryIndex(tile
));
518 AddProducedCargo(tile
, produced
);
521 /* Loop over the seen industries. They produce cargo for
522 * anything that is within 'rad' of any one of their tiles.
524 for (IndustryID industry
: industries
) {
525 const Industry
*i
= Industry::Get(industry
);
526 /* Skip industry with neutral station */
527 if (i
->neutral_station
!= nullptr && !_settings_game
.station
.serve_neutral_industries
) continue;
529 for (uint j
= 0; j
< lengthof(i
->produced_cargo
); j
++) {
530 CargoID cargo
= i
->produced_cargo
[j
];
531 if (cargo
!= CT_INVALID
) produced
[cargo
]++;
539 * Get the acceptance of cargoes around the tile in 1/8.
540 * @param tile Center of the search area
541 * @param w X extent of area
542 * @param h Y extent of area
543 * @param rad Search radius in addition to given area
544 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
545 * @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
547 CargoArray
GetAcceptanceAroundTiles(TileIndex tile
, int w
, int h
, int rad
, CargoTypes
*always_accepted
)
549 CargoArray acceptance
;
550 if (always_accepted
!= nullptr) *always_accepted
= 0;
552 TileArea ta
= TileArea(tile
, w
, h
).Expand(rad
);
554 TILE_AREA_LOOP(tile
, ta
) {
555 /* Ignore industry if it has a neutral station. */
556 if (!_settings_game
.station
.serve_neutral_industries
&& IsTileType(tile
, MP_INDUSTRY
) && Industry::GetByTile(tile
)->neutral_station
!= nullptr) continue;
558 AddAcceptedCargo(tile
, acceptance
, always_accepted
);
565 * Get the acceptance of cargoes around the station in.
566 * @param st Station to get acceptance of.
567 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
569 static CargoArray
GetAcceptanceAroundStation(const Station
*st
, CargoTypes
*always_accepted
)
571 CargoArray acceptance
;
572 if (always_accepted
!= nullptr) *always_accepted
= 0;
574 BitmapTileIterator
it(st
->catchment_tiles
);
575 for (TileIndex tile
= it
; tile
!= INVALID_TILE
; tile
= ++it
) {
576 AddAcceptedCargo(tile
, acceptance
, always_accepted
);
583 * Update the acceptance for a station.
584 * @param st Station to update
585 * @param show_msg controls whether to display a message that acceptance was changed.
587 void UpdateStationAcceptance(Station
*st
, bool show_msg
)
589 /* old accepted goods types */
590 CargoTypes old_acc
= GetAcceptanceMask(st
);
592 /* And retrieve the acceptance. */
593 CargoArray acceptance
;
594 if (!st
->rect
.IsEmpty()) {
595 acceptance
= GetAcceptanceAroundStation(st
, &st
->always_accepted
);
598 /* Adjust in case our station only accepts fewer kinds of goods */
599 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
600 uint amt
= acceptance
[i
];
602 /* Make sure the station can accept the goods type. */
603 bool is_passengers
= IsCargoInClass(i
, CC_PASSENGERS
);
604 if ((!is_passengers
&& !(st
->facilities
& ~FACIL_BUS_STOP
)) ||
605 (is_passengers
&& !(st
->facilities
& ~FACIL_TRUCK_STOP
))) {
609 GoodsEntry
&ge
= st
->goods
[i
];
610 SB(ge
.status
, GoodsEntry::GES_ACCEPTANCE
, 1, amt
>= 8);
611 if (LinkGraph::IsValidID(ge
.link_graph
)) {
612 (*LinkGraph::Get(ge
.link_graph
))[ge
.node
].SetDemand(amt
/ 8);
616 /* Only show a message in case the acceptance was actually changed. */
617 CargoTypes new_acc
= GetAcceptanceMask(st
);
618 if (old_acc
== new_acc
) return;
620 /* show a message to report that the acceptance was changed? */
621 if (show_msg
&& st
->owner
== _local_company
&& st
->IsInUse()) {
622 /* List of accept and reject strings for different number of
624 static const StringID accept_msg
[] = {
625 STR_NEWS_STATION_NOW_ACCEPTS_CARGO
,
626 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO
,
628 static const StringID reject_msg
[] = {
629 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO
,
630 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO
,
633 /* Array of accepted and rejected cargo types */
634 CargoID accepts
[2] = { CT_INVALID
, CT_INVALID
};
635 CargoID rejects
[2] = { CT_INVALID
, CT_INVALID
};
639 /* Test each cargo type to see if its acceptance has changed */
640 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
641 if (HasBit(new_acc
, i
)) {
642 if (!HasBit(old_acc
, i
) && num_acc
< lengthof(accepts
)) {
643 /* New cargo is accepted */
644 accepts
[num_acc
++] = i
;
647 if (HasBit(old_acc
, i
) && num_rej
< lengthof(rejects
)) {
648 /* Old cargo is no longer accepted */
649 rejects
[num_rej
++] = i
;
654 /* Show news message if there are any changes */
655 if (num_acc
> 0) ShowRejectOrAcceptNews(st
, num_acc
, accepts
, accept_msg
[num_acc
- 1]);
656 if (num_rej
> 0) ShowRejectOrAcceptNews(st
, num_rej
, rejects
, reject_msg
[num_rej
- 1]);
659 /* redraw the station view since acceptance changed */
660 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ACCEPT_RATING_LIST
);
663 static void UpdateStationSignCoord(BaseStation
*st
)
665 const StationRect
*r
= &st
->rect
;
667 if (r
->IsEmpty()) return; // no tiles belong to this station
669 /* clamp sign coord to be inside the station rect */
670 TileIndex new_xy
= TileXY(ClampU(TileX(st
->xy
), r
->left
, r
->right
), ClampU(TileY(st
->xy
), r
->top
, r
->bottom
));
671 st
->MoveSign(new_xy
);
673 if (!Station::IsExpected(st
)) return;
674 Station
*full_station
= Station::From(st
);
675 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
676 LinkGraphID lg
= full_station
->goods
[c
].link_graph
;
677 if (!LinkGraph::IsValidID(lg
)) continue;
678 (*LinkGraph::Get(lg
))[full_station
->goods
[c
].node
].UpdateLocation(st
->xy
);
683 * Common part of building various station parts and possibly attaching them to an existing one.
684 * @param[in,out] st Station to attach to
685 * @param flags Command flags
686 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
687 * @param area Area occupied by the new part
688 * @param name_class Station naming class to use to generate the new station's name
689 * @return Command error that occurred, if any
691 static CommandCost
BuildStationPart(Station
**st
, DoCommandFlag flags
, bool reuse
, TileArea area
, StationNaming name_class
)
693 /* Find a deleted station close to us */
694 if (*st
== nullptr && reuse
) *st
= GetClosestDeletedStation(area
.tile
);
696 if (*st
!= nullptr) {
697 if ((*st
)->owner
!= _current_company
) {
698 return_cmd_error(CMD_ERROR
);
701 CommandCost ret
= (*st
)->rect
.BeforeAddRect(area
.tile
, area
.w
, area
.h
, StationRect::ADD_TEST
);
702 if (ret
.Failed()) return ret
;
704 /* allocate and initialize new station */
705 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING
);
707 if (flags
& DC_EXEC
) {
708 *st
= new Station(area
.tile
);
709 _station_kdtree
.Insert((*st
)->index
);
711 (*st
)->town
= ClosestTownFromTile(area
.tile
, UINT_MAX
);
712 (*st
)->string_id
= GenerateStationName(*st
, area
.tile
, name_class
);
714 if (Company::IsValidID(_current_company
)) {
715 SetBit((*st
)->town
->have_ratings
, _current_company
);
719 return CommandCost();
723 * This is called right after a station was deleted.
724 * It checks if the whole station is free of substations, and if so, the station will be
725 * deleted after a little while.
728 static void DeleteStationIfEmpty(BaseStation
*st
)
730 if (!st
->IsInUse()) {
732 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
734 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
735 UpdateStationSignCoord(st
);
739 * After adding/removing tiles to station, update some station-related stuff.
740 * @param adding True if adding tiles, false if removing them.
741 * @param type StationType being modified.
743 void Station::AfterStationTileSetChange(bool adding
, StationType type
)
745 this->UpdateVirtCoord();
746 this->RecomputeCatchment();
747 DirtyCompanyInfrastructureWindows(this->owner
);
748 if (adding
) InvalidateWindowData(WC_STATION_LIST
, this->owner
, 0);
752 SetWindowWidgetDirty(WC_STATION_VIEW
, this->index
, WID_SV_TRAINS
);
754 case STATION_AIRPORT
:
758 SetWindowWidgetDirty(WC_STATION_VIEW
, this->index
, WID_SV_ROADVEHS
);
761 SetWindowWidgetDirty(WC_STATION_VIEW
, this->index
, WID_SV_SHIPS
);
763 default: NOT_REACHED();
767 UpdateStationAcceptance(this, false);
768 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
770 DeleteStationIfEmpty(this);
775 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
);
778 * Checks if the given tile is buildable, flat and has a certain height.
779 * @param tile TileIndex to check.
780 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
781 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
782 * @param allow_steep Whether steep slopes are allowed.
783 * @param check_bridge Check for the existence of a bridge.
784 * @return The cost in case of success, or an error code if it failed.
786 CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
= true)
788 if (check_bridge
&& IsBridgeAbove(tile
)) {
789 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
792 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
793 if (ret
.Failed()) return ret
;
796 Slope tileh
= GetTileSlope(tile
, &z
);
798 /* Prohibit building if
799 * 1) The tile is "steep" (i.e. stretches two height levels).
800 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
802 if ((!allow_steep
&& IsSteepSlope(tileh
)) ||
803 ((!_settings_game
.construction
.build_on_slopes
) && tileh
!= SLOPE_FLAT
)) {
804 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
807 CommandCost
cost(EXPENSES_CONSTRUCTION
);
808 int flat_z
= z
+ GetSlopeMaxZ(tileh
);
809 if (tileh
!= SLOPE_FLAT
) {
810 /* Forbid building if the tile faces a slope in a invalid direction. */
811 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
!= DIAGDIR_END
; dir
++) {
812 if (HasBit(invalid_dirs
, dir
) && !CanBuildDepotByTileh(dir
, tileh
)) {
813 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
816 cost
.AddCost(_price
[PR_BUILD_FOUNDATION
]);
819 /* The level of this tile must be equal to allowed_z. */
823 } else if (allowed_z
!= flat_z
) {
824 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
831 * Checks if an airport can be built at the given location and clear the area.
832 * @param tile_iter Airport tile iterator.
833 * @param flags Operation to perform.
834 * @return The cost in case of success, or an error code if it failed.
836 static CommandCost
CheckFlatLandAirport(AirportTileTableIterator tile_iter
, DoCommandFlag flags
)
838 CommandCost
cost(EXPENSES_CONSTRUCTION
);
841 for (; tile_iter
!= INVALID_TILE
; ++tile_iter
) {
842 CommandCost ret
= CheckBuildableTile(tile_iter
, 0, allowed_z
, true);
843 if (ret
.Failed()) return ret
;
846 ret
= DoCommand(tile_iter
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
847 if (ret
.Failed()) return ret
;
855 * Checks if a rail station can be built at the given area.
856 * @param tile_area Area to check.
857 * @param flags Operation to perform.
858 * @param axis Rail station axis.
859 * @param station StationID to be queried and returned if available.
860 * @param rt The rail type to check for (overbuilding rail stations over rail).
861 * @param affected_vehicles List of trains with PBS reservations on the tiles
862 * @param spec_class Station class.
863 * @param spec_index Index into the station class.
864 * @param plat_len Platform length.
865 * @param numtracks Number of platforms.
866 * @return The cost in case of success, or an error code if it failed.
868 static CommandCost
CheckFlatLandRailStation(TileArea tile_area
, DoCommandFlag flags
, Axis axis
, StationID
*station
, RailType rt
, std::vector
<Train
*> &affected_vehicles
, StationClassID spec_class
, byte spec_index
, byte plat_len
, byte numtracks
)
870 CommandCost
cost(EXPENSES_CONSTRUCTION
);
872 uint invalid_dirs
= 5 << axis
;
874 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
875 bool slope_cb
= statspec
!= nullptr && HasBit(statspec
->callback_mask
, CBM_STATION_SLOPE_CHECK
);
877 TILE_AREA_LOOP(tile_cur
, tile_area
) {
878 CommandCost ret
= CheckBuildableTile(tile_cur
, invalid_dirs
, allowed_z
, false);
879 if (ret
.Failed()) return ret
;
883 /* Do slope check if requested. */
884 ret
= PerformStationTileSlopeCheck(tile_area
.tile
, tile_cur
, statspec
, axis
, plat_len
, numtracks
);
885 if (ret
.Failed()) return ret
;
888 /* if station is set, then we have special handling to allow building on top of already existing stations.
889 * so station points to INVALID_STATION if we can build on any station.
890 * Or it points to a station if we're only allowed to build on exactly that station. */
891 if (station
!= nullptr && IsTileType(tile_cur
, MP_STATION
)) {
892 if (!IsRailStation(tile_cur
)) {
893 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
895 StationID st
= GetStationIndex(tile_cur
);
896 if (*station
== INVALID_STATION
) {
898 } else if (*station
!= st
) {
899 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
903 /* Rail type is only valid when building a railway station; if station to
904 * build isn't a rail station it's INVALID_RAILTYPE. */
905 if (rt
!= INVALID_RAILTYPE
&&
906 IsPlainRailTile(tile_cur
) && !HasSignals(tile_cur
) &&
907 HasPowerOnRail(GetRailType(tile_cur
), rt
)) {
908 /* Allow overbuilding if the tile:
909 * - has rail, but no signals
910 * - it has exactly one track
911 * - the track is in line with the station
912 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
914 TrackBits tracks
= GetTrackBits(tile_cur
);
915 Track track
= RemoveFirstTrack(&tracks
);
916 Track expected_track
= HasBit(invalid_dirs
, DIAGDIR_NE
) ? TRACK_X
: TRACK_Y
;
918 if (tracks
== TRACK_BIT_NONE
&& track
== expected_track
) {
919 /* Check for trains having a reservation for this tile. */
920 if (HasBit(GetRailReservationTrackBits(tile_cur
), track
)) {
921 Train
*v
= GetTrainForReservation(tile_cur
, track
);
923 affected_vehicles
.push_back(v
);
926 CommandCost ret
= DoCommand(tile_cur
, 0, track
, flags
, CMD_REMOVE_SINGLE_RAIL
);
927 if (ret
.Failed()) return ret
;
929 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
933 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
934 if (ret
.Failed()) return ret
;
943 * Checks if a road stop can be built at the given tile.
944 * @param tile_area Area to check.
945 * @param flags Operation to perform.
946 * @param invalid_dirs Prohibited directions (set of DiagDirections).
947 * @param is_drive_through True if trying to build a drive-through station.
948 * @param is_truck_stop True when building a truck stop, false otherwise.
949 * @param axis Axis of a drive-through road stop.
950 * @param station StationID to be queried and returned if available.
951 * @param rt Road type to build.
952 * @return The cost in case of success, or an error code if it failed.
954 static CommandCost
CheckFlatLandRoadStop(TileArea tile_area
, DoCommandFlag flags
, uint invalid_dirs
, bool is_drive_through
, bool is_truck_stop
, Axis axis
, StationID
*station
, RoadType rt
)
956 CommandCost
cost(EXPENSES_CONSTRUCTION
);
959 TILE_AREA_LOOP(cur_tile
, tile_area
) {
960 CommandCost ret
= CheckBuildableTile(cur_tile
, invalid_dirs
, allowed_z
, !is_drive_through
);
961 if (ret
.Failed()) return ret
;
964 /* If station is set, then we have special handling to allow building on top of already existing stations.
965 * Station points to INVALID_STATION if we can build on any station.
966 * Or it points to a station if we're only allowed to build on exactly that station. */
967 if (station
!= nullptr && IsTileType(cur_tile
, MP_STATION
)) {
968 if (!IsRoadStop(cur_tile
)) {
969 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
971 if (is_truck_stop
!= IsTruckStop(cur_tile
) ||
972 is_drive_through
!= IsDriveThroughStopTile(cur_tile
)) {
973 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
975 /* Drive-through station in the wrong direction. */
976 if (is_drive_through
&& IsDriveThroughStopTile(cur_tile
) && DiagDirToAxis(GetRoadStopDir(cur_tile
)) != axis
){
977 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
979 StationID st
= GetStationIndex(cur_tile
);
980 if (*station
== INVALID_STATION
) {
982 } else if (*station
!= st
) {
983 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
987 bool build_over_road
= is_drive_through
&& IsNormalRoadTile(cur_tile
);
988 /* Road bits in the wrong direction. */
989 RoadBits rb
= IsNormalRoadTile(cur_tile
) ? GetAllRoadBits(cur_tile
) : ROAD_NONE
;
990 if (build_over_road
&& (rb
& (axis
== AXIS_X
? ROAD_Y
: ROAD_X
)) != 0) {
991 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
992 switch (CountBits(rb
)) {
994 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
997 if (rb
== ROAD_X
|| rb
== ROAD_Y
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
998 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER
);
1001 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION
);
1005 if (build_over_road
) {
1006 /* There is a road, check if we can build road+tram stop over it. */
1007 RoadType road_rt
= GetRoadType(cur_tile
, RTT_ROAD
);
1008 if (road_rt
!= INVALID_ROADTYPE
) {
1009 Owner road_owner
= GetRoadOwner(cur_tile
, RTT_ROAD
);
1010 if (road_owner
== OWNER_TOWN
) {
1011 if (!_settings_game
.construction
.road_stop_on_town_road
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD
);
1012 } else if (!_settings_game
.construction
.road_stop_on_competitor_road
&& road_owner
!= OWNER_NONE
) {
1013 CommandCost ret
= CheckOwnership(road_owner
);
1014 if (ret
.Failed()) return ret
;
1016 uint num_pieces
= CountBits(GetRoadBits(cur_tile
, RTT_ROAD
));
1018 if (RoadTypeIsRoad(rt
) && !HasPowerOnRoad(rt
, road_rt
)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD
);
1020 if (GetDisallowedRoadDirections(cur_tile
) != DRD_NONE
&& road_owner
!= OWNER_TOWN
) {
1021 CommandCost ret
= CheckOwnership(road_owner
);
1022 if (ret
.Failed()) return ret
;
1025 cost
.AddCost(RoadBuildCost(road_rt
) * (2 - num_pieces
));
1026 } else if (RoadTypeIsRoad(rt
)) {
1027 cost
.AddCost(RoadBuildCost(rt
) * 2);
1030 /* There is a tram, check if we can build road+tram stop over it. */
1031 RoadType tram_rt
= GetRoadType(cur_tile
, RTT_TRAM
);
1032 if (tram_rt
!= INVALID_ROADTYPE
) {
1033 Owner tram_owner
= GetRoadOwner(cur_tile
, RTT_TRAM
);
1034 if (Company::IsValidID(tram_owner
) &&
1035 (!_settings_game
.construction
.road_stop_on_competitor_road
||
1036 /* Disallow breaking end-of-line of someone else
1037 * so trams can still reverse on this tile. */
1038 HasExactlyOneBit(GetRoadBits(cur_tile
, RTT_TRAM
)))) {
1039 CommandCost ret
= CheckOwnership(tram_owner
);
1040 if (ret
.Failed()) return ret
;
1042 uint num_pieces
= CountBits(GetRoadBits(cur_tile
, RTT_TRAM
));
1044 if (RoadTypeIsTram(rt
) && !HasPowerOnRoad(rt
, tram_rt
)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD
);
1046 cost
.AddCost(RoadBuildCost(tram_rt
) * (2 - num_pieces
));
1047 } else if (RoadTypeIsTram(rt
)) {
1048 cost
.AddCost(RoadBuildCost(rt
) * 2);
1051 ret
= DoCommand(cur_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
1052 if (ret
.Failed()) return ret
;
1054 cost
.AddCost(RoadBuildCost(rt
) * 2);
1063 * Check whether we can expand the rail part of the given station.
1064 * @param st the station to expand
1065 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1066 * @param axis the axis of the newly build rail
1067 * @return Succeeded or failed command.
1069 CommandCost
CanExpandRailStation(const BaseStation
*st
, TileArea
&new_ta
, Axis axis
)
1071 TileArea cur_ta
= st
->train_station
;
1073 /* determine new size of train station region.. */
1074 int x
= min(TileX(cur_ta
.tile
), TileX(new_ta
.tile
));
1075 int y
= min(TileY(cur_ta
.tile
), TileY(new_ta
.tile
));
1076 new_ta
.w
= max(TileX(cur_ta
.tile
) + cur_ta
.w
, TileX(new_ta
.tile
) + new_ta
.w
) - x
;
1077 new_ta
.h
= max(TileY(cur_ta
.tile
) + cur_ta
.h
, TileY(new_ta
.tile
) + new_ta
.h
) - y
;
1078 new_ta
.tile
= TileXY(x
, y
);
1080 /* make sure the final size is not too big. */
1081 if (new_ta
.w
> _settings_game
.station
.station_spread
|| new_ta
.h
> _settings_game
.station
.station_spread
) {
1082 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1085 return CommandCost();
1088 static inline byte
*CreateSingle(byte
*layout
, int n
)
1091 do *layout
++ = 0; while (--i
);
1092 layout
[((n
- 1) >> 1) - n
] = 2;
1096 static inline byte
*CreateMulti(byte
*layout
, int n
, byte b
)
1099 do *layout
++ = b
; while (--i
);
1102 layout
[n
- 1 - n
] = 0;
1108 * Create the station layout for the given number of tracks and platform length.
1109 * @param layout The layout to write to.
1110 * @param numtracks The number of tracks to write.
1111 * @param plat_len The length of the platforms.
1112 * @param statspec The specification of the station to (possibly) get the layout from.
1114 void GetStationLayout(byte
*layout
, int numtracks
, int plat_len
, const StationSpec
*statspec
)
1116 if (statspec
!= nullptr && statspec
->lengths
>= plat_len
&&
1117 statspec
->platforms
[plat_len
- 1] >= numtracks
&&
1118 statspec
->layouts
[plat_len
- 1][numtracks
- 1]) {
1119 /* Custom layout defined, follow it. */
1120 memcpy(layout
, statspec
->layouts
[plat_len
- 1][numtracks
- 1],
1121 plat_len
* numtracks
);
1125 if (plat_len
== 1) {
1126 CreateSingle(layout
, numtracks
);
1128 if (numtracks
& 1) layout
= CreateSingle(layout
, plat_len
);
1131 while (--numtracks
>= 0) {
1132 layout
= CreateMulti(layout
, plat_len
, 4);
1133 layout
= CreateMulti(layout
, plat_len
, 6);
1139 * Find a nearby station that joins this station.
1140 * @tparam T the class to find a station for
1141 * @tparam error_message the error message when building a station on top of others
1142 * @param existing_station an existing station we build over
1143 * @param station_to_join the station to join to
1144 * @param adjacent whether adjacent stations are allowed
1145 * @param ta the area of the newly build station
1146 * @param st 'return' pointer for the found station
1147 * @return command cost with the error or 'okay'
1149 template <class T
, StringID error_message
>
1150 CommandCost
FindJoiningBaseStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, T
**st
)
1152 assert(*st
== nullptr);
1153 bool check_surrounding
= true;
1155 if (_settings_game
.station
.adjacent_stations
) {
1156 if (existing_station
!= INVALID_STATION
) {
1157 if (adjacent
&& existing_station
!= station_to_join
) {
1158 /* You can't build an adjacent station over the top of one that
1159 * already exists. */
1160 return_cmd_error(error_message
);
1162 /* Extend the current station, and don't check whether it will
1163 * be near any other stations. */
1164 *st
= T::GetIfValid(existing_station
);
1165 check_surrounding
= (*st
== nullptr);
1168 /* There's no station here. Don't check the tiles surrounding this
1169 * one if the company wanted to build an adjacent station. */
1170 if (adjacent
) check_surrounding
= false;
1174 if (check_surrounding
) {
1175 /* Make sure there is no more than one other station around us that is owned by us. */
1176 CommandCost ret
= GetStationAround(ta
, existing_station
, _current_company
, st
);
1177 if (ret
.Failed()) return ret
;
1181 if (*st
== nullptr && station_to_join
!= INVALID_STATION
) *st
= T::GetIfValid(station_to_join
);
1183 return CommandCost();
1187 * Find a nearby station that joins this station.
1188 * @param existing_station an existing station we build over
1189 * @param station_to_join the station to join to
1190 * @param adjacent whether adjacent stations are allowed
1191 * @param ta the area of the newly build station
1192 * @param st 'return' pointer for the found station
1193 * @return command cost with the error or 'okay'
1195 static CommandCost
FindJoiningStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, Station
**st
)
1197 return FindJoiningBaseStation
<Station
, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST
>(existing_station
, station_to_join
, adjacent
, ta
, st
);
1201 * Find a nearby waypoint that joins this waypoint.
1202 * @param existing_waypoint an existing waypoint we build over
1203 * @param waypoint_to_join the waypoint to join to
1204 * @param adjacent whether adjacent waypoints are allowed
1205 * @param ta the area of the newly build waypoint
1206 * @param wp 'return' pointer for the found waypoint
1207 * @return command cost with the error or 'okay'
1209 CommandCost
FindJoiningWaypoint(StationID existing_waypoint
, StationID waypoint_to_join
, bool adjacent
, TileArea ta
, Waypoint
**wp
)
1211 return FindJoiningBaseStation
<Waypoint
, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST
>(existing_waypoint
, waypoint_to_join
, adjacent
, ta
, wp
);
1215 * Clear platform reservation during station building/removing.
1216 * @param v vehicle which holds reservation
1218 static void FreeTrainReservation(Train
*v
)
1220 FreeTrainTrackReservation(v
);
1221 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(v
->GetVehicleTrackdir()), false);
1223 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(ReverseTrackdir(v
->GetVehicleTrackdir())), false);
1227 * Restore platform reservation during station building/removing.
1228 * @param v vehicle which held reservation
1230 static void RestoreTrainReservation(Train
*v
)
1232 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(v
->GetVehicleTrackdir()), true);
1233 TryPathReserve(v
, true, true);
1235 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(ReverseTrackdir(v
->GetVehicleTrackdir())), true);
1239 * Build rail station
1240 * @param tile_org northern most position of station dragging/placement
1241 * @param flags operation to perform
1242 * @param p1 various bitstuffed elements
1243 * - p1 = (bit 0- 5) - railtype
1244 * - p1 = (bit 6) - orientation (Axis)
1245 * - p1 = (bit 8-15) - number of tracks
1246 * - p1 = (bit 16-23) - platform length
1247 * - p1 = (bit 24) - allow stations directly adjacent to other stations.
1248 * @param p2 various bitstuffed elements
1249 * - p2 = (bit 0- 7) - custom station class
1250 * - p2 = (bit 8-15) - custom station id
1251 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
1252 * @param text unused
1253 * @return the cost of this operation or an error
1255 CommandCost
CmdBuildRailStation(TileIndex tile_org
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1257 /* Unpack parameters */
1258 RailType rt
= Extract
<RailType
, 0, 6>(p1
);
1259 Axis axis
= Extract
<Axis
, 6, 1>(p1
);
1260 byte numtracks
= GB(p1
, 8, 8);
1261 byte plat_len
= GB(p1
, 16, 8);
1262 bool adjacent
= HasBit(p1
, 24);
1264 StationClassID spec_class
= Extract
<StationClassID
, 0, 8>(p2
);
1265 byte spec_index
= GB(p2
, 8, 8);
1266 StationID station_to_join
= GB(p2
, 16, 16);
1268 /* Does the authority allow this? */
1269 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile_org
, flags
);
1270 if (ret
.Failed()) return ret
;
1272 if (!ValParamRailtype(rt
)) return CMD_ERROR
;
1274 /* Check if the given station class is valid */
1275 if ((uint
)spec_class
>= StationClass::GetClassCount() || spec_class
== STAT_CLASS_WAYP
) return CMD_ERROR
;
1276 if (spec_index
>= StationClass::Get(spec_class
)->GetSpecCount()) return CMD_ERROR
;
1277 if (plat_len
== 0 || numtracks
== 0) return CMD_ERROR
;
1280 if (axis
== AXIS_X
) {
1288 bool reuse
= (station_to_join
!= NEW_STATION
);
1289 if (!reuse
) station_to_join
= INVALID_STATION
;
1290 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1292 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1294 if (h_org
> _settings_game
.station
.station_spread
|| w_org
> _settings_game
.station
.station_spread
) return CMD_ERROR
;
1296 /* these values are those that will be stored in train_tile and station_platforms */
1297 TileArea
new_location(tile_org
, w_org
, h_org
);
1299 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1300 StationID est
= INVALID_STATION
;
1301 std::vector
<Train
*> affected_vehicles
;
1302 /* Clear the land below the station. */
1303 CommandCost cost
= CheckFlatLandRailStation(new_location
, flags
, axis
, &est
, rt
, affected_vehicles
, spec_class
, spec_index
, plat_len
, numtracks
);
1304 if (cost
.Failed()) return cost
;
1305 /* Add construction expenses. */
1306 cost
.AddCost((numtracks
* _price
[PR_BUILD_STATION_RAIL
] + _price
[PR_BUILD_STATION_RAIL_LENGTH
]) * plat_len
);
1307 cost
.AddCost(numtracks
* plat_len
* RailBuildCost(rt
));
1309 Station
*st
= nullptr;
1310 ret
= FindJoiningStation(est
, station_to_join
, adjacent
, new_location
, &st
);
1311 if (ret
.Failed()) return ret
;
1313 ret
= BuildStationPart(&st
, flags
, reuse
, new_location
, STATIONNAMING_RAIL
);
1314 if (ret
.Failed()) return ret
;
1316 if (st
!= nullptr && st
->train_station
.tile
!= INVALID_TILE
) {
1317 CommandCost ret
= CanExpandRailStation(st
, new_location
, axis
);
1318 if (ret
.Failed()) return ret
;
1321 /* Check if we can allocate a custom stationspec to this station */
1322 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
1323 int specindex
= AllocateSpecToStation(statspec
, st
, (flags
& DC_EXEC
) != 0);
1324 if (specindex
== -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS
);
1326 if (statspec
!= nullptr) {
1327 /* Perform NewStation checks */
1329 /* Check if the station size is permitted */
1330 if (HasBit(statspec
->disallowed_platforms
, min(numtracks
- 1, 7)) || HasBit(statspec
->disallowed_lengths
, min(plat_len
- 1, 7))) {
1334 /* Check if the station is buildable */
1335 if (HasBit(statspec
->callback_mask
, CBM_STATION_AVAIL
)) {
1336 uint16 cb_res
= GetStationCallback(CBID_STATION_AVAILABILITY
, 0, 0, statspec
, nullptr, INVALID_TILE
);
1337 if (cb_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(statspec
->grf_prop
.grffile
, CBID_STATION_AVAILABILITY
, cb_res
)) return CMD_ERROR
;
1341 if (flags
& DC_EXEC
) {
1342 TileIndexDiff tile_delta
;
1344 byte numtracks_orig
;
1347 st
->train_station
= new_location
;
1348 st
->AddFacility(FACIL_TRAIN
, new_location
.tile
);
1350 st
->rect
.BeforeAddRect(tile_org
, w_org
, h_org
, StationRect::ADD_TRY
);
1352 if (statspec
!= nullptr) {
1353 /* Include this station spec's animation trigger bitmask
1354 * in the station's cached copy. */
1355 st
->cached_anim_triggers
|= statspec
->animation
.triggers
;
1358 tile_delta
= (axis
== AXIS_X
? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1359 track
= AxisToTrack(axis
);
1361 layout_ptr
= AllocaM(byte
, numtracks
* plat_len
);
1362 GetStationLayout(layout_ptr
, numtracks
, plat_len
, statspec
);
1364 numtracks_orig
= numtracks
;
1366 Company
*c
= Company::Get(st
->owner
);
1367 TileIndex tile_track
= tile_org
;
1369 TileIndex tile
= tile_track
;
1372 byte layout
= *layout_ptr
++;
1373 if (IsRailStationTile(tile
) && HasStationReservation(tile
)) {
1374 /* Check for trains having a reservation for this tile. */
1375 Train
*v
= GetTrainForReservation(tile
, AxisToTrack(GetRailStationAxis(tile
)));
1377 affected_vehicles
.push_back(v
);
1378 FreeTrainReservation(v
);
1382 /* Railtype can change when overbuilding. */
1383 if (IsRailStationTile(tile
)) {
1384 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[GetRailType(tile
)]--;
1385 c
->infrastructure
.station
--;
1388 /* Remove animation if overbuilding */
1389 DeleteAnimatedTile(tile
);
1390 byte old_specindex
= HasStationTileRail(tile
) ? GetCustomStationSpecIndex(tile
) : 0;
1391 MakeRailStation(tile
, st
->owner
, st
->index
, axis
, layout
& ~1, rt
);
1392 /* Free the spec if we overbuild something */
1393 DeallocateSpecFromStation(st
, old_specindex
);
1395 SetCustomStationSpecIndex(tile
, specindex
);
1396 SetStationTileRandomBits(tile
, GB(Random(), 0, 4));
1397 SetAnimationFrame(tile
, 0);
1399 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[rt
]++;
1400 c
->infrastructure
.station
++;
1402 if (statspec
!= nullptr) {
1403 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1404 uint32 platinfo
= GetPlatformInfo(AXIS_X
, GetStationGfx(tile
), plat_len
, numtracks_orig
, plat_len
- w
, numtracks_orig
- numtracks
, false);
1406 /* As the station is not yet completely finished, the station does not yet exist. */
1407 uint16 callback
= GetStationCallback(CBID_STATION_TILE_LAYOUT
, platinfo
, 0, statspec
, nullptr, tile
);
1408 if (callback
!= CALLBACK_FAILED
) {
1410 SetStationGfx(tile
, (callback
& ~1) + axis
);
1412 ErrorUnknownCallbackResult(statspec
->grf_prop
.grffile
->grfid
, CBID_STATION_TILE_LAYOUT
, callback
);
1416 /* Trigger station animation -- after building? */
1417 TriggerStationAnimation(st
, tile
, SAT_BUILT
);
1422 AddTrackToSignalBuffer(tile_track
, track
, _current_company
);
1423 YapfNotifyTrackLayoutChange(tile_track
, track
);
1424 tile_track
+= tile_delta
^ TileDiffXY(1, 1); // perpendicular to tile_delta
1425 } while (--numtracks
);
1427 for (uint i
= 0; i
< affected_vehicles
.size(); ++i
) {
1428 /* Restore reservations of trains. */
1429 RestoreTrainReservation(affected_vehicles
[i
]);
1432 /* Check whether we need to expand the reservation of trains already on the station. */
1433 TileArea update_reservation_area
;
1434 if (axis
== AXIS_X
) {
1435 update_reservation_area
= TileArea(tile_org
, 1, numtracks_orig
);
1437 update_reservation_area
= TileArea(tile_org
, numtracks_orig
, 1);
1440 TILE_AREA_LOOP(tile
, update_reservation_area
) {
1441 /* Don't even try to make eye candy parts reserved. */
1442 if (IsStationTileBlocked(tile
)) continue;
1444 DiagDirection dir
= AxisToDiagDir(axis
);
1445 TileIndexDiff tile_offset
= TileOffsByDiagDir(dir
);
1446 TileIndex platform_begin
= tile
;
1447 TileIndex platform_end
= tile
;
1449 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1450 for (TileIndex next_tile
= platform_begin
- tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_begin
); next_tile
-= tile_offset
) {
1451 platform_begin
= next_tile
;
1453 for (TileIndex next_tile
= platform_end
+ tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_end
); next_tile
+= tile_offset
) {
1454 platform_end
= next_tile
;
1457 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1458 bool reservation
= false;
1459 for (TileIndex t
= platform_begin
; !reservation
&& t
<= platform_end
; t
+= tile_offset
) {
1460 reservation
= HasStationReservation(t
);
1464 SetRailStationPlatformReservation(platform_begin
, dir
, true);
1468 st
->MarkTilesDirty(false);
1469 st
->AfterStationTileSetChange(true, STATION_RAIL
);
1475 static TileArea
MakeStationAreaSmaller(BaseStation
*st
, TileArea ta
, bool (*func
)(BaseStation
*, TileIndex
))
1480 if (ta
.w
!= 0 && ta
.h
!= 0) {
1481 /* check the left side, x = constant, y changes */
1482 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(0, i
));) {
1483 /* the left side is unused? */
1485 ta
.tile
+= TileDiffXY(1, 0);
1491 /* check the right side, x = constant, y changes */
1492 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(ta
.w
- 1, i
));) {
1493 /* the right side is unused? */
1500 /* check the upper side, y = constant, x changes */
1501 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(i
, 0));) {
1502 /* the left side is unused? */
1504 ta
.tile
+= TileDiffXY(0, 1);
1510 /* check the lower side, y = constant, x changes */
1511 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(i
, ta
.h
- 1));) {
1512 /* the left side is unused? */
1525 static bool TileBelongsToRailStation(BaseStation
*st
, TileIndex tile
)
1527 return st
->TileBelongsToRailStation(tile
);
1530 static void MakeRailStationAreaSmaller(BaseStation
*st
)
1532 st
->train_station
= MakeStationAreaSmaller(st
, st
->train_station
, TileBelongsToRailStation
);
1535 static bool TileBelongsToShipStation(BaseStation
*st
, TileIndex tile
)
1537 return IsDockTile(tile
) && GetStationIndex(tile
) == st
->index
;
1540 static void MakeShipStationAreaSmaller(Station
*st
)
1542 st
->ship_station
= MakeStationAreaSmaller(st
, st
->ship_station
, TileBelongsToShipStation
);
1543 UpdateStationDockingTiles(st
);
1547 * Remove a number of tiles from any rail station within the area.
1548 * @param ta the area to clear station tile from.
1549 * @param affected_stations the stations affected.
1550 * @param flags the command flags.
1551 * @param removal_cost the cost for removing the tile, including the rail.
1552 * @param keep_rail whether to keep the rail of the station.
1553 * @tparam T the type of station to remove.
1554 * @return the number of cleared tiles or an error.
1557 CommandCost
RemoveFromRailBaseStation(TileArea ta
, std::vector
<T
*> &affected_stations
, DoCommandFlag flags
, Money removal_cost
, bool keep_rail
)
1559 /* Count of the number of tiles removed */
1561 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
1562 /* Accumulator for the errors seen during clearing. If no errors happen,
1563 * and the quantity is 0 there is no station. Otherwise it will be one
1564 * of the other error that got accumulated. */
1567 /* Do the action for every tile into the area */
1568 TILE_AREA_LOOP(tile
, ta
) {
1569 /* Make sure the specified tile is a rail station */
1570 if (!HasStationTileRail(tile
)) continue;
1572 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1573 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1575 if (ret
.Failed()) continue;
1577 /* Check ownership of station */
1578 T
*st
= T::GetByTile(tile
);
1579 if (st
== nullptr) continue;
1581 if (_current_company
!= OWNER_WATER
) {
1582 CommandCost ret
= CheckOwnership(st
->owner
);
1584 if (ret
.Failed()) continue;
1587 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1590 if (keep_rail
|| IsStationTileBlocked(tile
)) {
1591 /* Don't refund the 'steel' of the track when we keep the
1592 * rail, or when the tile didn't have any rail at all. */
1593 total_cost
.AddCost(-_price
[PR_CLEAR_RAIL
]);
1596 if (flags
& DC_EXEC
) {
1597 /* read variables before the station tile is removed */
1598 uint specindex
= GetCustomStationSpecIndex(tile
);
1599 Track track
= GetRailStationTrack(tile
);
1600 Owner owner
= GetTileOwner(tile
);
1601 RailType rt
= GetRailType(tile
);
1604 if (HasStationReservation(tile
)) {
1605 v
= GetTrainForReservation(tile
, track
);
1606 if (v
!= nullptr) FreeTrainReservation(v
);
1609 bool build_rail
= keep_rail
&& !IsStationTileBlocked(tile
);
1610 if (!build_rail
&& !IsStationTileBlocked(tile
)) Company::Get(owner
)->infrastructure
.rail
[rt
]--;
1612 DoClearSquare(tile
);
1613 DeleteNewGRFInspectWindow(GSF_STATIONS
, tile
);
1614 if (build_rail
) MakeRailNormal(tile
, owner
, TrackToTrackBits(track
), rt
);
1615 Company::Get(owner
)->infrastructure
.station
--;
1616 DirtyCompanyInfrastructureWindows(owner
);
1618 st
->rect
.AfterRemoveTile(st
, tile
);
1619 AddTrackToSignalBuffer(tile
, track
, owner
);
1620 YapfNotifyTrackLayoutChange(tile
, track
);
1622 DeallocateSpecFromStation(st
, specindex
);
1624 include(affected_stations
, st
);
1626 if (v
!= nullptr) RestoreTrainReservation(v
);
1630 if (quantity
== 0) return error
.Failed() ? error
: CommandCost(STR_ERROR_THERE_IS_NO_STATION
);
1632 for (T
*st
: affected_stations
) {
1634 /* now we need to make the "spanned" area of the railway station smaller
1635 * if we deleted something at the edges.
1636 * we also need to adjust train_tile. */
1637 MakeRailStationAreaSmaller(st
);
1638 UpdateStationSignCoord(st
);
1640 /* if we deleted the whole station, delete the train facility. */
1641 if (st
->train_station
.tile
== INVALID_TILE
) {
1642 st
->facilities
&= ~FACIL_TRAIN
;
1643 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1644 st
->UpdateVirtCoord();
1645 DeleteStationIfEmpty(st
);
1649 total_cost
.AddCost(quantity
* removal_cost
);
1654 * Remove a single tile from a rail station.
1655 * This allows for custom-built station with holes and weird layouts
1656 * @param start tile of station piece to remove
1657 * @param flags operation to perform
1658 * @param p1 start_tile
1659 * @param p2 various bitstuffed elements
1660 * - p2 = bit 0 - if set keep the rail
1661 * @param text unused
1662 * @return the cost of this operation or an error
1664 CommandCost
CmdRemoveFromRailStation(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1666 TileIndex end
= p1
== 0 ? start
: p1
;
1667 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1669 TileArea
ta(start
, end
);
1670 std::vector
<Station
*> affected_stations
;
1672 CommandCost ret
= RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_STATION_RAIL
], HasBit(p2
, 0));
1673 if (ret
.Failed()) return ret
;
1675 /* Do all station specific functions here. */
1676 for (Station
*st
: affected_stations
) {
1678 if (st
->train_station
.tile
== INVALID_TILE
) SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1679 st
->MarkTilesDirty(false);
1680 st
->RecomputeCatchment();
1683 /* Now apply the rail cost to the number that we deleted */
1688 * Remove a single tile from a waypoint.
1689 * This allows for custom-built waypoint with holes and weird layouts
1690 * @param start tile of waypoint piece to remove
1691 * @param flags operation to perform
1692 * @param p1 start_tile
1693 * @param p2 various bitstuffed elements
1694 * - p2 = bit 0 - if set keep the rail
1695 * @param text unused
1696 * @return the cost of this operation or an error
1698 CommandCost
CmdRemoveFromRailWaypoint(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1700 TileIndex end
= p1
== 0 ? start
: p1
;
1701 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1703 TileArea
ta(start
, end
);
1704 std::vector
<Waypoint
*> affected_stations
;
1706 return RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
], HasBit(p2
, 0));
1711 * Remove a rail station/waypoint
1712 * @param st The station/waypoint to remove the rail part from
1713 * @param flags operation to perform
1714 * @param removal_cost the cost for removing a tile
1715 * @tparam T the type of station to remove
1716 * @return cost or failure of operation
1719 CommandCost
RemoveRailStation(T
*st
, DoCommandFlag flags
, Money removal_cost
)
1721 /* Current company owns the station? */
1722 if (_current_company
!= OWNER_WATER
) {
1723 CommandCost ret
= CheckOwnership(st
->owner
);
1724 if (ret
.Failed()) return ret
;
1727 /* determine width and height of platforms */
1728 TileArea ta
= st
->train_station
;
1730 assert(ta
.w
!= 0 && ta
.h
!= 0);
1732 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1733 /* clear all areas of the station */
1734 TILE_AREA_LOOP(tile
, ta
) {
1735 /* only remove tiles that are actually train station tiles */
1736 if (st
->TileBelongsToRailStation(tile
)) {
1737 std::vector
<T
*> affected_stations
; // dummy
1738 CommandCost ret
= RemoveFromRailBaseStation(TileArea(tile
, 1, 1), affected_stations
, flags
, removal_cost
, false);
1739 if (ret
.Failed()) return ret
;
1748 * Remove a rail station
1749 * @param tile Tile of the station.
1750 * @param flags operation to perform
1751 * @return cost or failure of operation
1753 static CommandCost
RemoveRailStation(TileIndex tile
, DoCommandFlag flags
)
1755 /* if there is flooding, remove platforms tile by tile */
1756 if (_current_company
== OWNER_WATER
) {
1757 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_STATION
);
1760 Station
*st
= Station::GetByTile(tile
);
1761 CommandCost cost
= RemoveRailStation(st
, flags
, _price
[PR_CLEAR_STATION_RAIL
]);
1763 if (flags
& DC_EXEC
) st
->RecomputeCatchment();
1769 * Remove a rail waypoint
1770 * @param tile Tile of the waypoint.
1771 * @param flags operation to perform
1772 * @return cost or failure of operation
1774 static CommandCost
RemoveRailWaypoint(TileIndex tile
, DoCommandFlag flags
)
1776 /* if there is flooding, remove waypoints tile by tile */
1777 if (_current_company
== OWNER_WATER
) {
1778 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_WAYPOINT
);
1781 return RemoveRailStation(Waypoint::GetByTile(tile
), flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
]);
1786 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1787 * @param st The Station to do the whole procedure for
1788 * @return a pointer to where to link a new RoadStop*
1790 static RoadStop
**FindRoadStopSpot(bool truck_station
, Station
*st
)
1792 RoadStop
**primary_stop
= (truck_station
) ? &st
->truck_stops
: &st
->bus_stops
;
1794 if (*primary_stop
== nullptr) {
1795 /* we have no roadstop of the type yet, so write a "primary stop" */
1796 return primary_stop
;
1798 /* there are stops already, so append to the end of the list */
1799 RoadStop
*stop
= *primary_stop
;
1800 while (stop
->next
!= nullptr) stop
= stop
->next
;
1805 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
);
1808 * Find a nearby station that joins this road stop.
1809 * @param existing_stop an existing road stop we build over
1810 * @param station_to_join the station to join to
1811 * @param adjacent whether adjacent stations are allowed
1812 * @param ta the area of the newly build station
1813 * @param st 'return' pointer for the found station
1814 * @return command cost with the error or 'okay'
1816 static CommandCost
FindJoiningRoadStop(StationID existing_stop
, StationID station_to_join
, bool adjacent
, TileArea ta
, Station
**st
)
1818 return FindJoiningBaseStation
<Station
, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST
>(existing_stop
, station_to_join
, adjacent
, ta
, st
);
1822 * Build a bus or truck stop.
1823 * @param tile Northernmost tile of the stop.
1824 * @param flags Operation to perform.
1825 * @param p1 bit 0..7: Width of the road stop.
1826 * bit 8..15: Length of the road stop.
1827 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1828 * bit 1: 0 For normal stops, 1 for drive-through.
1829 * bit 2: Allow stations directly adjacent to other stations.
1830 * bit 3..4: Entrance direction (#DiagDirection) for normal stops.
1831 * bit 3: #Axis of the road for drive-through stops.
1832 * bit 5..10: The roadtype.
1833 * bit 16..31: Station ID to join (NEW_STATION if build new one).
1834 * @param text Unused.
1835 * @return The cost of this operation or an error.
1837 CommandCost
CmdBuildRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1839 bool type
= HasBit(p2
, 0);
1840 bool is_drive_through
= HasBit(p2
, 1);
1841 RoadType rt
= Extract
<RoadType
, 5, 6>(p2
);
1842 if (!ValParamRoadType(rt
)) return CMD_ERROR
;
1843 StationID station_to_join
= GB(p2
, 16, 16);
1844 bool reuse
= (station_to_join
!= NEW_STATION
);
1845 if (!reuse
) station_to_join
= INVALID_STATION
;
1846 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1848 uint8 width
= (uint8
)GB(p1
, 0, 8);
1849 uint8 length
= (uint8
)GB(p1
, 8, 8);
1851 /* Check if the requested road stop is too big */
1852 if (width
> _settings_game
.station
.station_spread
|| length
> _settings_game
.station
.station_spread
) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1853 /* Check for incorrect width / length. */
1854 if (width
== 0 || length
== 0) return CMD_ERROR
;
1855 /* Check if the first tile and the last tile are valid */
1856 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, length
- 1) == INVALID_TILE
) return CMD_ERROR
;
1858 TileArea
roadstop_area(tile
, width
, length
);
1860 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1862 /* Trams only have drive through stops */
1863 if (!is_drive_through
&& RoadTypeIsTram(rt
)) return CMD_ERROR
;
1867 if (is_drive_through
) {
1868 /* By definition axis is valid, due to there being 2 axes and reading 1 bit. */
1869 axis
= Extract
<Axis
, 3, 1>(p2
);
1870 ddir
= AxisToDiagDir(axis
);
1872 /* By definition ddir is valid, due to there being 4 diagonal directions and reading 2 bits. */
1873 ddir
= Extract
<DiagDirection
, 3, 2>(p2
);
1874 axis
= DiagDirToAxis(ddir
);
1877 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
1878 if (ret
.Failed()) return ret
;
1880 /* Total road stop cost. */
1881 CommandCost
cost(EXPENSES_CONSTRUCTION
, roadstop_area
.w
* roadstop_area
.h
* _price
[type
? PR_BUILD_STATION_TRUCK
: PR_BUILD_STATION_BUS
]);
1882 StationID est
= INVALID_STATION
;
1883 ret
= CheckFlatLandRoadStop(roadstop_area
, flags
, is_drive_through
? 5 << axis
: 1 << ddir
, is_drive_through
, type
, axis
, &est
, rt
);
1884 if (ret
.Failed()) return ret
;
1887 Station
*st
= nullptr;
1888 ret
= FindJoiningRoadStop(est
, station_to_join
, HasBit(p2
, 2), roadstop_area
, &st
);
1889 if (ret
.Failed()) return ret
;
1891 /* Check if this number of road stops can be allocated. */
1892 if (!RoadStop::CanAllocateItem(roadstop_area
.w
* roadstop_area
.h
)) return_cmd_error(type
? STR_ERROR_TOO_MANY_TRUCK_STOPS
: STR_ERROR_TOO_MANY_BUS_STOPS
);
1894 ret
= BuildStationPart(&st
, flags
, reuse
, roadstop_area
, STATIONNAMING_ROAD
);
1895 if (ret
.Failed()) return ret
;
1897 if (flags
& DC_EXEC
) {
1898 /* Check every tile in the area. */
1899 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
1900 /* Get existing road types and owners before any tile clearing */
1901 RoadType road_rt
= MayHaveRoad(cur_tile
) ? GetRoadType(cur_tile
, RTT_ROAD
) : INVALID_ROADTYPE
;
1902 RoadType tram_rt
= MayHaveRoad(cur_tile
) ? GetRoadType(cur_tile
, RTT_TRAM
) : INVALID_ROADTYPE
;
1903 Owner road_owner
= road_rt
!= INVALID_ROADTYPE
? GetRoadOwner(cur_tile
, RTT_ROAD
) : _current_company
;
1904 Owner tram_owner
= tram_rt
!= INVALID_ROADTYPE
? GetRoadOwner(cur_tile
, RTT_TRAM
) : _current_company
;
1906 if (IsTileType(cur_tile
, MP_STATION
) && IsRoadStop(cur_tile
)) {
1907 RemoveRoadStop(cur_tile
, flags
);
1910 RoadStop
*road_stop
= new RoadStop(cur_tile
);
1911 /* Insert into linked list of RoadStops. */
1912 RoadStop
**currstop
= FindRoadStopSpot(type
, st
);
1913 *currstop
= road_stop
;
1916 st
->truck_station
.Add(cur_tile
);
1918 st
->bus_station
.Add(cur_tile
);
1921 /* Initialize an empty station. */
1922 st
->AddFacility((type
) ? FACIL_TRUCK_STOP
: FACIL_BUS_STOP
, cur_tile
);
1924 st
->rect
.BeforeAddTile(cur_tile
, StationRect::ADD_TRY
);
1926 RoadStopType rs_type
= type
? ROADSTOP_TRUCK
: ROADSTOP_BUS
;
1927 if (is_drive_through
) {
1928 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
1930 if (IsNormalRoadTile(cur_tile
)) {
1931 UpdateCompanyRoadInfrastructure(road_rt
, road_owner
, -(int)CountBits(GetRoadBits(cur_tile
, RTT_ROAD
)));
1932 UpdateCompanyRoadInfrastructure(tram_rt
, tram_owner
, -(int)CountBits(GetRoadBits(cur_tile
, RTT_TRAM
)));
1935 if (road_rt
== INVALID_ROADTYPE
&& RoadTypeIsRoad(rt
)) road_rt
= rt
;
1936 if (tram_rt
== INVALID_ROADTYPE
&& RoadTypeIsTram(rt
)) tram_rt
= rt
;
1938 UpdateCompanyRoadInfrastructure(road_rt
, road_owner
, 2);
1939 UpdateCompanyRoadInfrastructure(tram_rt
, tram_owner
, 2);
1941 MakeDriveThroughRoadStop(cur_tile
, st
->owner
, road_owner
, tram_owner
, st
->index
, rs_type
, road_rt
, tram_rt
, axis
);
1942 road_stop
->MakeDriveThrough();
1944 if (road_rt
== INVALID_ROADTYPE
&& RoadTypeIsRoad(rt
)) road_rt
= rt
;
1945 if (tram_rt
== INVALID_ROADTYPE
&& RoadTypeIsTram(rt
)) tram_rt
= rt
;
1946 /* Non-drive-through stop never overbuild and always count as two road bits. */
1947 Company::Get(st
->owner
)->infrastructure
.road
[rt
] += 2;
1948 MakeRoadStop(cur_tile
, st
->owner
, st
->index
, rs_type
, road_rt
, tram_rt
, ddir
);
1950 Company::Get(st
->owner
)->infrastructure
.station
++;
1952 MarkTileDirtyByTile(cur_tile
);
1956 if (st
!= nullptr) {
1957 st
->AfterStationTileSetChange(true, type
? STATION_TRUCK
: STATION_BUS
);
1963 static Vehicle
*ClearRoadStopStatusEnum(Vehicle
*v
, void *)
1965 if (v
->type
== VEH_ROAD
) {
1966 /* Okay... we are a road vehicle on a drive through road stop.
1967 * But that road stop has just been removed, so we need to make
1968 * sure we are in a valid state... however, vehicles can also
1969 * turn on road stop tiles, so only clear the 'road stop' state
1970 * bits and only when the state was 'in road stop', otherwise
1971 * we'll end up clearing the turn around bits. */
1972 RoadVehicle
*rv
= RoadVehicle::From(v
);
1973 if (HasBit(rv
->state
, RVS_IN_DT_ROAD_STOP
)) rv
->state
&= RVSB_ROAD_STOP_TRACKDIR_MASK
;
1981 * Remove a bus station/truck stop
1982 * @param tile TileIndex been queried
1983 * @param flags operation to perform
1984 * @return cost or failure of operation
1986 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
)
1988 Station
*st
= Station::GetByTile(tile
);
1990 if (_current_company
!= OWNER_WATER
) {
1991 CommandCost ret
= CheckOwnership(st
->owner
);
1992 if (ret
.Failed()) return ret
;
1995 bool is_truck
= IsTruckStop(tile
);
1997 RoadStop
**primary_stop
;
1999 if (is_truck
) { // truck stop
2000 primary_stop
= &st
->truck_stops
;
2001 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_TRUCK
);
2003 primary_stop
= &st
->bus_stops
;
2004 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_BUS
);
2007 assert(cur_stop
!= nullptr);
2009 /* don't do the check for drive-through road stops when company bankrupts */
2010 if (IsDriveThroughStopTile(tile
) && (flags
& DC_BANKRUPT
)) {
2011 /* remove the 'going through road stop' status from all vehicles on that tile */
2012 if (flags
& DC_EXEC
) FindVehicleOnPos(tile
, nullptr, &ClearRoadStopStatusEnum
);
2014 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
2015 if (ret
.Failed()) return ret
;
2018 if (flags
& DC_EXEC
) {
2019 if (*primary_stop
== cur_stop
) {
2020 /* removed the first stop in the list */
2021 *primary_stop
= cur_stop
->next
;
2022 /* removed the only stop? */
2023 if (*primary_stop
== nullptr) {
2024 st
->facilities
&= (is_truck
? ~FACIL_TRUCK_STOP
: ~FACIL_BUS_STOP
);
2027 /* tell the predecessor in the list to skip this stop */
2028 RoadStop
*pred
= *primary_stop
;
2029 while (pred
->next
!= cur_stop
) pred
= pred
->next
;
2030 pred
->next
= cur_stop
->next
;
2033 /* Update company infrastructure counts. */
2034 FOR_ALL_ROADTRAMTYPES(rtt
) {
2035 RoadType rt
= GetRoadType(tile
, rtt
);
2036 UpdateCompanyRoadInfrastructure(rt
, GetRoadOwner(tile
, rtt
), -2);
2039 Company::Get(st
->owner
)->infrastructure
.station
--;
2040 DirtyCompanyInfrastructureWindows(st
->owner
);
2042 if (IsDriveThroughStopTile(tile
)) {
2043 /* Clears the tile for us */
2044 cur_stop
->ClearDriveThrough();
2046 DoClearSquare(tile
);
2051 /* Make sure no vehicle is going to the old roadstop */
2052 for (RoadVehicle
*v
: RoadVehicle::Iterate()) {
2053 if (v
->First() == v
&& v
->current_order
.IsType(OT_GOTO_STATION
) &&
2054 v
->dest_tile
== tile
) {
2055 v
->SetDestTile(v
->GetOrderStationLocation(st
->index
));
2059 st
->rect
.AfterRemoveTile(st
, tile
);
2061 st
->AfterStationTileSetChange(false, is_truck
? STATION_TRUCK
: STATION_BUS
);
2063 /* Update the tile area of the truck/bus stop */
2065 st
->truck_station
.Clear();
2066 for (const RoadStop
*rs
= st
->truck_stops
; rs
!= nullptr; rs
= rs
->next
) st
->truck_station
.Add(rs
->xy
);
2068 st
->bus_station
.Clear();
2069 for (const RoadStop
*rs
= st
->bus_stops
; rs
!= nullptr; rs
= rs
->next
) st
->bus_station
.Add(rs
->xy
);
2073 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[is_truck
? PR_CLEAR_STATION_TRUCK
: PR_CLEAR_STATION_BUS
]);
2077 * Remove bus or truck stops.
2078 * @param tile Northernmost tile of the removal area.
2079 * @param flags Operation to perform.
2080 * @param p1 bit 0..7: Width of the removal area.
2081 * bit 8..15: Height of the removal area.
2082 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
2083 * @param p2 bit 1: 0 to keep roads of all drive-through stops, 1 to remove them.
2084 * @param text Unused.
2085 * @return The cost of this operation or an error.
2087 CommandCost
CmdRemoveRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2089 uint8 width
= (uint8
)GB(p1
, 0, 8);
2090 uint8 height
= (uint8
)GB(p1
, 8, 8);
2091 bool keep_drive_through_roads
= !HasBit(p2
, 1);
2093 /* Check for incorrect width / height. */
2094 if (width
== 0 || height
== 0) return CMD_ERROR
;
2095 /* Check if the first tile and the last tile are valid */
2096 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, height
- 1) == INVALID_TILE
) return CMD_ERROR
;
2097 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2098 if (!keep_drive_through_roads
&& (flags
& DC_BANKRUPT
)) return CMD_ERROR
;
2100 TileArea
roadstop_area(tile
, width
, height
);
2102 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2103 CommandCost
last_error(STR_ERROR_THERE_IS_NO_STATION
);
2104 bool had_success
= false;
2106 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
2107 /* Make sure the specified tile is a road stop of the correct type */
2108 if (!IsTileType(cur_tile
, MP_STATION
) || !IsRoadStop(cur_tile
) || (uint32
)GetRoadStopType(cur_tile
) != GB(p2
, 0, 1)) continue;
2110 /* Save information on to-be-restored roads before the stop is removed. */
2111 RoadBits road_bits
= ROAD_NONE
;
2112 RoadType road_type
[] = { INVALID_ROADTYPE
, INVALID_ROADTYPE
};
2113 Owner road_owner
[] = { OWNER_NONE
, OWNER_NONE
};
2114 if (IsDriveThroughStopTile(cur_tile
)) {
2115 FOR_ALL_ROADTRAMTYPES(rtt
) {
2116 road_type
[rtt
] = GetRoadType(cur_tile
, rtt
);
2117 if (road_type
[rtt
] == INVALID_ROADTYPE
) continue;
2118 road_owner
[rtt
] = GetRoadOwner(cur_tile
, rtt
);
2119 /* If we don't want to preserve our roads then restore only roads of others. */
2120 if (!keep_drive_through_roads
&& road_owner
[rtt
] == _current_company
) road_type
[rtt
] = INVALID_ROADTYPE
;
2122 road_bits
= AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile
)));
2125 CommandCost ret
= RemoveRoadStop(cur_tile
, flags
);
2133 /* Restore roads. */
2134 if ((flags
& DC_EXEC
) && (road_type
[RTT_ROAD
] != INVALID_ROADTYPE
|| road_type
[RTT_TRAM
] != INVALID_ROADTYPE
)) {
2135 MakeRoadNormal(cur_tile
, road_bits
, road_type
[RTT_ROAD
], road_type
[RTT_TRAM
], ClosestTownFromTile(cur_tile
, UINT_MAX
)->index
,
2136 road_owner
[RTT_ROAD
], road_owner
[RTT_TRAM
]);
2138 /* Update company infrastructure counts. */
2139 int count
= CountBits(road_bits
);
2140 UpdateCompanyRoadInfrastructure(road_type
[RTT_ROAD
], road_owner
[RTT_ROAD
], count
);
2141 UpdateCompanyRoadInfrastructure(road_type
[RTT_TRAM
], road_owner
[RTT_TRAM
], count
);
2145 return had_success
? cost
: last_error
;
2149 * Get a possible noise reduction factor based on distance from town center.
2150 * The further you get, the less noise you generate.
2151 * So all those folks at city council can now happily slee... work in their offices
2152 * @param as airport information
2153 * @param distance minimum distance between town and airport
2154 * @return the noise that will be generated, according to distance
2156 uint8
GetAirportNoiseLevelForDistance(const AirportSpec
*as
, uint distance
)
2158 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2159 * So no need to go any further*/
2160 if (as
->noise_level
< 2) return as
->noise_level
;
2162 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2163 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2164 * Basically, it says that the less tolerant a town is, the bigger the distance before
2165 * an actual decrease can be granted */
2166 uint8 town_tolerance_distance
= 8 + (_settings_game
.difficulty
.town_council_tolerance
* 4);
2168 /* now, we want to have the distance segmented using the distance judged bareable by town
2169 * This will give us the coefficient of reduction the distance provides. */
2170 uint noise_reduction
= distance
/ town_tolerance_distance
;
2172 /* If the noise reduction equals the airport noise itself, don't give it for free.
2173 * Otherwise, simply reduce the airport's level. */
2174 return noise_reduction
>= as
->noise_level
? 1 : as
->noise_level
- noise_reduction
;
2178 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2179 * If two towns have the same distance, town with lower index is returned.
2180 * @param as airport's description
2181 * @param it An iterator over all airport tiles
2182 * @param[out] mindist Minimum distance to town
2183 * @return nearest town to airport
2185 Town
*AirportGetNearestTown(const AirportSpec
*as
, const TileIterator
&it
, uint
&mindist
)
2187 assert(Town::GetNumItems() > 0);
2189 Town
*nearest
= nullptr;
2191 uint perimeter_min_x
= TileX(it
);
2192 uint perimeter_min_y
= TileY(it
);
2193 uint perimeter_max_x
= perimeter_min_x
+ as
->size_x
- 1;
2194 uint perimeter_max_y
= perimeter_min_y
+ as
->size_y
- 1;
2196 mindist
= UINT_MAX
- 1; // prevent overflow
2198 std::unique_ptr
<TileIterator
> copy(it
.Clone());
2199 for (TileIndex cur_tile
= *copy
; cur_tile
!= INVALID_TILE
; cur_tile
= ++*copy
) {
2200 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
) {
2201 Town
*t
= CalcClosestTownFromTile(cur_tile
, mindist
+ 1);
2202 if (t
== nullptr) continue;
2204 uint dist
= DistanceManhattan(t
->xy
, cur_tile
);
2205 if (dist
== mindist
&& t
->index
< nearest
->index
) nearest
= t
;
2206 if (dist
< mindist
) {
2217 /** Recalculate the noise generated by the airports of each town */
2218 void UpdateAirportsNoise()
2220 for (Town
*t
: Town::Iterate()) t
->noise_reached
= 0;
2222 for (const Station
*st
: Station::Iterate()) {
2223 if (st
->airport
.tile
!= INVALID_TILE
&& st
->airport
.type
!= AT_OILRIG
) {
2224 const AirportSpec
*as
= st
->airport
.GetSpec();
2225 AirportTileIterator
it(st
);
2227 Town
*nearest
= AirportGetNearestTown(as
, it
, dist
);
2228 nearest
->noise_reached
+= GetAirportNoiseLevelForDistance(as
, dist
);
2235 * @param tile tile where airport will be built
2236 * @param flags operation to perform
2238 * - p1 = (bit 0- 7) - airport type, @see airport.h
2239 * - p1 = (bit 8-15) - airport layout
2240 * @param p2 various bitstuffed elements
2241 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2242 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2243 * @param text unused
2244 * @return the cost of this operation or an error
2246 CommandCost
CmdBuildAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2248 StationID station_to_join
= GB(p2
, 16, 16);
2249 bool reuse
= (station_to_join
!= NEW_STATION
);
2250 if (!reuse
) station_to_join
= INVALID_STATION
;
2251 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2252 byte airport_type
= GB(p1
, 0, 8);
2253 byte layout
= GB(p1
, 8, 8);
2255 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2257 if (airport_type
>= NUM_AIRPORTS
) return CMD_ERROR
;
2259 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2260 if (ret
.Failed()) return ret
;
2262 /* Check if a valid, buildable airport was chosen for construction */
2263 const AirportSpec
*as
= AirportSpec::Get(airport_type
);
2264 if (!as
->IsAvailable() || layout
>= as
->num_table
) return CMD_ERROR
;
2265 if (!as
->IsWithinMapBounds(layout
, tile
)) return CMD_ERROR
;
2267 Direction rotation
= as
->rotation
[layout
];
2270 if (rotation
== DIR_E
|| rotation
== DIR_W
) Swap(w
, h
);
2271 TileArea airport_area
= TileArea(tile
, w
, h
);
2273 if (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
) {
2274 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
2277 AirportTileTableIterator
iter(as
->table
[layout
], tile
);
2278 CommandCost cost
= CheckFlatLandAirport(iter
, flags
);
2279 if (cost
.Failed()) return cost
;
2281 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2283 Town
*nearest
= AirportGetNearestTown(as
, iter
, dist
);
2284 uint newnoise_level
= GetAirportNoiseLevelForDistance(as
, dist
);
2286 /* Check if local auth would allow a new airport */
2287 StringID authority_refuse_message
= STR_NULL
;
2288 Town
*authority_refuse_town
= nullptr;
2290 if (_settings_game
.economy
.station_noise_level
) {
2291 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2292 if ((nearest
->noise_reached
+ newnoise_level
) > nearest
->MaxTownNoise()) {
2293 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE
;
2294 authority_refuse_town
= nearest
;
2297 Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
2299 for (const Station
*st
: Station::Iterate()) {
2300 if (st
->town
== t
&& (st
->facilities
& FACIL_AIRPORT
) && st
->airport
.type
!= AT_OILRIG
) num
++;
2303 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT
;
2304 authority_refuse_town
= t
;
2308 if (authority_refuse_message
!= STR_NULL
) {
2309 SetDParam(0, authority_refuse_town
->index
);
2310 return_cmd_error(authority_refuse_message
);
2313 Station
*st
= nullptr;
2314 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, HasBit(p2
, 0), airport_area
, &st
);
2315 if (ret
.Failed()) return ret
;
2318 if (st
== nullptr && distant_join
) st
= Station::GetIfValid(station_to_join
);
2320 ret
= BuildStationPart(&st
, flags
, reuse
, airport_area
, (GetAirport(airport_type
)->flags
& AirportFTAClass::AIRPLANES
) ? STATIONNAMING_AIRPORT
: STATIONNAMING_HELIPORT
);
2321 if (ret
.Failed()) return ret
;
2323 if (st
!= nullptr && st
->airport
.tile
!= INVALID_TILE
) {
2324 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT
);
2327 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2328 cost
.AddCost(_price
[PR_BUILD_STATION_AIRPORT
]);
2331 if (flags
& DC_EXEC
) {
2332 /* Always add the noise, so there will be no need to recalculate when option toggles */
2333 nearest
->noise_reached
+= newnoise_level
;
2335 st
->AddFacility(FACIL_AIRPORT
, tile
);
2336 st
->airport
.type
= airport_type
;
2337 st
->airport
.layout
= layout
;
2338 st
->airport
.flags
= 0;
2339 st
->airport
.rotation
= rotation
;
2341 st
->rect
.BeforeAddRect(tile
, w
, h
, StationRect::ADD_TRY
);
2343 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2344 MakeAirport(iter
, st
->owner
, st
->index
, iter
.GetStationGfx(), WATER_CLASS_INVALID
);
2345 SetStationTileRandomBits(iter
, GB(Random(), 0, 4));
2346 st
->airport
.Add(iter
);
2348 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter
.GetStationGfx()))->animation
.status
!= ANIM_STATUS_NO_ANIMATION
) AddAnimatedTile(iter
);
2351 /* Only call the animation trigger after all tiles have been built */
2352 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2353 AirportTileAnimationTrigger(st
, iter
, AAT_BUILT
);
2356 UpdateAirplanesOnNewStation(st
);
2358 Company::Get(st
->owner
)->infrastructure
.airport
++;
2360 st
->AfterStationTileSetChange(true, STATION_AIRPORT
);
2361 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2363 if (_settings_game
.economy
.station_noise_level
) {
2364 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2373 * @param tile TileIndex been queried
2374 * @param flags operation to perform
2375 * @return cost or failure of operation
2377 static CommandCost
RemoveAirport(TileIndex tile
, DoCommandFlag flags
)
2379 Station
*st
= Station::GetByTile(tile
);
2381 if (_current_company
!= OWNER_WATER
) {
2382 CommandCost ret
= CheckOwnership(st
->owner
);
2383 if (ret
.Failed()) return ret
;
2386 tile
= st
->airport
.tile
;
2388 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2390 for (const Aircraft
*a
: Aircraft::Iterate()) {
2391 if (!a
->IsNormalAircraft()) continue;
2392 if (a
->targetairport
== st
->index
&& a
->state
!= FLYING
) {
2393 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY
);
2397 if (flags
& DC_EXEC
) {
2398 const AirportSpec
*as
= st
->airport
.GetSpec();
2399 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2400 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2401 * need of recalculation */
2402 AirportTileIterator
it(st
);
2404 Town
*nearest
= AirportGetNearestTown(as
, it
, dist
);
2405 nearest
->noise_reached
-= GetAirportNoiseLevelForDistance(as
, dist
);
2408 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2409 if (!st
->TileBelongsToAirport(tile_cur
)) continue;
2411 CommandCost ret
= EnsureNoVehicleOnGround(tile_cur
);
2412 if (ret
.Failed()) return ret
;
2414 cost
.AddCost(_price
[PR_CLEAR_STATION_AIRPORT
]);
2416 if (flags
& DC_EXEC
) {
2417 if (IsHangarTile(tile_cur
)) OrderBackup::Reset(tile_cur
, false);
2418 DeleteAnimatedTile(tile_cur
);
2419 DoClearSquare(tile_cur
);
2420 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
);
2424 if (flags
& DC_EXEC
) {
2425 /* Clear the persistent storage. */
2426 delete st
->airport
.psa
;
2428 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2430 WC_VEHICLE_DEPOT
, st
->airport
.GetHangarTile(i
)
2434 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2436 st
->airport
.Clear();
2437 st
->facilities
&= ~FACIL_AIRPORT
;
2439 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2441 if (_settings_game
.economy
.station_noise_level
) {
2442 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2445 Company::Get(st
->owner
)->infrastructure
.airport
--;
2447 st
->AfterStationTileSetChange(false, STATION_AIRPORT
);
2449 DeleteNewGRFInspectWindow(GSF_AIRPORTS
, st
->index
);
2456 * Open/close an airport to incoming aircraft.
2457 * @param tile Unused.
2458 * @param flags Operation to perform.
2459 * @param p1 Station ID of the airport.
2461 * @param text unused
2462 * @return the cost of this operation or an error
2464 CommandCost
CmdOpenCloseAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2466 if (!Station::IsValidID(p1
)) return CMD_ERROR
;
2467 Station
*st
= Station::Get(p1
);
2469 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->owner
== OWNER_NONE
) return CMD_ERROR
;
2471 CommandCost ret
= CheckOwnership(st
->owner
);
2472 if (ret
.Failed()) return ret
;
2474 if (flags
& DC_EXEC
) {
2475 st
->airport
.flags
^= AIRPORT_CLOSED_block
;
2476 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_CLOSE_AIRPORT
);
2478 return CommandCost();
2482 * Tests whether the company's vehicles have this station in orders
2483 * @param station station ID
2484 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2485 * @param company company ID
2487 bool HasStationInUse(StationID station
, bool include_company
, CompanyID company
)
2489 for (const Vehicle
*v
: Vehicle::Iterate()) {
2490 if ((v
->owner
== company
) == include_company
) {
2492 FOR_VEHICLE_ORDERS(v
, order
) {
2493 if ((order
->IsType(OT_GOTO_STATION
) || order
->IsType(OT_GOTO_WAYPOINT
)) && order
->GetDestination() == station
) {
2502 static const TileIndexDiffC _dock_tileoffs_chkaround
[] = {
2508 static const byte _dock_w_chk
[4] = { 2, 1, 2, 1 };
2509 static const byte _dock_h_chk
[4] = { 1, 2, 1, 2 };
2512 * Build a dock/haven.
2513 * @param tile tile where dock will be built
2514 * @param flags operation to perform
2515 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
2516 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
2517 * @param text unused
2518 * @return the cost of this operation or an error
2520 CommandCost
CmdBuildDock(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2522 StationID station_to_join
= GB(p2
, 16, 16);
2523 bool reuse
= (station_to_join
!= NEW_STATION
);
2524 if (!reuse
) station_to_join
= INVALID_STATION
;
2525 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2527 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2529 DiagDirection direction
= GetInclinedSlopeDirection(GetTileSlope(tile
));
2530 if (direction
== INVALID_DIAGDIR
) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2531 direction
= ReverseDiagDir(direction
);
2533 /* Docks cannot be placed on rapids */
2534 if (HasTileWaterGround(tile
)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2536 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2537 if (ret
.Failed()) return ret
;
2539 if (IsBridgeAbove(tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2541 ret
= DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2542 if (ret
.Failed()) return ret
;
2544 TileIndex tile_cur
= tile
+ TileOffsByDiagDir(direction
);
2546 if (!IsTileType(tile_cur
, MP_WATER
) || !IsTileFlat(tile_cur
)) {
2547 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2550 if (IsBridgeAbove(tile_cur
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2552 /* Get the water class of the water tile before it is cleared.*/
2553 WaterClass wc
= GetWaterClass(tile_cur
);
2555 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2556 if (ret
.Failed()) return ret
;
2558 tile_cur
+= TileOffsByDiagDir(direction
);
2559 if (!IsTileType(tile_cur
, MP_WATER
) || !IsTileFlat(tile_cur
)) {
2560 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2563 TileArea dock_area
= TileArea(tile
+ ToTileIndexDiff(_dock_tileoffs_chkaround
[direction
]),
2564 _dock_w_chk
[direction
], _dock_h_chk
[direction
]);
2567 Station
*st
= nullptr;
2568 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, HasBit(p1
, 0), dock_area
, &st
);
2569 if (ret
.Failed()) return ret
;
2572 if (st
== nullptr && distant_join
) st
= Station::GetIfValid(station_to_join
);
2574 ret
= BuildStationPart(&st
, flags
, reuse
, dock_area
, STATIONNAMING_DOCK
);
2575 if (ret
.Failed()) return ret
;
2577 if (flags
& DC_EXEC
) {
2578 st
->ship_station
.Add(tile
);
2579 st
->ship_station
.Add(tile
+ TileOffsByDiagDir(direction
));
2580 st
->AddFacility(FACIL_DOCK
, tile
);
2582 st
->rect
.BeforeAddRect(dock_area
.tile
, dock_area
.w
, dock_area
.h
, StationRect::ADD_TRY
);
2584 /* If the water part of the dock is on a canal, update infrastructure counts.
2585 * This is needed as we've unconditionally cleared that tile before. */
2586 if (wc
== WATER_CLASS_CANAL
) {
2587 Company::Get(st
->owner
)->infrastructure
.water
++;
2589 Company::Get(st
->owner
)->infrastructure
.station
+= 2;
2591 MakeDock(tile
, st
->owner
, st
->index
, direction
, wc
);
2592 UpdateStationDockingTiles(st
);
2594 st
->AfterStationTileSetChange(true, STATION_DOCK
);
2597 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_STATION_DOCK
]);
2600 void RemoveDockingTile(TileIndex t
)
2602 for (DiagDirection d
= DIAGDIR_BEGIN
; d
!= DIAGDIR_END
; d
++) {
2603 TileIndex tile
= t
+ TileOffsByDiagDir(d
);
2604 if (!IsValidTile(tile
)) continue;
2606 if (IsTileType(tile
, MP_STATION
)) {
2607 UpdateStationDockingTiles(Station::GetByTile(tile
));
2608 } else if (IsTileType(tile
, MP_INDUSTRY
)) {
2609 Station
*neutral
= Industry::GetByTile(tile
)->neutral_station
;
2610 if (neutral
!= nullptr) UpdateStationDockingTiles(neutral
);
2616 * Clear docking tile status from tiles around a removed dock, if the tile has
2617 * no neighbours which would keep it as a docking tile.
2618 * @param tile Ex-dock tile to check.
2620 void ClearDockingTilesCheckingNeighbours(TileIndex tile
)
2622 assert(IsValidTile(tile
));
2624 /* Clear and maybe re-set docking tile */
2625 for (DiagDirection d
= DIAGDIR_BEGIN
; d
!= DIAGDIR_END
; d
++) {
2626 TileIndex docking_tile
= tile
+ TileOffsByDiagDir(d
);
2627 if (!IsValidTile(docking_tile
)) continue;
2629 if (IsPossibleDockingTile(docking_tile
)) {
2630 SetDockingTile(docking_tile
, false);
2631 CheckForDockingTile(docking_tile
);
2637 * Check if a dock tile can be docked from the given direction.
2638 * @param t Tile index of dock.
2639 * @param d DiagDirection adjacent to dock being tested.
2640 * @return True iff the dock can be docked from the given direction.
2642 bool IsValidDockingDirectionForDock(TileIndex t
, DiagDirection d
)
2644 assert(IsDockTile(t
));
2646 /** Bitmap of valid directions for each dock tile part. */
2647 static const uint8 _valid_docking_tile
[] = {
2648 0, 0, 0, 0, // No docking against the slope part.
2649 1 << DIAGDIR_NE
| 1 << DIAGDIR_SW
, // Docking permitted at the end
2650 1 << DIAGDIR_NW
| 1 << DIAGDIR_SE
, // of the flat piers.
2653 StationGfx gfx
= GetStationGfx(t
);
2654 assert(gfx
< lengthof(_valid_docking_tile
));
2655 return HasBit(_valid_docking_tile
[gfx
], d
);
2659 * Find the part of a dock that is land-based
2660 * @param t Dock tile to find land part of
2661 * @return tile of land part of dock
2663 static TileIndex
FindDockLandPart(TileIndex t
)
2665 assert(IsDockTile(t
));
2667 StationGfx gfx
= GetStationGfx(t
);
2668 if (gfx
< GFX_DOCK_BASE_WATER_PART
) return t
;
2670 for (DiagDirection d
= DIAGDIR_BEGIN
; d
!= DIAGDIR_END
; d
++) {
2671 TileIndex tile
= t
+ TileOffsByDiagDir(d
);
2672 if (!IsValidTile(tile
)) continue;
2673 if (!IsDockTile(tile
)) continue;
2674 if (GetStationGfx(tile
) < GFX_DOCK_BASE_WATER_PART
&& tile
+ TileOffsByDiagDir(GetDockDirection(tile
)) == t
) return tile
;
2677 return INVALID_TILE
;
2682 * @param tile TileIndex been queried
2683 * @param flags operation to perform
2684 * @return cost or failure of operation
2686 static CommandCost
RemoveDock(TileIndex tile
, DoCommandFlag flags
)
2688 Station
*st
= Station::GetByTile(tile
);
2689 CommandCost ret
= CheckOwnership(st
->owner
);
2690 if (ret
.Failed()) return ret
;
2692 if (!IsDockTile(tile
)) return CMD_ERROR
;
2694 TileIndex tile1
= FindDockLandPart(tile
);
2695 if (tile1
== INVALID_TILE
) return CMD_ERROR
;
2696 TileIndex tile2
= tile1
+ TileOffsByDiagDir(GetDockDirection(tile1
));
2698 ret
= EnsureNoVehicleOnGround(tile1
);
2699 if (ret
.Succeeded()) ret
= EnsureNoVehicleOnGround(tile2
);
2700 if (ret
.Failed()) return ret
;
2702 if (flags
& DC_EXEC
) {
2703 DoClearSquare(tile1
);
2704 MarkTileDirtyByTile(tile1
);
2705 MakeWaterKeepingClass(tile2
, st
->owner
);
2707 st
->rect
.AfterRemoveTile(st
, tile1
);
2708 st
->rect
.AfterRemoveTile(st
, tile2
);
2710 MakeShipStationAreaSmaller(st
);
2711 if (st
->ship_station
.tile
== INVALID_TILE
) {
2712 st
->ship_station
.Clear();
2713 st
->docking_station
.Clear();
2714 st
->facilities
&= ~FACIL_DOCK
;
2717 Company::Get(st
->owner
)->infrastructure
.station
-= 2;
2719 st
->AfterStationTileSetChange(false, STATION_DOCK
);
2721 ClearDockingTilesCheckingNeighbours(tile1
);
2722 ClearDockingTilesCheckingNeighbours(tile2
);
2724 /* All ships that were going to our station, can't go to it anymore.
2725 * Just clear the order, then automatically the next appropriate order
2726 * will be selected and in case of no appropriate order it will just
2727 * wander around the world. */
2728 if (!(st
->facilities
& FACIL_DOCK
)) {
2729 for (Ship
*s
: Ship::Iterate()) {
2730 if (s
->current_order
.IsType(OT_LOADING
) && s
->current_order
.GetDestination() == st
->index
) {
2734 if (s
->current_order
.IsType(OT_GOTO_STATION
) && s
->current_order
.GetDestination() == st
->index
) {
2735 s
->SetDestTile(s
->GetOrderStationLocation(st
->index
));
2741 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_STATION_DOCK
]);
2744 #include "table/station_land.h"
2746 const DrawTileSprites
*GetStationTileLayout(StationType st
, byte gfx
)
2748 return &_station_display_datas
[st
][gfx
];
2752 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
2753 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
2754 * is set to the overlay to draw.
2755 * @param ti Positional info for the tile to decide snowyness etc. May be nullptr.
2756 * @param[in,out] ground Groundsprite to draw.
2757 * @param[out] overlay_offset Overlay to draw.
2758 * @return true if overlay can be drawn.
2760 bool SplitGroundSpriteForOverlay(const TileInfo
*ti
, SpriteID
*ground
, RailTrackOffset
*overlay_offset
)
2764 case SPR_RAIL_TRACK_X
:
2765 case SPR_MONO_TRACK_X
:
2766 case SPR_MGLV_TRACK_X
:
2767 snow_desert
= false;
2768 *overlay_offset
= RTO_X
;
2771 case SPR_RAIL_TRACK_Y
:
2772 case SPR_MONO_TRACK_Y
:
2773 case SPR_MGLV_TRACK_Y
:
2774 snow_desert
= false;
2775 *overlay_offset
= RTO_Y
;
2778 case SPR_RAIL_TRACK_X_SNOW
:
2779 case SPR_MONO_TRACK_X_SNOW
:
2780 case SPR_MGLV_TRACK_X_SNOW
:
2782 *overlay_offset
= RTO_X
;
2785 case SPR_RAIL_TRACK_Y_SNOW
:
2786 case SPR_MONO_TRACK_Y_SNOW
:
2787 case SPR_MGLV_TRACK_Y_SNOW
:
2789 *overlay_offset
= RTO_Y
;
2796 if (ti
!= nullptr) {
2797 /* Decide snow/desert from tile */
2798 switch (_settings_game
.game_creation
.landscape
) {
2800 snow_desert
= (uint
)ti
->z
> GetSnowLine() * TILE_HEIGHT
;
2804 snow_desert
= GetTropicZone(ti
->tile
) == TROPICZONE_DESERT
;
2812 *ground
= snow_desert
? SPR_FLAT_SNOW_DESERT_TILE
: SPR_FLAT_GRASS_TILE
;
2816 static void DrawTile_Station(TileInfo
*ti
)
2818 const NewGRFSpriteLayout
*layout
= nullptr;
2819 DrawTileSprites tmp_rail_layout
;
2820 const DrawTileSprites
*t
= nullptr;
2822 const RailtypeInfo
*rti
= nullptr;
2823 uint32 relocation
= 0;
2824 uint32 ground_relocation
= 0;
2825 BaseStation
*st
= nullptr;
2826 const StationSpec
*statspec
= nullptr;
2827 uint tile_layout
= 0;
2829 if (HasStationRail(ti
->tile
)) {
2830 rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
2831 total_offset
= rti
->GetRailtypeSpriteOffset();
2833 if (IsCustomStationSpecIndex(ti
->tile
)) {
2834 /* look for customization */
2835 st
= BaseStation::GetByTile(ti
->tile
);
2836 statspec
= st
->speclist
[GetCustomStationSpecIndex(ti
->tile
)].spec
;
2838 if (statspec
!= nullptr) {
2839 tile_layout
= GetStationGfx(ti
->tile
);
2841 if (HasBit(statspec
->callback_mask
, CBM_STATION_SPRITE_LAYOUT
)) {
2842 uint16 callback
= GetStationCallback(CBID_STATION_SPRITE_LAYOUT
, 0, 0, statspec
, st
, ti
->tile
);
2843 if (callback
!= CALLBACK_FAILED
) tile_layout
= (callback
& ~1) + GetRailStationAxis(ti
->tile
);
2846 /* Ensure the chosen tile layout is valid for this custom station */
2847 if (statspec
->renderdata
!= nullptr) {
2848 layout
= &statspec
->renderdata
[tile_layout
< statspec
->tiles
? tile_layout
: (uint
)GetRailStationAxis(ti
->tile
)];
2849 if (!layout
->NeedsPreprocessing()) {
2860 StationGfx gfx
= GetStationGfx(ti
->tile
);
2861 if (IsAirport(ti
->tile
)) {
2862 gfx
= GetAirportGfx(ti
->tile
);
2863 if (gfx
>= NEW_AIRPORTTILE_OFFSET
) {
2864 const AirportTileSpec
*ats
= AirportTileSpec::Get(gfx
);
2865 if (ats
->grf_prop
.spritegroup
[0] != nullptr && DrawNewAirportTile(ti
, Station::GetByTile(ti
->tile
), gfx
, ats
)) {
2868 /* No sprite group (or no valid one) found, meaning no graphics associated.
2869 * Use the substitute one instead */
2870 assert(ats
->grf_prop
.subst_id
!= INVALID_AIRPORTTILE
);
2871 gfx
= ats
->grf_prop
.subst_id
;
2874 case APT_RADAR_GRASS_FENCE_SW
:
2875 t
= &_station_display_datas_airport_radar_grass_fence_sw
[GetAnimationFrame(ti
->tile
)];
2877 case APT_GRASS_FENCE_NE_FLAG
:
2878 t
= &_station_display_datas_airport_flag_grass_fence_ne
[GetAnimationFrame(ti
->tile
)];
2880 case APT_RADAR_FENCE_SW
:
2881 t
= &_station_display_datas_airport_radar_fence_sw
[GetAnimationFrame(ti
->tile
)];
2883 case APT_RADAR_FENCE_NE
:
2884 t
= &_station_display_datas_airport_radar_fence_ne
[GetAnimationFrame(ti
->tile
)];
2886 case APT_GRASS_FENCE_NE_FLAG_2
:
2887 t
= &_station_display_datas_airport_flag_grass_fence_ne_2
[GetAnimationFrame(ti
->tile
)];
2892 Owner owner
= GetTileOwner(ti
->tile
);
2895 if (Company::IsValidID(owner
)) {
2896 palette
= COMPANY_SPRITE_COLOUR(owner
);
2898 /* Some stations are not owner by a company, namely oil rigs */
2899 palette
= PALETTE_TO_GREY
;
2902 if (layout
== nullptr && (t
== nullptr || t
->seq
== nullptr)) t
= GetStationTileLayout(GetStationType(ti
->tile
), gfx
);
2904 /* don't show foundation for docks */
2905 if (ti
->tileh
!= SLOPE_FLAT
&& !IsDock(ti
->tile
)) {
2906 if (statspec
!= nullptr && HasBit(statspec
->flags
, SSF_CUSTOM_FOUNDATIONS
)) {
2907 /* Station has custom foundations.
2908 * Check whether the foundation continues beyond the tile's upper sides. */
2911 Slope slope
= GetFoundationPixelSlope(ti
->tile
, &z
);
2912 if (!HasFoundationNW(ti
->tile
, slope
, z
)) SetBit(edge_info
, 0);
2913 if (!HasFoundationNE(ti
->tile
, slope
, z
)) SetBit(edge_info
, 1);
2914 SpriteID image
= GetCustomStationFoundationRelocation(statspec
, st
, ti
->tile
, tile_layout
, edge_info
);
2915 if (image
== 0) goto draw_default_foundation
;
2917 if (HasBit(statspec
->flags
, SSF_EXTENDED_FOUNDATIONS
)) {
2918 /* Station provides extended foundations. */
2920 static const uint8 foundation_parts
[] = {
2921 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2922 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2923 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2924 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2927 AddSortableSpriteToDraw(image
+ foundation_parts
[ti
->tileh
], PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
2929 /* Draw simple foundations, built up from 8 possible foundation sprites. */
2931 /* Each set bit represents one of the eight composite sprites to be drawn.
2932 * 'Invalid' entries will not drawn but are included for completeness. */
2933 static const uint8 composite_foundation_parts
[] = {
2934 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2935 0x00, 0xD1, 0xE4, 0xE0,
2936 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2937 0xCA, 0xC9, 0xC4, 0xC0,
2938 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2939 0xD2, 0x91, 0xE4, 0xA0,
2940 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2944 uint8 parts
= composite_foundation_parts
[ti
->tileh
];
2946 /* If foundations continue beyond the tile's upper sides then
2947 * mask out the last two pieces. */
2948 if (HasBit(edge_info
, 0)) ClrBit(parts
, 6);
2949 if (HasBit(edge_info
, 1)) ClrBit(parts
, 7);
2952 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2953 * correct offset for the childsprites.
2954 * So, draw the (completely empty) sprite of the default foundations. */
2955 goto draw_default_foundation
;
2958 StartSpriteCombine();
2959 for (int i
= 0; i
< 8; i
++) {
2960 if (HasBit(parts
, i
)) {
2961 AddSortableSpriteToDraw(image
+ i
, PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
2967 OffsetGroundSprite(31, 1);
2968 ti
->z
+= ApplyPixelFoundationToSlope(FOUNDATION_LEVELED
, &ti
->tileh
);
2970 draw_default_foundation
:
2971 DrawFoundation(ti
, FOUNDATION_LEVELED
);
2975 if (IsBuoy(ti
->tile
)) {
2976 DrawWaterClassGround(ti
);
2977 SpriteID sprite
= GetCanalSprite(CF_BUOY
, ti
->tile
);
2978 if (sprite
!= 0) total_offset
= sprite
- SPR_IMG_BUOY
;
2979 } else if (IsDock(ti
->tile
) || (IsOilRig(ti
->tile
) && IsTileOnWater(ti
->tile
))) {
2980 if (ti
->tileh
== SLOPE_FLAT
) {
2981 DrawWaterClassGround(ti
);
2983 assert(IsDock(ti
->tile
));
2984 TileIndex water_tile
= ti
->tile
+ TileOffsByDiagDir(GetDockDirection(ti
->tile
));
2985 WaterClass wc
= HasTileWaterClass(water_tile
) ? GetWaterClass(water_tile
) : WATER_CLASS_INVALID
;
2986 if (wc
== WATER_CLASS_SEA
) {
2987 DrawShoreTile(ti
->tileh
);
2989 DrawClearLandTile(ti
, 3);
2993 if (layout
!= nullptr) {
2994 /* Sprite layout which needs preprocessing */
2995 bool separate_ground
= HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
);
2996 uint32 var10_values
= layout
->PrepareLayout(total_offset
, rti
->fallback_railtype
, 0, 0, separate_ground
);
2998 FOR_EACH_SET_BIT(var10
, var10_values
) {
2999 uint32 var10_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, var10
);
3000 layout
->ProcessRegisters(var10
, var10_relocation
, separate_ground
);
3002 tmp_rail_layout
.seq
= layout
->GetLayout(&tmp_rail_layout
.ground
);
3003 t
= &tmp_rail_layout
;
3005 } else if (statspec
!= nullptr) {
3006 /* Simple sprite layout */
3007 ground_relocation
= relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 0);
3008 if (HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
)) {
3009 ground_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 1);
3011 ground_relocation
+= rti
->fallback_railtype
;
3014 SpriteID image
= t
->ground
.sprite
;
3015 PaletteID pal
= t
->ground
.pal
;
3016 RailTrackOffset overlay_offset
;
3017 if (rti
!= nullptr && rti
->UsesOverlay() && SplitGroundSpriteForOverlay(ti
, &image
, &overlay_offset
)) {
3018 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
);
3019 DrawGroundSprite(image
, PAL_NONE
);
3020 DrawGroundSprite(ground
+ overlay_offset
, PAL_NONE
);
3022 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationReservation(ti
->tile
)) {
3023 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
3024 DrawGroundSprite(overlay
+ overlay_offset
, PALETTE_CRASH
);
3027 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
3028 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
3029 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
));
3031 /* PBS debugging, draw reserved tracks darker */
3032 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationRail(ti
->tile
) && HasStationReservation(ti
->tile
)) {
3033 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
3034 DrawGroundSprite(GetRailStationAxis(ti
->tile
) == AXIS_X
? rti
->base_sprites
.single_x
: rti
->base_sprites
.single_y
, PALETTE_CRASH
);
3039 if (HasStationRail(ti
->tile
) && HasRailCatenaryDrawn(GetRailType(ti
->tile
))) DrawRailCatenary(ti
);
3041 if (IsRoadStop(ti
->tile
)) {
3042 RoadType road_rt
= GetRoadTypeRoad(ti
->tile
);
3043 RoadType tram_rt
= GetRoadTypeTram(ti
->tile
);
3044 const RoadTypeInfo
* road_rti
= road_rt
== INVALID_ROADTYPE
? nullptr : GetRoadTypeInfo(road_rt
);
3045 const RoadTypeInfo
* tram_rti
= tram_rt
== INVALID_ROADTYPE
? nullptr : GetRoadTypeInfo(tram_rt
);
3047 if (IsDriveThroughStopTile(ti
->tile
)) {
3048 Axis axis
= GetRoadStopDir(ti
->tile
) == DIAGDIR_NE
? AXIS_X
: AXIS_Y
;
3049 uint sprite_offset
= axis
== AXIS_X
? 1 : 0;
3051 DrawRoadOverlays(ti
, PAL_NONE
, road_rti
, tram_rti
, sprite_offset
, sprite_offset
);
3053 /* Non-drivethrough road stops are only valid for roads. */
3054 assert(road_rt
!= INVALID_ROADTYPE
&& tram_rt
== INVALID_ROADTYPE
);
3056 if (road_rti
->UsesOverlay()) {
3057 DiagDirection dir
= GetRoadStopDir(ti
->tile
);
3058 SpriteID ground
= GetCustomRoadSprite(road_rti
, ti
->tile
, ROTSG_ROADSTOP
);
3059 DrawGroundSprite(ground
+ dir
, PAL_NONE
);
3063 /* Draw road, tram catenary */
3064 DrawRoadCatenary(ti
);
3067 if (IsRailWaypoint(ti
->tile
)) {
3068 /* Don't offset the waypoint graphics; they're always the same. */
3072 DrawRailTileSeq(ti
, t
, TO_BUILDINGS
, total_offset
, relocation
, palette
);
3075 void StationPickerDrawSprite(int x
, int y
, StationType st
, RailType railtype
, RoadType roadtype
, int image
)
3077 int32 total_offset
= 0;
3078 PaletteID pal
= COMPANY_SPRITE_COLOUR(_local_company
);
3079 const DrawTileSprites
*t
= GetStationTileLayout(st
, image
);
3080 const RailtypeInfo
*rti
= nullptr;
3082 if (railtype
!= INVALID_RAILTYPE
) {
3083 rti
= GetRailTypeInfo(railtype
);
3084 total_offset
= rti
->GetRailtypeSpriteOffset();
3087 SpriteID img
= t
->ground
.sprite
;
3088 RailTrackOffset overlay_offset
;
3089 if (rti
!= nullptr && rti
->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img
, &overlay_offset
)) {
3090 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
3091 DrawSprite(img
, PAL_NONE
, x
, y
);
3092 DrawSprite(ground
+ overlay_offset
, PAL_NONE
, x
, y
);
3094 DrawSprite(img
+ total_offset
, HasBit(img
, PALETTE_MODIFIER_COLOUR
) ? pal
: PAL_NONE
, x
, y
);
3097 if (roadtype
!= INVALID_ROADTYPE
) {
3098 const RoadTypeInfo
* rti
= GetRoadTypeInfo(roadtype
);
3100 /* Drive-through stop */
3101 uint sprite_offset
= 5 - image
;
3103 /* Road underlay takes precedence over tram */
3104 if (rti
->UsesOverlay()) {
3105 SpriteID ground
= GetCustomRoadSprite(rti
, INVALID_TILE
, ROTSG_GROUND
);
3106 DrawSprite(ground
+ sprite_offset
, PAL_NONE
, x
, y
);
3108 SpriteID overlay
= GetCustomRoadSprite(rti
, INVALID_TILE
, ROTSG_OVERLAY
);
3109 if (overlay
) DrawSprite(overlay
+ sprite_offset
, PAL_NONE
, x
, y
);
3110 } else if (RoadTypeIsTram(roadtype
)) {
3111 DrawSprite(SPR_TRAMWAY_TRAM
+ sprite_offset
, PAL_NONE
, x
, y
);
3115 if (RoadTypeIsRoad(roadtype
) && rti
->UsesOverlay()) {
3116 SpriteID ground
= GetCustomRoadSprite(rti
, INVALID_TILE
, ROTSG_ROADSTOP
);
3117 DrawSprite(ground
+ image
, PAL_NONE
, x
, y
);
3122 /* Default waypoint has no railtype specific sprites */
3123 DrawRailTileSeqInGUI(x
, y
, t
, st
== STATION_WAYPOINT
? 0 : total_offset
, 0, pal
);
3126 static int GetSlopePixelZ_Station(TileIndex tile
, uint x
, uint y
)
3128 return GetTileMaxPixelZ(tile
);
3131 static Foundation
GetFoundation_Station(TileIndex tile
, Slope tileh
)
3133 return FlatteningFoundation(tileh
);
3136 static void GetTileDesc_Station(TileIndex tile
, TileDesc
*td
)
3138 td
->owner
[0] = GetTileOwner(tile
);
3140 if (IsRoadStopTile(tile
)) {
3141 RoadType road_rt
= GetRoadTypeRoad(tile
);
3142 RoadType tram_rt
= GetRoadTypeTram(tile
);
3143 Owner road_owner
= INVALID_OWNER
;
3144 Owner tram_owner
= INVALID_OWNER
;
3145 if (road_rt
!= INVALID_ROADTYPE
) {
3146 const RoadTypeInfo
*rti
= GetRoadTypeInfo(road_rt
);
3147 td
->roadtype
= rti
->strings
.name
;
3148 td
->road_speed
= rti
->max_speed
/ 2;
3149 road_owner
= GetRoadOwner(tile
, RTT_ROAD
);
3152 if (tram_rt
!= INVALID_ROADTYPE
) {
3153 const RoadTypeInfo
*rti
= GetRoadTypeInfo(tram_rt
);
3154 td
->tramtype
= rti
->strings
.name
;
3155 td
->tram_speed
= rti
->max_speed
/ 2;
3156 tram_owner
= GetRoadOwner(tile
, RTT_TRAM
);
3159 if (IsDriveThroughStopTile(tile
)) {
3160 /* Is there a mix of owners? */
3161 if ((tram_owner
!= INVALID_OWNER
&& tram_owner
!= td
->owner
[0]) ||
3162 (road_owner
!= INVALID_OWNER
&& road_owner
!= td
->owner
[0])) {
3164 if (road_owner
!= INVALID_OWNER
) {
3165 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_ROAD_OWNER
;
3166 td
->owner
[i
] = road_owner
;
3169 if (tram_owner
!= INVALID_OWNER
) {
3170 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_TRAM_OWNER
;
3171 td
->owner
[i
] = tram_owner
;
3177 td
->build_date
= BaseStation::GetByTile(tile
)->build_date
;
3179 if (HasStationTileRail(tile
)) {
3180 const StationSpec
*spec
= GetStationSpec(tile
);
3182 if (spec
!= nullptr) {
3183 td
->station_class
= StationClass::Get(spec
->cls_id
)->name
;
3184 td
->station_name
= spec
->name
;
3186 if (spec
->grf_prop
.grffile
!= nullptr) {
3187 const GRFConfig
*gc
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
);
3188 td
->grf
= gc
->GetName();
3192 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(tile
));
3193 td
->rail_speed
= rti
->max_speed
;
3194 td
->railtype
= rti
->strings
.name
;
3197 if (IsAirport(tile
)) {
3198 const AirportSpec
*as
= Station::GetByTile(tile
)->airport
.GetSpec();
3199 td
->airport_class
= AirportClass::Get(as
->cls_id
)->name
;
3200 td
->airport_name
= as
->name
;
3202 const AirportTileSpec
*ats
= AirportTileSpec::GetByTile(tile
);
3203 td
->airport_tile_name
= ats
->name
;
3205 if (as
->grf_prop
.grffile
!= nullptr) {
3206 const GRFConfig
*gc
= GetGRFConfig(as
->grf_prop
.grffile
->grfid
);
3207 td
->grf
= gc
->GetName();
3208 } else if (ats
->grf_prop
.grffile
!= nullptr) {
3209 const GRFConfig
*gc
= GetGRFConfig(ats
->grf_prop
.grffile
->grfid
);
3210 td
->grf
= gc
->GetName();
3215 switch (GetStationType(tile
)) {
3216 default: NOT_REACHED();
3217 case STATION_RAIL
: str
= STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION
; break;
3218 case STATION_AIRPORT
:
3219 str
= (IsHangar(tile
) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR
: STR_LAI_STATION_DESCRIPTION_AIRPORT
);
3221 case STATION_TRUCK
: str
= STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA
; break;
3222 case STATION_BUS
: str
= STR_LAI_STATION_DESCRIPTION_BUS_STATION
; break;
3223 case STATION_OILRIG
: {
3224 const Industry
*i
= Station::GetByTile(tile
)->industry
;
3225 const IndustrySpec
*is
= GetIndustrySpec(i
->type
);
3226 td
->owner
[0] = i
->owner
;
3228 if (is
->grf_prop
.grffile
!= nullptr) td
->grf
= GetGRFConfig(is
->grf_prop
.grffile
->grfid
)->GetName();
3231 case STATION_DOCK
: str
= STR_LAI_STATION_DESCRIPTION_SHIP_DOCK
; break;
3232 case STATION_BUOY
: str
= STR_LAI_STATION_DESCRIPTION_BUOY
; break;
3233 case STATION_WAYPOINT
: str
= STR_LAI_STATION_DESCRIPTION_WAYPOINT
; break;
3239 static TrackStatus
GetTileTrackStatus_Station(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
3241 TrackBits trackbits
= TRACK_BIT_NONE
;
3244 case TRANSPORT_RAIL
:
3245 if (HasStationRail(tile
) && !IsStationTileBlocked(tile
)) {
3246 trackbits
= TrackToTrackBits(GetRailStationTrack(tile
));
3250 case TRANSPORT_WATER
:
3251 /* buoy is coded as a station, it is always on open water */
3253 trackbits
= TRACK_BIT_ALL
;
3254 /* remove tracks that connect NE map edge */
3255 if (TileX(tile
) == 0) trackbits
&= ~(TRACK_BIT_X
| TRACK_BIT_UPPER
| TRACK_BIT_RIGHT
);
3256 /* remove tracks that connect NW map edge */
3257 if (TileY(tile
) == 0) trackbits
&= ~(TRACK_BIT_Y
| TRACK_BIT_LEFT
| TRACK_BIT_UPPER
);
3261 case TRANSPORT_ROAD
:
3262 if (IsRoadStop(tile
)) {
3263 RoadTramType rtt
= (RoadTramType
)sub_mode
;
3264 if (!HasTileRoadType(tile
, rtt
)) break;
3266 DiagDirection dir
= GetRoadStopDir(tile
);
3267 Axis axis
= DiagDirToAxis(dir
);
3269 if (side
!= INVALID_DIAGDIR
) {
3270 if (axis
!= DiagDirToAxis(side
) || (IsStandardRoadStopTile(tile
) && dir
!= side
)) break;
3273 trackbits
= AxisToTrackBits(axis
);
3281 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits
), TRACKDIR_BIT_NONE
);
3285 static void TileLoop_Station(TileIndex tile
)
3287 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3288 * hardcoded.....not good */
3289 switch (GetStationType(tile
)) {
3290 case STATION_AIRPORT
:
3291 AirportTileAnimationTrigger(Station::GetByTile(tile
), tile
, AAT_TILELOOP
);
3295 if (!IsTileFlat(tile
)) break; // only handle water part
3298 case STATION_OILRIG
: //(station part)
3300 TileLoop_Water(tile
);
3308 static void AnimateTile_Station(TileIndex tile
)
3310 if (HasStationRail(tile
)) {
3311 AnimateStationTile(tile
);
3315 if (IsAirport(tile
)) {
3316 AnimateAirportTile(tile
);
3321 static bool ClickTile_Station(TileIndex tile
)
3323 const BaseStation
*bst
= BaseStation::GetByTile(tile
);
3325 if (bst
->facilities
& FACIL_WAYPOINT
) {
3326 ShowWaypointWindow(Waypoint::From(bst
));
3327 } else if (IsHangar(tile
)) {
3328 const Station
*st
= Station::From(bst
);
3329 ShowDepotWindow(st
->airport
.GetHangarTile(st
->airport
.GetHangarNum(tile
)), VEH_AIRCRAFT
);
3331 ShowStationViewWindow(bst
->index
);
3336 static VehicleEnterTileStatus
VehicleEnter_Station(Vehicle
*v
, TileIndex tile
, int x
, int y
)
3338 if (v
->type
== VEH_TRAIN
) {
3339 StationID station_id
= GetStationIndex(tile
);
3340 if (!v
->current_order
.ShouldStopAtStation(v
, station_id
)) return VETSB_CONTINUE
;
3341 if (!IsRailStation(tile
) || !v
->IsFrontEngine()) return VETSB_CONTINUE
;
3345 int stop
= GetTrainStopLocation(station_id
, tile
, Train::From(v
), &station_ahead
, &station_length
);
3347 /* Stop whenever that amount of station ahead + the distance from the
3348 * begin of the platform to the stop location is longer than the length
3349 * of the platform. Station ahead 'includes' the current tile where the
3350 * vehicle is on, so we need to subtract that. */
3351 if (stop
+ station_ahead
- (int)TILE_SIZE
>= station_length
) return VETSB_CONTINUE
;
3353 DiagDirection dir
= DirToDiagDir(v
->direction
);
3358 if (DiagDirToAxis(dir
) != AXIS_X
) Swap(x
, y
);
3359 if (y
== TILE_SIZE
/ 2) {
3360 if (dir
!= DIAGDIR_SE
&& dir
!= DIAGDIR_SW
) x
= TILE_SIZE
- 1 - x
;
3361 stop
&= TILE_SIZE
- 1;
3364 return VETSB_ENTERED_STATION
| (VehicleEnterTileStatus
)(station_id
<< VETS_STATION_ID_OFFSET
); // enter station
3365 } else if (x
< stop
) {
3366 v
->vehstatus
|= VS_TRAIN_SLOWING
;
3367 uint16 spd
= max(0, (stop
- x
) * 20 - 15);
3368 if (spd
< v
->cur_speed
) v
->cur_speed
= spd
;
3371 } else if (v
->type
== VEH_ROAD
) {
3372 RoadVehicle
*rv
= RoadVehicle::From(v
);
3373 if (rv
->state
< RVSB_IN_ROAD_STOP
&& !IsReversingRoadTrackdir((Trackdir
)rv
->state
) && rv
->frame
== 0) {
3374 if (IsRoadStop(tile
) && rv
->IsFrontEngine()) {
3375 /* Attempt to allocate a parking bay in a road stop */
3376 return RoadStop::GetByTile(tile
, GetRoadStopType(tile
))->Enter(rv
) ? VETSB_CONTINUE
: VETSB_CANNOT_ENTER
;
3381 return VETSB_CONTINUE
;
3385 * Run the watched cargo callback for all houses in the catchment area.
3386 * @param st Station.
3388 void TriggerWatchedCargoCallbacks(Station
*st
)
3390 /* Collect cargoes accepted since the last big tick. */
3391 CargoTypes cargoes
= 0;
3392 for (CargoID cid
= 0; cid
< NUM_CARGO
; cid
++) {
3393 if (HasBit(st
->goods
[cid
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
)) SetBit(cargoes
, cid
);
3396 /* Anything to do? */
3397 if (cargoes
== 0) return;
3399 /* Loop over all houses in the catchment. */
3400 BitmapTileIterator
it(st
->catchment_tiles
);
3401 for (TileIndex tile
= it
; tile
!= INVALID_TILE
; tile
= ++it
) {
3402 if (IsTileType(tile
, MP_HOUSE
)) {
3403 WatchedCargoCallback(tile
, cargoes
);
3409 * This function is called for each station once every 250 ticks.
3410 * Not all stations will get the tick at the same time.
3411 * @param st the station receiving the tick.
3412 * @return true if the station is still valid (wasn't deleted)
3414 static bool StationHandleBigTick(BaseStation
*st
)
3416 if (!st
->IsInUse()) {
3417 if (++st
->delete_ctr
>= 8) delete st
;
3421 if (Station::IsExpected(st
)) {
3422 TriggerWatchedCargoCallbacks(Station::From(st
));
3424 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3425 ClrBit(Station::From(st
)->goods
[i
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
);
3430 if ((st
->facilities
& FACIL_WAYPOINT
) == 0) UpdateStationAcceptance(Station::From(st
), true);
3435 static inline void byte_inc_sat(byte
*p
)
3442 * Truncate the cargo by a specific amount.
3443 * @param cs The type of cargo to perform the truncation for.
3444 * @param ge The goods entry, of the station, to truncate.
3445 * @param amount The amount to truncate the cargo by.
3447 static void TruncateCargo(const CargoSpec
*cs
, GoodsEntry
*ge
, uint amount
= UINT_MAX
)
3449 /* If truncating also punish the source stations' ratings to
3450 * decrease the flow of incoming cargo. */
3452 StationCargoAmountMap waiting_per_source
;
3453 ge
->cargo
.Truncate(amount
, &waiting_per_source
);
3454 for (StationCargoAmountMap::iterator
i(waiting_per_source
.begin()); i
!= waiting_per_source
.end(); ++i
) {
3455 Station
*source_station
= Station::GetIfValid(i
->first
);
3456 if (source_station
== nullptr) continue;
3458 GoodsEntry
&source_ge
= source_station
->goods
[cs
->Index()];
3459 source_ge
.max_waiting_cargo
= max(source_ge
.max_waiting_cargo
, i
->second
);
3463 static void UpdateStationRating(Station
*st
)
3465 bool waiting_changed
= false;
3467 byte_inc_sat(&st
->time_since_load
);
3468 byte_inc_sat(&st
->time_since_unload
);
3470 const CargoSpec
*cs
;
3471 FOR_ALL_CARGOSPECS(cs
) {
3472 GoodsEntry
*ge
= &st
->goods
[cs
->Index()];
3473 /* Slowly increase the rating back to his original level in the case we
3474 * didn't deliver cargo yet to this station. This happens when a bribe
3475 * failed while you didn't moved that cargo yet to a station. */
3476 if (!ge
->HasRating() && ge
->rating
< INITIAL_STATION_RATING
) {
3480 /* Only change the rating if we are moving this cargo */
3481 if (ge
->HasRating()) {
3482 byte_inc_sat(&ge
->time_since_pickup
);
3483 if (ge
->time_since_pickup
== 255 && _settings_game
.order
.selectgoods
) {
3484 ClrBit(ge
->status
, GoodsEntry::GES_RATING
);
3486 TruncateCargo(cs
, ge
);
3487 waiting_changed
= true;
3493 uint waiting
= ge
->cargo
.AvailableCount();
3495 /* num_dests is at least 1 if there is any cargo as
3496 * INVALID_STATION is also a destination.
3498 uint num_dests
= (uint
)ge
->cargo
.Packets()->MapSize();
3500 /* Average amount of cargo per next hop, but prefer solitary stations
3501 * with only one or two next hops. They are allowed to have more
3502 * cargo waiting per next hop.
3503 * With manual cargo distribution waiting_avg = waiting / 2 as then
3504 * INVALID_STATION is the only destination.
3506 uint waiting_avg
= waiting
/ (num_dests
+ 1);
3508 if (HasBit(cs
->callback_mask
, CBM_CARGO_STATION_RATING_CALC
)) {
3509 /* Perform custom station rating. If it succeeds the speed, days in transit and
3510 * waiting cargo ratings must not be executed. */
3512 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3513 uint last_speed
= ge
->HasVehicleEverTriedLoading() ? ge
->last_speed
: 0xFF;
3515 uint32 var18
= min(ge
->time_since_pickup
, 0xFF) | (min(ge
->max_waiting_cargo
, 0xFFFF) << 8) | (min(last_speed
, 0xFF) << 24);
3516 /* Convert to the 'old' vehicle types */
3517 uint32 var10
= (st
->last_vehicle_type
== VEH_INVALID
) ? 0x0 : (st
->last_vehicle_type
+ 0x10);
3518 uint16 callback
= GetCargoCallback(CBID_CARGO_STATION_RATING_CALC
, var10
, var18
, cs
);
3519 if (callback
!= CALLBACK_FAILED
) {
3521 rating
= GB(callback
, 0, 14);
3523 /* Simulate a 15 bit signed value */
3524 if (HasBit(callback
, 14)) rating
-= 0x4000;
3529 int b
= ge
->last_speed
- 85;
3530 if (b
>= 0) rating
+= b
>> 2;
3532 byte waittime
= ge
->time_since_pickup
;
3533 if (st
->last_vehicle_type
== VEH_SHIP
) waittime
>>= 2;
3534 if (waittime
<= 21) rating
+= 25;
3535 if (waittime
<= 12) rating
+= 25;
3536 if (waittime
<= 6) rating
+= 45;
3537 if (waittime
<= 3) rating
+= 35;
3540 if (ge
->max_waiting_cargo
<= 1500) rating
+= 55;
3541 if (ge
->max_waiting_cargo
<= 1000) rating
+= 35;
3542 if (ge
->max_waiting_cargo
<= 600) rating
+= 10;
3543 if (ge
->max_waiting_cargo
<= 300) rating
+= 20;
3544 if (ge
->max_waiting_cargo
<= 100) rating
+= 10;
3547 if (Company::IsValidID(st
->owner
) && HasBit(st
->town
->statues
, st
->owner
)) rating
+= 26;
3549 byte age
= ge
->last_age
;
3550 if (age
< 3) rating
+= 10;
3551 if (age
< 2) rating
+= 10;
3552 if (age
< 1) rating
+= 13;
3555 int or_
= ge
->rating
; // old rating
3557 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3558 ge
->rating
= rating
= or_
+ Clamp(Clamp(rating
, 0, 255) - or_
, -2, 2);
3560 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3561 * remove some random amount of goods from the station */
3562 if (rating
<= 64 && waiting_avg
>= 100) {
3563 int dec
= Random() & 0x1F;
3564 if (waiting_avg
< 200) dec
&= 7;
3565 waiting
-= (dec
+ 1) * num_dests
;
3566 waiting_changed
= true;
3569 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3570 if (rating
<= 127 && waiting
!= 0) {
3571 uint32 r
= Random();
3572 if (rating
<= (int)GB(r
, 0, 7)) {
3573 /* Need to have int, otherwise it will just overflow etc. */
3574 waiting
= max((int)waiting
- (int)((GB(r
, 8, 2) - 1) * num_dests
), 0);
3575 waiting_changed
= true;
3579 /* At some point we really must cap the cargo. Previously this
3580 * was a strict 4095, but now we'll have a less strict, but
3581 * increasingly aggressive truncation of the amount of cargo. */
3582 static const uint WAITING_CARGO_THRESHOLD
= 1 << 12;
3583 static const uint WAITING_CARGO_CUT_FACTOR
= 1 << 6;
3584 static const uint MAX_WAITING_CARGO
= 1 << 15;
3586 if (waiting
> WAITING_CARGO_THRESHOLD
) {
3587 uint difference
= waiting
- WAITING_CARGO_THRESHOLD
;
3588 waiting
-= (difference
/ WAITING_CARGO_CUT_FACTOR
);
3590 waiting
= min(waiting
, MAX_WAITING_CARGO
);
3591 waiting_changed
= true;
3594 /* We can't truncate cargo that's already reserved for loading.
3595 * Thus StoredCount() here. */
3596 if (waiting_changed
&& waiting
< ge
->cargo
.AvailableCount()) {
3597 /* Feed back the exact own waiting cargo at this station for the
3598 * next rating calculation. */
3599 ge
->max_waiting_cargo
= 0;
3601 TruncateCargo(cs
, ge
, ge
->cargo
.AvailableCount() - waiting
);
3603 /* If the average number per next hop is low, be more forgiving. */
3604 ge
->max_waiting_cargo
= waiting_avg
;
3610 StationID index
= st
->index
;
3611 if (waiting_changed
) {
3612 SetWindowDirty(WC_STATION_VIEW
, index
); // update whole window
3614 SetWindowWidgetDirty(WC_STATION_VIEW
, index
, WID_SV_ACCEPT_RATING_LIST
); // update only ratings list
3619 * Reroute cargo of type c at station st or in any vehicles unloading there.
3620 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3621 * @param st Station to be rerouted at.
3622 * @param c Type of cargo.
3623 * @param avoid Original next hop of cargo, avoid this.
3624 * @param avoid2 Another station to be avoided when rerouting.
3626 void RerouteCargo(Station
*st
, CargoID c
, StationID avoid
, StationID avoid2
)
3628 GoodsEntry
&ge
= st
->goods
[c
];
3630 /* Reroute cargo in station. */
3631 ge
.cargo
.Reroute(UINT_MAX
, &ge
.cargo
, avoid
, avoid2
, &ge
);
3633 /* Reroute cargo staged to be transferred. */
3634 for (std::list
<Vehicle
*>::iterator
it(st
->loading_vehicles
.begin()); it
!= st
->loading_vehicles
.end(); ++it
) {
3635 for (Vehicle
*v
= *it
; v
!= nullptr; v
= v
->Next()) {
3636 if (v
->cargo_type
!= c
) continue;
3637 v
->cargo
.Reroute(UINT_MAX
, &v
->cargo
, avoid
, avoid2
, &ge
);
3643 * Check all next hops of cargo packets in this station for existence of a
3644 * a valid link they may use to travel on. Reroute any cargo not having a valid
3645 * link and remove timed out links found like this from the linkgraph. We're
3646 * not all links here as that is expensive and useless. A link no one is using
3647 * doesn't hurt either.
3648 * @param from Station to check.
3650 void DeleteStaleLinks(Station
*from
)
3652 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
3653 const bool auto_distributed
= (_settings_game
.linkgraph
.GetDistributionType(c
) != DT_MANUAL
);
3654 GoodsEntry
&ge
= from
->goods
[c
];
3655 LinkGraph
*lg
= LinkGraph::GetIfValid(ge
.link_graph
);
3656 if (lg
== nullptr) continue;
3657 Node node
= (*lg
)[ge
.node
];
3658 for (EdgeIterator
it(node
.Begin()); it
!= node
.End();) {
3659 Edge edge
= it
->second
;
3660 Station
*to
= Station::Get((*lg
)[it
->first
].Station());
3661 assert(to
->goods
[c
].node
== it
->first
);
3662 ++it
; // Do that before removing the edge. Anything else may crash.
3663 assert(_date
>= edge
.LastUpdate());
3664 uint timeout
= LinkGraph::MIN_TIMEOUT_DISTANCE
+ (DistanceManhattan(from
->xy
, to
->xy
) >> 3);
3665 if ((uint
)(_date
- edge
.LastUpdate()) > timeout
) {
3666 bool updated
= false;
3668 if (auto_distributed
) {
3669 /* Have all vehicles refresh their next hops before deciding to
3670 * remove the node. */
3671 std::vector
<Vehicle
*> vehicles
;
3672 for (OrderList
*l
: OrderList::Iterate()) {
3673 bool found_from
= false;
3674 bool found_to
= false;
3675 for (Order
*order
= l
->GetFirstOrder(); order
!= nullptr; order
= order
->next
) {
3676 if (!order
->IsType(OT_GOTO_STATION
) && !order
->IsType(OT_IMPLICIT
)) continue;
3677 if (order
->GetDestination() == from
->index
) {
3679 if (found_to
) break;
3680 } else if (order
->GetDestination() == to
->index
) {
3682 if (found_from
) break;
3685 if (!found_to
|| !found_from
) continue;
3686 vehicles
.push_back(l
->GetFirstSharedVehicle());
3689 auto iter
= vehicles
.begin();
3690 while (iter
!= vehicles
.end()) {
3693 LinkRefresher::Run(v
, false); // Don't allow merging. Otherwise lg might get deleted.
3694 if (edge
.LastUpdate() == _date
) {
3699 Vehicle
*next_shared
= v
->NextShared();
3701 *iter
= next_shared
;
3704 iter
= vehicles
.erase(iter
);
3707 if (iter
== vehicles
.end()) iter
= vehicles
.begin();
3712 /* If it's still considered dead remove it. */
3713 node
.RemoveEdge(to
->goods
[c
].node
);
3714 ge
.flows
.DeleteFlows(to
->index
);
3715 RerouteCargo(from
, c
, to
->index
, from
->index
);
3717 } else if (edge
.LastUnrestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastUnrestrictedUpdate()) > timeout
) {
3719 ge
.flows
.RestrictFlows(to
->index
);
3720 RerouteCargo(from
, c
, to
->index
, from
->index
);
3721 } else if (edge
.LastRestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastRestrictedUpdate()) > timeout
) {
3725 assert(_date
>= lg
->LastCompression());
3726 if ((uint
)(_date
- lg
->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL
) {
3733 * Increase capacity for a link stat given by station cargo and next hop.
3734 * @param st Station to get the link stats from.
3735 * @param cargo Cargo to increase stat for.
3736 * @param next_station_id Station the consist will be travelling to next.
3737 * @param capacity Capacity to add to link stat.
3738 * @param usage Usage to add to link stat.
3739 * @param mode Update mode to be applied.
3741 void IncreaseStats(Station
*st
, CargoID cargo
, StationID next_station_id
, uint capacity
, uint usage
, EdgeUpdateMode mode
)
3743 GoodsEntry
&ge1
= st
->goods
[cargo
];
3744 Station
*st2
= Station::Get(next_station_id
);
3745 GoodsEntry
&ge2
= st2
->goods
[cargo
];
3746 LinkGraph
*lg
= nullptr;
3747 if (ge1
.link_graph
== INVALID_LINK_GRAPH
) {
3748 if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3749 if (LinkGraph::CanAllocateItem()) {
3750 lg
= new LinkGraph(cargo
);
3751 LinkGraphSchedule::instance
.Queue(lg
);
3752 ge2
.link_graph
= lg
->index
;
3753 ge2
.node
= lg
->AddNode(st2
);
3755 DEBUG(misc
, 0, "Can't allocate link graph");
3758 lg
= LinkGraph::Get(ge2
.link_graph
);
3761 ge1
.link_graph
= lg
->index
;
3762 ge1
.node
= lg
->AddNode(st
);
3764 } else if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3765 lg
= LinkGraph::Get(ge1
.link_graph
);
3766 ge2
.link_graph
= lg
->index
;
3767 ge2
.node
= lg
->AddNode(st2
);
3769 lg
= LinkGraph::Get(ge1
.link_graph
);
3770 if (ge1
.link_graph
!= ge2
.link_graph
) {
3771 LinkGraph
*lg2
= LinkGraph::Get(ge2
.link_graph
);
3772 if (lg
->Size() < lg2
->Size()) {
3773 LinkGraphSchedule::instance
.Unqueue(lg
);
3774 lg2
->Merge(lg
); // Updates GoodsEntries of lg
3777 LinkGraphSchedule::instance
.Unqueue(lg2
);
3778 lg
->Merge(lg2
); // Updates GoodsEntries of lg2
3782 if (lg
!= nullptr) {
3783 (*lg
)[ge1
.node
].UpdateEdge(ge2
.node
, capacity
, usage
, mode
);
3788 * Increase capacity for all link stats associated with vehicles in the given consist.
3789 * @param st Station to get the link stats from.
3790 * @param front First vehicle in the consist.
3791 * @param next_station_id Station the consist will be travelling to next.
3793 void IncreaseStats(Station
*st
, const Vehicle
*front
, StationID next_station_id
)
3795 for (const Vehicle
*v
= front
; v
!= nullptr; v
= v
->Next()) {
3796 if (v
->refit_cap
> 0) {
3797 /* The cargo count can indeed be higher than the refit_cap if
3798 * wagons have been auto-replaced and subsequently auto-
3799 * refitted to a higher capacity. The cargo gets redistributed
3800 * among the wagons in that case.
3801 * As usage is not such an important figure anyway we just
3802 * ignore the additional cargo then.*/
3803 IncreaseStats(st
, v
->cargo_type
, next_station_id
, v
->refit_cap
,
3804 min(v
->refit_cap
, v
->cargo
.StoredCount()), EUM_INCREASE
);
3809 /* called for every station each tick */
3810 static void StationHandleSmallTick(BaseStation
*st
)
3812 if ((st
->facilities
& FACIL_WAYPOINT
) != 0 || !st
->IsInUse()) return;
3814 byte b
= st
->delete_ctr
+ 1;
3815 if (b
>= STATION_RATING_TICKS
) b
= 0;
3818 if (b
== 0) UpdateStationRating(Station::From(st
));
3821 void OnTick_Station()
3823 if (_game_mode
== GM_EDITOR
) return;
3825 for (BaseStation
*st
: BaseStation::Iterate()) {
3826 StationHandleSmallTick(st
);
3828 /* Clean up the link graph about once a week. */
3829 if (Station::IsExpected(st
) && (_tick_counter
+ st
->index
) % STATION_LINKGRAPH_TICKS
== 0) {
3830 DeleteStaleLinks(Station::From(st
));
3833 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3834 * Station index is included so that triggers are not all done
3835 * at the same time. */
3836 if ((_tick_counter
+ st
->index
) % STATION_ACCEPTANCE_TICKS
== 0) {
3837 /* Stop processing this station if it was deleted */
3838 if (!StationHandleBigTick(st
)) continue;
3839 TriggerStationAnimation(st
, st
->xy
, SAT_250_TICKS
);
3840 if (Station::IsExpected(st
)) AirportAnimationTrigger(Station::From(st
), AAT_STATION_250_TICKS
);
3845 /** Monthly loop for stations. */
3846 void StationMonthlyLoop()
3848 for (Station
*st
: Station::Iterate()) {
3849 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3850 GoodsEntry
*ge
= &st
->goods
[i
];
3851 SB(ge
->status
, GoodsEntry::GES_LAST_MONTH
, 1, GB(ge
->status
, GoodsEntry::GES_CURRENT_MONTH
, 1));
3852 ClrBit(ge
->status
, GoodsEntry::GES_CURRENT_MONTH
);
3858 void ModifyStationRatingAround(TileIndex tile
, Owner owner
, int amount
, uint radius
)
3860 ForAllStationsRadius(tile
, radius
, [&](Station
*st
) {
3861 if (st
->owner
== owner
) {
3862 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3863 GoodsEntry
*ge
= &st
->goods
[i
];
3865 if (ge
->status
!= 0) {
3866 ge
->rating
= Clamp(ge
->rating
+ amount
, 0, 255);
3873 static uint
UpdateStationWaiting(Station
*st
, CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
)
3875 /* We can't allocate a CargoPacket? Then don't do anything
3876 * at all; i.e. just discard the incoming cargo. */
3877 if (!CargoPacket::CanAllocateItem()) return 0;
3879 GoodsEntry
&ge
= st
->goods
[type
];
3880 amount
+= ge
.amount_fract
;
3881 ge
.amount_fract
= GB(amount
, 0, 8);
3884 /* No new "real" cargo item yet. */
3885 if (amount
== 0) return 0;
3887 StationID next
= ge
.GetVia(st
->index
);
3888 ge
.cargo
.Append(new CargoPacket(st
->index
, st
->xy
, amount
, source_type
, source_id
), next
);
3889 LinkGraph
*lg
= nullptr;
3890 if (ge
.link_graph
== INVALID_LINK_GRAPH
) {
3891 if (LinkGraph::CanAllocateItem()) {
3892 lg
= new LinkGraph(type
);
3893 LinkGraphSchedule::instance
.Queue(lg
);
3894 ge
.link_graph
= lg
->index
;
3895 ge
.node
= lg
->AddNode(st
);
3897 DEBUG(misc
, 0, "Can't allocate link graph");
3900 lg
= LinkGraph::Get(ge
.link_graph
);
3902 if (lg
!= nullptr) (*lg
)[ge
.node
].UpdateSupply(amount
);
3904 if (!ge
.HasRating()) {
3905 InvalidateWindowData(WC_STATION_LIST
, st
->index
);
3906 SetBit(ge
.status
, GoodsEntry::GES_RATING
);
3909 TriggerStationRandomisation(st
, st
->xy
, SRT_NEW_CARGO
, type
);
3910 TriggerStationAnimation(st
, st
->xy
, SAT_NEW_CARGO
, type
);
3911 AirportAnimationTrigger(st
, AAT_STATION_NEW_CARGO
, type
);
3913 SetWindowDirty(WC_STATION_VIEW
, st
->index
);
3914 st
->MarkTilesDirty(true);
3918 static bool IsUniqueStationName(const char *name
)
3920 for (const Station
*st
: Station::Iterate()) {
3921 if (st
->name
!= nullptr && strcmp(st
->name
, name
) == 0) return false;
3929 * @param tile unused
3930 * @param flags operation to perform
3931 * @param p1 station ID that is to be renamed
3933 * @param text the new name or an empty string when resetting to the default
3934 * @return the cost of this operation or an error
3936 CommandCost
CmdRenameStation(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
3938 Station
*st
= Station::GetIfValid(p1
);
3939 if (st
== nullptr) return CMD_ERROR
;
3941 CommandCost ret
= CheckOwnership(st
->owner
);
3942 if (ret
.Failed()) return ret
;
3944 bool reset
= StrEmpty(text
);
3947 if (Utf8StringLength(text
) >= MAX_LENGTH_STATION_NAME_CHARS
) return CMD_ERROR
;
3948 if (!IsUniqueStationName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
3951 if (flags
& DC_EXEC
) {
3952 st
->cached_name
.clear();
3954 st
->name
= reset
? nullptr : stredup(text
);
3956 st
->UpdateVirtCoord();
3957 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 1);
3960 return CommandCost();
3963 static void AddNearbyStationsByCatchment(TileIndex tile
, StationList
*stations
, StationList
&nearby
)
3965 for (Station
*st
: nearby
) {
3966 if (st
->TileIsInCatchment(tile
)) stations
->insert(st
);
3971 * Find all stations around a rectangular producer (industry, house, headquarter, ...)
3973 * @param location The location/area of the producer
3974 * @param[out] stations The list to store the stations in
3975 * @param use_nearby Use nearby station list of industry/town associated with location.tile
3977 void FindStationsAroundTiles(const TileArea
&location
, StationList
* const stations
, bool use_nearby
)
3980 /* Industries and towns maintain a list of nearby stations */
3981 if (IsTileType(location
.tile
, MP_INDUSTRY
)) {
3982 /* Industry nearby stations are already filtered by catchment. */
3983 *stations
= Industry::GetByTile(location
.tile
)->stations_near
;
3985 } else if (IsTileType(location
.tile
, MP_HOUSE
)) {
3986 /* Town nearby stations need to be filtered per tile. */
3987 assert(location
.w
== 1 && location
.h
== 1);
3988 AddNearbyStationsByCatchment(location
.tile
, stations
, Town::GetByTile(location
.tile
)->stations_near
);
3993 /* Not using, or don't have a nearby stations list, so we need to scan. */
3994 std::set
<StationID
> seen_stations
;
3996 /* Scan an area around the building covering the maximum possible station
3997 * to find the possible nearby stations. */
3998 uint max_c
= _settings_game
.station
.modified_catchment
? MAX_CATCHMENT
: CA_UNMODIFIED
;
3999 TileArea ta
= TileArea(location
).Expand(max_c
);
4000 TILE_AREA_LOOP(tile
, ta
) {
4001 if (IsTileType(tile
, MP_STATION
)) seen_stations
.insert(GetStationIndex(tile
));
4004 for (StationID stationid
: seen_stations
) {
4005 Station
*st
= Station::GetIfValid(stationid
);
4006 if (st
== nullptr) continue; /* Waypoint */
4008 /* Check if station is attached to an industry */
4009 if (!_settings_game
.station
.serve_neutral_industries
&& st
->industry
!= nullptr) continue;
4011 /* Test if the tile is within the station's catchment */
4012 TILE_AREA_LOOP(tile
, location
) {
4013 if (st
->TileIsInCatchment(tile
)) {
4014 stations
->insert(st
);
4022 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
4023 * @return pointer to a StationList containing all stations found
4025 const StationList
*StationFinder::GetStations()
4027 if (this->tile
!= INVALID_TILE
) {
4028 FindStationsAroundTiles(*this, &this->stations
);
4029 this->tile
= INVALID_TILE
;
4031 return &this->stations
;
4034 static bool CanMoveGoodsToStation(const Station
*st
, CargoID type
)
4036 /* Is the station reserved exclusively for somebody else? */
4037 if (st
->owner
!= OWNER_NONE
&& st
->town
->exclusive_counter
> 0 && st
->town
->exclusivity
!= st
->owner
) return false;
4039 /* Lowest possible rating, better not to give cargo anymore. */
4040 if (st
->goods
[type
].rating
== 0) return false;
4042 /* Selectively servicing stations, and not this one. */
4043 if (_settings_game
.order
.selectgoods
&& !st
->goods
[type
].HasVehicleEverTriedLoading()) return false;
4045 if (IsCargoInClass(type
, CC_PASSENGERS
)) {
4046 /* Passengers are never served by just a truck stop. */
4047 if (st
->facilities
== FACIL_TRUCK_STOP
) return false;
4049 /* Non-passengers are never served by just a bus stop. */
4050 if (st
->facilities
== FACIL_BUS_STOP
) return false;
4055 uint
MoveGoodsToStation(CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
, const StationList
*all_stations
)
4057 /* Return if nothing to do. Also the rounding below fails for 0. */
4058 if (all_stations
->empty()) return 0;
4059 if (amount
== 0) return 0;
4061 Station
*first_station
= nullptr;
4062 typedef std::pair
<Station
*, uint
> StationInfo
;
4063 std::vector
<StationInfo
> used_stations
;
4065 for (Station
*st
: *all_stations
) {
4066 if (!CanMoveGoodsToStation(st
, type
)) continue;
4068 /* Avoid allocating a vector if there is only one station to significantly
4069 * improve performance in this common case. */
4070 if (first_station
== nullptr) {
4074 if (used_stations
.empty()) {
4075 used_stations
.reserve(2);
4076 used_stations
.emplace_back(std::make_pair(first_station
, 0));
4078 used_stations
.emplace_back(std::make_pair(st
, 0));
4081 /* no stations around at all? */
4082 if (first_station
== nullptr) return 0;
4084 if (used_stations
.empty()) {
4085 /* only one station around */
4086 amount
*= first_station
->goods
[type
].rating
+ 1;
4087 return UpdateStationWaiting(first_station
, type
, amount
, source_type
, source_id
);
4090 uint company_best
[OWNER_NONE
+ 1] = {}; // best rating for each company, including OWNER_NONE
4091 uint company_sum
[OWNER_NONE
+ 1] = {}; // sum of ratings for each company
4092 uint best_rating
= 0;
4093 uint best_sum
= 0; // sum of best ratings for each company
4095 for (auto &p
: used_stations
) {
4096 auto owner
= p
.first
->owner
;
4097 auto rating
= p
.first
->goods
[type
].rating
;
4098 if (rating
> company_best
[owner
]) {
4099 best_sum
+= rating
- company_best
[owner
]; // it's usually faster than iterating companies later
4100 company_best
[owner
] = rating
;
4101 if (rating
> best_rating
) best_rating
= rating
;
4103 company_sum
[owner
] += rating
;
4106 /* From now we'll calculate with fractional cargo amounts.
4107 * First determine how much cargo we really have. */
4108 amount
*= best_rating
+ 1;
4111 for (auto &p
: used_stations
) {
4112 uint owner
= p
.first
->owner
;
4113 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4114 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4115 p
.second
= amount
* company_best
[owner
] * p
.first
->goods
[type
].rating
/ best_sum
/ company_sum
[owner
];
4119 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4120 if (amount
> moving
) {
4121 std::sort(used_stations
.begin(), used_stations
.end(), [type
] (const StationInfo
&a
, const StationInfo
&b
) {
4122 return b
.first
->goods
[type
].rating
< a
.first
->goods
[type
].rating
;
4125 assert(amount
- moving
<= used_stations
.size());
4126 for (uint i
= 0; i
< amount
- moving
; i
++) {
4127 used_stations
[i
].second
++;
4132 for (auto &p
: used_stations
) {
4133 moved
+= UpdateStationWaiting(p
.first
, type
, p
.second
, source_type
, source_id
);
4139 void UpdateStationDockingTiles(Station
*st
)
4141 st
->docking_station
.Clear();
4143 /* For neutral stations, start with the industry area instead of dock area */
4144 const TileArea
*area
= st
->industry
!= nullptr ? &st
->industry
->location
: &st
->ship_station
;
4146 if (area
->tile
== INVALID_TILE
) return;
4148 int x
= TileX(area
->tile
);
4149 int y
= TileY(area
->tile
);
4151 /* Expand the area by a tile on each side while
4152 * making sure that we remain inside the map. */
4153 int x2
= min(x
+ area
->w
+ 1, MapSizeX());
4154 int x1
= max(x
- 1, 0);
4156 int y2
= min(y
+ area
->h
+ 1, MapSizeY());
4157 int y1
= max(y
- 1, 0);
4159 TileArea
ta(TileXY(x1
, y1
), TileXY(x2
- 1, y2
- 1));
4160 TILE_AREA_LOOP(tile
, ta
) {
4161 if (IsValidTile(tile
) && IsPossibleDockingTile(tile
)) CheckForDockingTile(tile
);
4165 void BuildOilRig(TileIndex tile
)
4167 if (!Station::CanAllocateItem()) {
4168 DEBUG(misc
, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile
);
4172 Station
*st
= new Station(tile
);
4173 _station_kdtree
.Insert(st
->index
);
4174 st
->town
= ClosestTownFromTile(tile
, UINT_MAX
);
4176 st
->string_id
= GenerateStationName(st
, tile
, STATIONNAMING_OILRIG
);
4178 assert(IsTileType(tile
, MP_INDUSTRY
));
4179 /* Mark industry as associated both ways */
4180 st
->industry
= Industry::GetByTile(tile
);
4181 st
->industry
->neutral_station
= st
;
4182 DeleteAnimatedTile(tile
);
4183 MakeOilrig(tile
, st
->index
, GetWaterClass(tile
));
4185 st
->owner
= OWNER_NONE
;
4186 st
->airport
.type
= AT_OILRIG
;
4187 st
->airport
.Add(tile
);
4188 st
->ship_station
.Add(tile
);
4189 st
->facilities
= FACIL_AIRPORT
| FACIL_DOCK
;
4190 st
->build_date
= _date
;
4191 UpdateStationDockingTiles(st
);
4193 st
->rect
.BeforeAddTile(tile
, StationRect::ADD_FORCE
);
4195 st
->UpdateVirtCoord();
4196 st
->RecomputeCatchment();
4197 UpdateStationAcceptance(st
, false);
4200 void DeleteOilRig(TileIndex tile
)
4202 Station
*st
= Station::GetByTile(tile
);
4204 MakeWaterKeepingClass(tile
, OWNER_NONE
);
4206 /* The oil rig station is not supposed to be shared with anything else */
4207 assert(st
->facilities
== (FACIL_AIRPORT
| FACIL_DOCK
) && st
->airport
.type
== AT_OILRIG
);
4208 if (st
->industry
!= nullptr && st
->industry
->neutral_station
== st
) {
4209 /* Don't leave dangling neutral station pointer */
4210 st
->industry
->neutral_station
= nullptr;
4215 static void ChangeTileOwner_Station(TileIndex tile
, Owner old_owner
, Owner new_owner
)
4217 if (IsRoadStopTile(tile
)) {
4218 FOR_ALL_ROADTRAMTYPES(rtt
) {
4219 /* Update all roadtypes, no matter if they are present */
4220 if (GetRoadOwner(tile
, rtt
) == old_owner
) {
4221 RoadType rt
= GetRoadType(tile
, rtt
);
4222 if (rt
!= INVALID_ROADTYPE
) {
4223 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4224 Company::Get(old_owner
)->infrastructure
.road
[rt
] -= 2;
4225 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.road
[rt
] += 2;
4227 SetRoadOwner(tile
, rtt
, new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
);
4232 if (!IsTileOwner(tile
, old_owner
)) return;
4234 if (new_owner
!= INVALID_OWNER
) {
4235 /* Update company infrastructure counts. Only do it here
4236 * if the new owner is valid as otherwise the clear
4237 * command will do it for us. No need to dirty windows
4238 * here, we'll redraw the whole screen anyway.*/
4239 Company
*old_company
= Company::Get(old_owner
);
4240 Company
*new_company
= Company::Get(new_owner
);
4242 /* Update counts for underlying infrastructure. */
4243 switch (GetStationType(tile
)) {
4245 case STATION_WAYPOINT
:
4246 if (!IsStationTileBlocked(tile
)) {
4247 old_company
->infrastructure
.rail
[GetRailType(tile
)]--;
4248 new_company
->infrastructure
.rail
[GetRailType(tile
)]++;
4254 /* Road stops were already handled above. */
4259 if (GetWaterClass(tile
) == WATER_CLASS_CANAL
) {
4260 old_company
->infrastructure
.water
--;
4261 new_company
->infrastructure
.water
++;
4269 /* Update station tile count. */
4270 if (!IsBuoy(tile
) && !IsAirport(tile
)) {
4271 old_company
->infrastructure
.station
--;
4272 new_company
->infrastructure
.station
++;
4275 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4276 SetTileOwner(tile
, new_owner
);
4277 InvalidateWindowClassesData(WC_STATION_LIST
, 0);
4279 if (IsDriveThroughStopTile(tile
)) {
4280 /* Remove the drive-through road stop */
4281 DoCommand(tile
, 1 | 1 << 8, (GetStationType(tile
) == STATION_TRUCK
) ? ROADSTOP_TRUCK
: ROADSTOP_BUS
, DC_EXEC
| DC_BANKRUPT
, CMD_REMOVE_ROAD_STOP
);
4282 assert(IsTileType(tile
, MP_ROAD
));
4283 /* Change owner of tile and all roadtypes */
4284 ChangeTileOwner(tile
, old_owner
, new_owner
);
4286 DoCommand(tile
, 0, 0, DC_EXEC
| DC_BANKRUPT
, CMD_LANDSCAPE_CLEAR
);
4287 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4288 * Update owner of buoy if it was not removed (was in orders).
4289 * Do not update when owned by OWNER_WATER (sea and rivers). */
4290 if ((IsTileType(tile
, MP_WATER
) || IsBuoyTile(tile
)) && IsTileOwner(tile
, old_owner
)) SetTileOwner(tile
, OWNER_NONE
);
4296 * Check if a drive-through road stop tile can be cleared.
4297 * Road stops built on town-owned roads check the conditions
4298 * that would allow clearing of the original road.
4299 * @param tile road stop tile to check
4300 * @param flags command flags
4301 * @return true if the road can be cleared
4303 static bool CanRemoveRoadWithStop(TileIndex tile
, DoCommandFlag flags
)
4305 /* Yeah... water can always remove stops, right? */
4306 if (_current_company
== OWNER_WATER
) return true;
4308 if (GetRoadTypeTram(tile
) != INVALID_ROADTYPE
) {
4309 Owner tram_owner
= GetRoadOwner(tile
, RTT_TRAM
);
4310 if (tram_owner
!= OWNER_NONE
&& CheckOwnership(tram_owner
).Failed()) return false;
4312 if (GetRoadTypeRoad(tile
) != INVALID_ROADTYPE
) {
4313 Owner road_owner
= GetRoadOwner(tile
, RTT_ROAD
);
4314 if (road_owner
!= OWNER_TOWN
) {
4315 if (road_owner
!= OWNER_NONE
&& CheckOwnership(road_owner
).Failed()) return false;
4317 if (CheckAllowRemoveRoad(tile
, GetAnyRoadBits(tile
, RTT_ROAD
), OWNER_TOWN
, RTT_ROAD
, flags
).Failed()) return false;
4325 * Clear a single tile of a station.
4326 * @param tile The tile to clear.
4327 * @param flags The DoCommand flags related to the "command".
4328 * @return The cost, or error of clearing.
4330 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
)
4332 if (flags
& DC_AUTO
) {
4333 switch (GetStationType(tile
)) {
4335 case STATION_RAIL
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD
);
4336 case STATION_WAYPOINT
: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
4337 case STATION_AIRPORT
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
4338 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
);
4339 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
);
4340 case STATION_BUOY
: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY
);
4341 case STATION_DOCK
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST
);
4342 case STATION_OILRIG
:
4343 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG
);
4344 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY
);
4348 switch (GetStationType(tile
)) {
4349 case STATION_RAIL
: return RemoveRailStation(tile
, flags
);
4350 case STATION_WAYPOINT
: return RemoveRailWaypoint(tile
, flags
);
4351 case STATION_AIRPORT
: return RemoveAirport(tile
, flags
);
4353 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4354 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST
);
4356 return RemoveRoadStop(tile
, flags
);
4358 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4359 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST
);
4361 return RemoveRoadStop(tile
, flags
);
4362 case STATION_BUOY
: return RemoveBuoy(tile
, flags
);
4363 case STATION_DOCK
: return RemoveDock(tile
, flags
);
4370 static CommandCost
TerraformTile_Station(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
4372 if (_settings_game
.construction
.build_on_slopes
&& AutoslopeEnabled()) {
4373 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4374 * TTDP does not call it.
4376 if (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
)) {
4377 switch (GetStationType(tile
)) {
4378 case STATION_WAYPOINT
:
4379 case STATION_RAIL
: {
4380 DiagDirection direction
= AxisToDiagDir(GetRailStationAxis(tile
));
4381 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4382 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4383 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4386 case STATION_AIRPORT
:
4387 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4391 DiagDirection direction
= GetRoadStopDir(tile
);
4392 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4393 if (IsDriveThroughStopTile(tile
)) {
4394 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4396 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4403 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
4407 * Get flow for a station.
4408 * @param st Station to get flow for.
4409 * @return Flow for st.
4411 uint
FlowStat::GetShare(StationID st
) const
4414 for (SharesMap::const_iterator it
= this->shares
.begin(); it
!= this->shares
.end(); ++it
) {
4415 if (it
->second
== st
) {
4416 return it
->first
- prev
;
4425 * Get a station a package can be routed to, but exclude the given ones.
4426 * @param excluded StationID not to be selected.
4427 * @param excluded2 Another StationID not to be selected.
4428 * @return A station ID from the shares map.
4430 StationID
FlowStat::GetVia(StationID excluded
, StationID excluded2
) const
4432 if (this->unrestricted
== 0) return INVALID_STATION
;
4433 assert(!this->shares
.empty());
4434 SharesMap::const_iterator it
= this->shares
.upper_bound(RandomRange(this->unrestricted
));
4435 assert(it
!= this->shares
.end() && it
->first
<= this->unrestricted
);
4436 if (it
->second
!= excluded
&& it
->second
!= excluded2
) return it
->second
;
4438 /* We've hit one of the excluded stations.
4439 * Draw another share, from outside its range. */
4441 uint end
= it
->first
;
4442 uint begin
= (it
== this->shares
.begin() ? 0 : (--it
)->first
);
4443 uint interval
= end
- begin
;
4444 if (interval
>= this->unrestricted
) return INVALID_STATION
; // Only one station in the map.
4445 uint new_max
= this->unrestricted
- interval
;
4446 uint rand
= RandomRange(new_max
);
4447 SharesMap::const_iterator it2
= (rand
< begin
) ? this->shares
.upper_bound(rand
) :
4448 this->shares
.upper_bound(rand
+ interval
);
4449 assert(it2
!= this->shares
.end() && it2
->first
<= this->unrestricted
);
4450 if (it2
->second
!= excluded
&& it2
->second
!= excluded2
) return it2
->second
;
4452 /* We've hit the second excluded station.
4453 * Same as before, only a bit more complicated. */
4455 uint end2
= it2
->first
;
4456 uint begin2
= (it2
== this->shares
.begin() ? 0 : (--it2
)->first
);
4457 uint interval2
= end2
- begin2
;
4458 if (interval2
>= new_max
) return INVALID_STATION
; // Only the two excluded stations in the map.
4459 new_max
-= interval2
;
4460 if (begin
> begin2
) {
4461 Swap(begin
, begin2
);
4463 Swap(interval
, interval2
);
4465 rand
= RandomRange(new_max
);
4466 SharesMap::const_iterator it3
= this->shares
.upper_bound(this->unrestricted
);
4468 it3
= this->shares
.upper_bound(rand
);
4469 } else if (rand
< begin2
- interval
) {
4470 it3
= this->shares
.upper_bound(rand
+ interval
);
4472 it3
= this->shares
.upper_bound(rand
+ interval
+ interval2
);
4474 assert(it3
!= this->shares
.end() && it3
->first
<= this->unrestricted
);
4479 * Reduce all flows to minimum capacity so that they don't get in the way of
4480 * link usage statistics too much. Keep them around, though, to continue
4481 * routing any remaining cargo.
4483 void FlowStat::Invalidate()
4485 assert(!this->shares
.empty());
4486 SharesMap new_shares
;
4488 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4489 new_shares
[++i
] = it
->second
;
4490 if (it
->first
== this->unrestricted
) this->unrestricted
= i
;
4492 this->shares
.swap(new_shares
);
4493 assert(!this->shares
.empty() && this->unrestricted
<= (--this->shares
.end())->first
);
4497 * Change share for specified station. By specifying INT_MIN as parameter you
4498 * can erase a share. Newly added flows will be unrestricted.
4499 * @param st Next Hop to be removed.
4500 * @param flow Share to be added or removed.
4502 void FlowStat::ChangeShare(StationID st
, int flow
)
4504 /* We assert only before changing as afterwards the shares can actually
4505 * be empty. In that case the whole flow stat must be deleted then. */
4506 assert(!this->shares
.empty());
4508 uint removed_shares
= 0;
4509 uint added_shares
= 0;
4510 uint last_share
= 0;
4511 SharesMap new_shares
;
4512 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4513 if (it
->second
== st
) {
4515 uint share
= it
->first
- last_share
;
4516 if (flow
== INT_MIN
|| (uint
)(-flow
) >= share
) {
4517 removed_shares
+= share
;
4518 if (it
->first
<= this->unrestricted
) this->unrestricted
-= share
;
4519 if (flow
!= INT_MIN
) flow
+= share
;
4520 last_share
= it
->first
;
4521 continue; // remove the whole share
4523 removed_shares
+= (uint
)(-flow
);
4525 added_shares
+= (uint
)(flow
);
4527 if (it
->first
<= this->unrestricted
) this->unrestricted
+= flow
;
4529 /* If we don't continue above the whole flow has been added or
4533 new_shares
[it
->first
+ added_shares
- removed_shares
] = it
->second
;
4534 last_share
= it
->first
;
4537 new_shares
[last_share
+ (uint
)flow
] = st
;
4538 if (this->unrestricted
< last_share
) {
4539 this->ReleaseShare(st
);
4541 this->unrestricted
+= flow
;
4544 this->shares
.swap(new_shares
);
4548 * Restrict a flow by moving it to the end of the map and decreasing the amount
4549 * of unrestricted flow.
4550 * @param st Station of flow to be restricted.
4552 void FlowStat::RestrictShare(StationID st
)
4554 assert(!this->shares
.empty());
4556 uint last_share
= 0;
4557 SharesMap new_shares
;
4558 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4560 if (it
->first
> this->unrestricted
) return; // Not present or already restricted.
4561 if (it
->second
== st
) {
4562 flow
= it
->first
- last_share
;
4563 this->unrestricted
-= flow
;
4565 new_shares
[it
->first
] = it
->second
;
4568 new_shares
[it
->first
- flow
] = it
->second
;
4570 last_share
= it
->first
;
4572 if (flow
== 0) return;
4573 new_shares
[last_share
+ flow
] = st
;
4574 this->shares
.swap(new_shares
);
4575 assert(!this->shares
.empty());
4579 * Release ("unrestrict") a flow by moving it to the begin of the map and
4580 * increasing the amount of unrestricted flow.
4581 * @param st Station of flow to be released.
4583 void FlowStat::ReleaseShare(StationID st
)
4585 assert(!this->shares
.empty());
4587 uint next_share
= 0;
4589 for (SharesMap::reverse_iterator
it(this->shares
.rbegin()); it
!= this->shares
.rend(); ++it
) {
4590 if (it
->first
< this->unrestricted
) return; // Note: not <= as the share may hit the limit.
4592 flow
= next_share
- it
->first
;
4593 this->unrestricted
+= flow
;
4596 if (it
->first
== this->unrestricted
) return; // !found -> Limit not hit.
4597 if (it
->second
== st
) found
= true;
4599 next_share
= it
->first
;
4601 if (flow
== 0) return;
4602 SharesMap new_shares
;
4603 new_shares
[flow
] = st
;
4604 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4605 if (it
->second
!= st
) {
4606 new_shares
[flow
+ it
->first
] = it
->second
;
4611 this->shares
.swap(new_shares
);
4612 assert(!this->shares
.empty());
4616 * Scale all shares from link graph's runtime to monthly values.
4617 * @param runtime Time the link graph has been running without compression.
4618 * @pre runtime must be greater than 0 as we don't want infinite flow values.
4620 void FlowStat::ScaleToMonthly(uint runtime
)
4622 assert(runtime
> 0);
4623 SharesMap new_shares
;
4625 for (SharesMap::iterator i
= this->shares
.begin(); i
!= this->shares
.end(); ++i
) {
4626 share
= max(share
+ 1, i
->first
* 30 / runtime
);
4627 new_shares
[share
] = i
->second
;
4628 if (this->unrestricted
== i
->first
) this->unrestricted
= share
;
4630 this->shares
.swap(new_shares
);
4634 * Add some flow from "origin", going via "via".
4635 * @param origin Origin of the flow.
4636 * @param via Next hop.
4637 * @param flow Amount of flow to be added.
4639 void FlowStatMap::AddFlow(StationID origin
, StationID via
, uint flow
)
4641 FlowStatMap::iterator origin_it
= this->find(origin
);
4642 if (origin_it
== this->end()) {
4643 this->insert(std::make_pair(origin
, FlowStat(via
, flow
)));
4645 origin_it
->second
.ChangeShare(via
, flow
);
4646 assert(!origin_it
->second
.GetShares()->empty());
4651 * Pass on some flow, remembering it as invalid, for later subtraction from
4652 * locally consumed flow. This is necessary because we can't have negative
4653 * flows and we don't want to sort the flows before adding them up.
4654 * @param origin Origin of the flow.
4655 * @param via Next hop.
4656 * @param flow Amount of flow to be passed.
4658 void FlowStatMap::PassOnFlow(StationID origin
, StationID via
, uint flow
)
4660 FlowStatMap::iterator prev_it
= this->find(origin
);
4661 if (prev_it
== this->end()) {
4662 FlowStat
fs(via
, flow
);
4663 fs
.AppendShare(INVALID_STATION
, flow
);
4664 this->insert(std::make_pair(origin
, fs
));
4666 prev_it
->second
.ChangeShare(via
, flow
);
4667 prev_it
->second
.ChangeShare(INVALID_STATION
, flow
);
4668 assert(!prev_it
->second
.GetShares()->empty());
4673 * Subtract invalid flows from locally consumed flow.
4674 * @param self ID of own station.
4676 void FlowStatMap::FinalizeLocalConsumption(StationID self
)
4678 for (FlowStatMap::iterator i
= this->begin(); i
!= this->end(); ++i
) {
4679 FlowStat
&fs
= i
->second
;
4680 uint local
= fs
.GetShare(INVALID_STATION
);
4681 if (local
> INT_MAX
) { // make sure it fits in an int
4682 fs
.ChangeShare(self
, -INT_MAX
);
4683 fs
.ChangeShare(INVALID_STATION
, -INT_MAX
);
4686 fs
.ChangeShare(self
, -(int)local
);
4687 fs
.ChangeShare(INVALID_STATION
, -(int)local
);
4689 /* If the local share is used up there must be a share for some
4690 * remote station. */
4691 assert(!fs
.GetShares()->empty());
4696 * Delete all flows at a station for specific cargo and destination.
4697 * @param via Remote station of flows to be deleted.
4698 * @return IDs of source stations for which the complete FlowStat, not only a
4699 * share, has been erased.
4701 StationIDStack
FlowStatMap::DeleteFlows(StationID via
)
4704 for (FlowStatMap::iterator f_it
= this->begin(); f_it
!= this->end();) {
4705 FlowStat
&s_flows
= f_it
->second
;
4706 s_flows
.ChangeShare(via
, INT_MIN
);
4707 if (s_flows
.GetShares()->empty()) {
4708 ret
.Push(f_it
->first
);
4709 this->erase(f_it
++);
4718 * Restrict all flows at a station for specific cargo and destination.
4719 * @param via Remote station of flows to be restricted.
4721 void FlowStatMap::RestrictFlows(StationID via
)
4723 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4724 it
->second
.RestrictShare(via
);
4729 * Release all flows at a station for specific cargo and destination.
4730 * @param via Remote station of flows to be released.
4732 void FlowStatMap::ReleaseFlows(StationID via
)
4734 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4735 it
->second
.ReleaseShare(via
);
4740 * Get the sum of all flows from this FlowStatMap.
4741 * @return sum of all flows.
4743 uint
FlowStatMap::GetFlow() const
4746 for (FlowStatMap::const_iterator i
= this->begin(); i
!= this->end(); ++i
) {
4747 ret
+= (--(i
->second
.GetShares()->end()))->first
;
4753 * Get the sum of flows via a specific station from this FlowStatMap.
4754 * @param via Remote station to look for.
4755 * @return all flows for 'via' added up.
4757 uint
FlowStatMap::GetFlowVia(StationID via
) const
4760 for (FlowStatMap::const_iterator i
= this->begin(); i
!= this->end(); ++i
) {
4761 ret
+= i
->second
.GetShare(via
);
4767 * Get the sum of flows from a specific station from this FlowStatMap.
4768 * @param from Origin station to look for.
4769 * @return all flows from 'from' added up.
4771 uint
FlowStatMap::GetFlowFrom(StationID from
) const
4773 FlowStatMap::const_iterator i
= this->find(from
);
4774 if (i
== this->end()) return 0;
4775 return (--(i
->second
.GetShares()->end()))->first
;
4779 * Get the flow from a specific station via a specific other station.
4780 * @param from Origin station to look for.
4781 * @param via Remote station to look for.
4782 * @return flow share originating at 'from' and going to 'via'.
4784 uint
FlowStatMap::GetFlowFromVia(StationID from
, StationID via
) const
4786 FlowStatMap::const_iterator i
= this->find(from
);
4787 if (i
== this->end()) return 0;
4788 return i
->second
.GetShare(via
);
4791 extern const TileTypeProcs _tile_type_station_procs
= {
4792 DrawTile_Station
, // draw_tile_proc
4793 GetSlopePixelZ_Station
, // get_slope_z_proc
4794 ClearTile_Station
, // clear_tile_proc
4795 nullptr, // add_accepted_cargo_proc
4796 GetTileDesc_Station
, // get_tile_desc_proc
4797 GetTileTrackStatus_Station
, // get_tile_track_status_proc
4798 ClickTile_Station
, // click_tile_proc
4799 AnimateTile_Station
, // animate_tile_proc
4800 TileLoop_Station
, // tile_loop_proc
4801 ChangeTileOwner_Station
, // change_tile_owner_proc
4802 nullptr, // add_produced_cargo_proc
4803 VehicleEnter_Station
, // vehicle_enter_tile_proc
4804 GetFoundation_Station
, // get_foundation_proc
4805 TerraformTile_Station
, // terraform_tile_proc