4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
10 /** @file station_cmd.cpp Handling of station tiles. */
14 #include "bridge_map.h"
15 #include "cmd_helper.h"
16 #include "viewport_func.h"
17 #include "command_func.h"
19 #include "news_func.h"
24 #include "newgrf_cargo.h"
25 #include "newgrf_debug.h"
26 #include "newgrf_station.h"
27 #include "newgrf_canal.h" /* For the buoy */
28 #include "pathfinder/yapf/yapf_cache.h"
29 #include "road_internal.h" /* For drawing catenary/checking road removal */
30 #include "autoslope.h"
32 #include "strings_func.h"
33 #include "clear_func.h"
34 #include "date_func.h"
35 #include "vehicle_func.h"
36 #include "string_func.h"
37 #include "animated_tile_func.h"
38 #include "elrail_func.h"
39 #include "station_base.h"
40 #include "roadstop_base.h"
41 #include "dock_base.h"
42 #include "newgrf_railtype.h"
43 #include "waypoint_base.h"
44 #include "waypoint_func.h"
46 #include "overlay_cmd.h"
48 #include "core/random_func.hpp"
49 #include "company_base.h"
50 #include "table/airporttile_ids.h"
51 #include "newgrf_airporttiles.h"
52 #include "order_backup.h"
53 #include "newgrf_house.h"
54 #include "company_gui.h"
55 #include "linkgraph/linkgraph_base.h"
56 #include "linkgraph/refresh.h"
57 #include "widgets/station_widget.h"
60 #include "table/strings.h"
61 #include "newgrf_townname.h"
63 #include "safeguards.h"
66 * Static instance of FlowStat::SharesMap.
67 * Note: This instance is created on task start.
68 * Lazy creation on first usage results in a data race between the CDist threads.
70 /* static */ const FlowStat::SharesMap
FlowStat::empty_sharesmap
;
73 * Check whether the given tile is a hangar.///
74 * @param t the tile to of whether it is a hangar.
75 * @pre IsTileType(t, MP_STATION)
76 * @return true if and only if the tile is a hangar.
78 bool IsHangar(TileIndex t
)
80 assert(IsTileType(t
, MP_STATION
));
82 /* If the tile isn't an airport there's no chance it's a hangar. */
83 if (!IsAirport(t
)) return false;
85 const Station
*st
= Station::GetByTile(t
);
86 const AirportSpec
*as
= st
->airport
.GetSpec();
88 for (uint i
= 0; i
< as
->nof_depots
; i
++) {
89 if (st
->airport
.GetHangarTile(i
) == t
) return true;
96 * Look for a station around the given tile area.
97 * @param ta the area to search over
98 * @param closest_station the closest station found so far
99 * @param st to 'return' the found station
100 * @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
103 CommandCost
GetStationAround(TileArea ta
, StationID closest_station
, T
**st
)
105 ta
.tile
-= TileDiffXY(1, 1);
109 /* check around to see if there's any stations there */
110 TILE_AREA_LOOP(tile_cur
, ta
) {
111 if (IsTileType(tile_cur
, MP_STATION
)) {
112 StationID t
= GetStationIndex(tile_cur
);
113 if (!T::IsValidID(t
)) continue;
115 if (closest_station
== INVALID_STATION
) {
117 } else if (closest_station
!= t
) {
118 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
122 *st
= (closest_station
== INVALID_STATION
) ? NULL
: T::Get(closest_station
);
123 return CommandCost();
127 * Function to check whether the given tile matches some criterion.
128 * @param tile the tile to check
129 * @return true if it matches, false otherwise
131 typedef bool (*CMSAMatcher
)(TileIndex tile
);
134 * Counts the numbers of tiles matching a specific type in the area around
135 * @param tile the center tile of the 'count area'
136 * @param width the x size of area around
137 * @param height the y size of area around
138 * @param rad the radius to count around area
139 * @param cmp the comparator/matcher (@see CMSAMatcher)
140 * @return the number of matching tiles around
142 static int CountMapSquareAround(TileIndex tile
, int width
, int height
, int rad
, CMSAMatcher cmp
)
146 for (int dx
= -rad
; dx
<= (width
-1) + rad
; dx
++) {
147 for (int dy
= -rad
; dy
<= (height
-1) + rad
; dy
++) {
148 TileIndex t
= TileAddWrap(tile
, dx
, dy
);
149 if (t
!= INVALID_TILE
&& cmp(t
)) num
++;
157 * Check whether the tile is a mine.
158 * @param tile the tile to investigate.
159 * @return true if and only if the tile is a mine
161 static bool CMSAMine(TileIndex tile
)
164 if (!IsTileType(tile
, MP_INDUSTRY
)) return false;
166 const Industry
*ind
= Industry::GetByTile(tile
);
168 /* No extractive industry */
169 if ((GetIndustrySpec(ind
->type
)->life_type
& INDUSTRYLIFE_EXTRACTIVE
) == 0) return false;
171 for (uint i
= 0; i
< lengthof(ind
->produced_cargo
); i
++) {
172 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
173 * Also the production of passengers and mail is ignored. */
174 if (ind
->produced_cargo
[i
] != CT_INVALID
&&
175 (CargoSpec::Get(ind
->produced_cargo
[i
])->classes
& (CC_LIQUID
| CC_PASSENGERS
| CC_MAIL
)) == 0) {
184 * Check whether the tile is water.
185 * @param tile the tile to investigate.
186 * @return true if and only if the tile is a water tile
188 static bool CMSAWater(TileIndex tile
)
190 return IsTileType(tile
, MP_WATER
) && IsWater(tile
);
194 * Check whether the tile is a tree.
195 * @param tile the tile to investigate.
196 * @return true if and only if the tile is a tree tile
198 static bool CMSATree(TileIndex tile
)
200 return IsTileType(tile
, MP_TREES
);
203 static bool CMSAIndustry(TileIndex tile
)
205 return IsTileType(tile
, MP_INDUSTRY
);
208 #define M(x) ((x) - STR_SV_STNAME)
213 STATIONNAMING_AIRPORT
,
214 STATIONNAMING_OILRIG
,
216 STATIONNAMING_HELIPORT
,
219 /** Information to handle station action 0 property 24 correctly */
220 struct StationNameInformation
{
221 uint32 free_names
; ///< Current bitset of free names (we can remove names).
222 bool *indtypes
; ///< Array of bools telling whether an industry type has been found.
226 * Find a station action 0 property 24 station name, or reduce the
227 * free_names if needed.
228 * @param tile the tile to search
229 * @param user_data the StationNameInformation to base the search on
230 * @return true if the tile contains an industry that has not given
231 * its name to one of the other stations in town.
233 static bool FindNearIndustryName(TileIndex tile
, void *user_data
)
235 /* All already found industry types */
236 StationNameInformation
*sni
= (StationNameInformation
*)user_data
;
237 if (!IsTileType(tile
, MP_INDUSTRY
)) return false;
239 /* If the station name is undefined it means that it doesn't name a station */
240 IndustryType indtype
= GetIndustryType(tile
);
241 if (GetIndustrySpec(indtype
)->station_name
== STR_UNDEFINED
) return false;
243 /* In all cases if an industry that provides a name is found two of
244 * the standard names will be disabled. */
245 sni
->free_names
&= ~(1 << M(STR_SV_STNAME_OILFIELD
) | 1 << M(STR_SV_STNAME_MINES
));
246 return !sni
->indtypes
[indtype
];
249 static bool IsUniqueStationName(const char*);
251 static StringID
GenerateStationName(Station
*st
, TileIndex tile
, int width
, int height
, StationNaming name_class
)
253 static const uint32 _gen_station_name_bits
[] = {
254 0, // STATIONNAMING_RAIL
255 0, // STATIONNAMING_ROAD
256 1U << M(STR_SV_STNAME_AIRPORT
), // STATIONNAMING_AIRPORT
257 0, // STATIONNAMING_OILRIG
258 1U << M(STR_SV_STNAME_DOCKS
), // STATIONNAMING_DOCK
259 1U << M(STR_SV_STNAME_HELIPORT
), // STATIONNAMING_HELIPORT
262 const Town
*t
= st
->town
;
263 uint32 free_names
= UINT32_MAX
;
265 bool indtypes
[NUM_INDUSTRYTYPES
];
266 memset(indtypes
, 0, sizeof(indtypes
));
269 FOR_ALL_STATIONS(s
) {
270 if (s
!= st
&& s
->town
== t
) {
271 if (s
->indtype
!= IT_INVALID
) {
272 indtypes
[s
->indtype
] = true;
273 StringID name
= GetIndustrySpec(s
->indtype
)->station_name
;
274 if (name
!= STR_UNDEFINED
) {
275 /* Filter for other industry types with the same name */
276 for (IndustryType it
= 0; it
< NUM_INDUSTRYTYPES
; it
++) {
277 const IndustrySpec
*indsp
= GetIndustrySpec(it
);
278 if (indsp
->enabled
&& indsp
->station_name
== name
) indtypes
[it
] = true;
283 uint str
= M(s
->string_id
);
285 if (str
== M(STR_SV_STNAME_FOREST
)) {
286 str
= M(STR_SV_STNAME_WOODS
);
288 ClrBit(free_names
, str
);
293 TileIndex indtile
= tile
;
294 StationNameInformation sni
= { free_names
, indtypes
};
296 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
297 free_names
= sni
.free_names
;
299 /* check default names */
300 uint32 tmp
= free_names
& _gen_station_name_bits
[name_class
];
301 if (tmp
!= 0) return STR_SV_STNAME
+ FindFirstBit(tmp
);
303 /* check industry >>variable names<< */
304 for (int dx
= -4; dx
<= (width
-1) + 4; dx
++) {
305 for (int dy
= -4; dy
<= (height
-1) + 4; dy
++) {
306 if (CMSAIndustry(TILE_MASK(tile
+ TileDiffXY(dx
, dy
)))) {
309 // Get town name (code mostly stolen from FormatString)
310 const Industry
*ind
= Industry::GetByTile(tile
+ TileDiffXY(dx
, dy
));
311 const Town
*ind_t
= ind
->town
;
314 temp
[0] = ind_t
->townnameparts
;
315 StringParameters
tmp_params(temp
);
316 uint32 grfid
= ind_t
->townnamegrfid
;
318 if (ind_t
->name
!= NULL
) {
319 strecpy(buf
, ind_t
->name
, lastof(buf
));
320 } else if (grfid
== 0) {
321 /* Original town name */
322 GetStringWithArgs(buf
, ind_t
->townnametype
, &tmp_params
, lastof(buf
));
324 /* Newgrf town name */
325 if (GetGRFTownName(grfid
) != NULL
) {
326 /* The grf is loaded */
327 GRFTownNameGenerate(buf
, ind_t
->townnamegrfid
, ind_t
->townnametype
, ind_t
->townnameparts
, lastof(buf
));
329 /* Fallback to english original */
330 GetStringWithArgs(buf
, SPECSTR_TOWNNAME_ENGLISH
, &tmp_params
, lastof(buf
));
333 // End of get town name
336 strecat(buf
, " ", lastof(buf
));
339 GetString(buf
+strlen(buf
), (GetIndustrySpec(ind
->type
))->name
, lastof(buf
));
343 if (IsUniqueStationName(buf
)) {
345 st
->name
= stredup(buf
);
352 /* check close enough to town to get central as name? */
353 if (DistanceMax(tile
, t
->xy
) < 8) {
354 if (HasBit(free_names
, M(STR_SV_STNAME
))) return STR_SV_STNAME
;
356 if (HasBit(free_names
, M(STR_SV_STNAME_CENTRAL
))) return STR_SV_STNAME_CENTRAL
;
360 if (HasBit(free_names
, M(STR_SV_STNAME_LAKESIDE
)) &&
361 DistanceFromEdge(tile
) < 20 &&
362 CountMapSquareAround(tile
, width
, height
, 3, CMSAWater
) >= 5) {
363 return STR_SV_STNAME_LAKESIDE
;
367 if (HasBit(free_names
, M(STR_SV_STNAME_WOODS
)) && (
368 CountMapSquareAround(tile
, width
, height
, 3, CMSATree
) >= 8 ||
369 CountMapSquareAround(tile
, width
, height
, 3, IsTileForestIndustry
) >= 2)
371 return _settings_game
.game_creation
.landscape
== LT_TROPIC
? STR_SV_STNAME_FOREST
: STR_SV_STNAME_WOODS
;
374 /* check elevation compared to town */
375 int z
= GetTileZ(tile
);
376 int z2
= GetTileZ(t
->xy
);
378 if (HasBit(free_names
, M(STR_SV_STNAME_VALLEY
))) return STR_SV_STNAME_VALLEY
;
380 if (HasBit(free_names
, M(STR_SV_STNAME_HEIGHTS
))) return STR_SV_STNAME_HEIGHTS
;
383 /* check direction compared to town */
384 static const int8 _direction_and_table
[] = {
385 ~( (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
386 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
387 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
388 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) ),
391 free_names
&= _direction_and_table
[
392 (TileX(tile
) < TileX(t
->xy
)) +
393 (TileY(tile
) < TileY(t
->xy
)) * 2];
395 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));
396 return (tmp
== 0) ? STR_SV_STNAME_FALLBACK
: (STR_SV_STNAME
+ FindFirstBit(tmp
));
401 * Find the closest deleted station of the current company
402 * @param tile the tile to search from.
403 * @return the closest station or NULL if too far.
405 static Station
*GetClosestDeletedStation(TileIndex tile
)
408 Station
*best_station
= NULL
;
411 FOR_ALL_STATIONS(st
) {
412 if (!st
->IsInUse() && st
->owner
== _current_company
) {
413 uint cur_dist
= DistanceManhattan(tile
, st
->xy
);
415 if (cur_dist
< threshold
) {
416 threshold
= cur_dist
;
426 void Station::GetTileArea(TileArea
*ta
, StationType type
) const
430 *ta
= this->train_station
;
433 case STATION_AIRPORT
:
438 *ta
= this->truck_station
;
442 *ta
= this->bus_station
;
447 *ta
= this->dock_station
;
450 default: NOT_REACHED();
458 * Update the virtual coords needed to draw the station sign.
460 void Station::UpdateVirtCoord()
462 Point pt
= RemapCoords2(TileX(this->xy
) * TILE_SIZE
, TileY(this->xy
) * TILE_SIZE
);
464 pt
.y
-= 32 * ZOOM_LVL_BASE
;
465 if ((this->facilities
& FACIL_AIRPORT
) && this->airport
.type
== AT_OILRIG
) pt
.y
-= 16 * ZOOM_LVL_BASE
;
467 SetDParam(0, this->index
);
468 SetDParam(1, this->facilities
);
469 this->sign
.UpdatePosition(pt
.x
, pt
.y
, STR_VIEWPORT_STATION
);
471 SetWindowDirty(WC_STATION_VIEW
, this->index
);
474 /** Update the virtual coords needed to draw the station sign for all stations. */
475 void UpdateAllStationVirtCoords()
479 FOR_ALL_BASE_STATIONS(st
) {
480 st
->UpdateVirtCoord();
485 * Get a mask of the cargo types that the station accepts.
486 * @param st Station to query
487 * @return the expected mask
489 static uint
GetAcceptanceMask(const Station
*st
)
493 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
494 if (HasBit(st
->goods
[i
].status
, GoodsEntry::GES_ACCEPTANCE
)) mask
|= 1 << i
;
500 * Items contains the two cargo names that are to be accepted or rejected.
501 * msg is the string id of the message to display.
503 static void ShowRejectOrAcceptNews(const Station
*st
, uint num_items
, CargoID
*cargo
, StringID msg
)
505 for (uint i
= 0; i
< num_items
; i
++) {
506 SetDParam(i
+ 1, CargoSpec::Get(cargo
[i
])->name
);
509 SetDParam(0, st
->index
);
510 AddNewsItem(msg
, NT_ACCEPTANCE
, NF_INCOLOUR
| NF_SMALL
, NR_STATION
, st
->index
);
514 * Get the cargo types being produced around the tile (in a rectangle).
515 * @param tile Northtile of area
516 * @param w X extent of the area
517 * @param h Y extent of the area
518 * @param rad Search radius in addition to the given area
520 CargoArray
GetProductionAroundTiles(TileIndex tile
, int w
, int h
, int rad
)
527 /* expand the region by rad tiles on each side
528 * while making sure that we remain inside the board. */
529 int x2
= min(x
+ w
+ rad
, MapSizeX());
530 int x1
= max(x
- rad
, 0);
532 int y2
= min(y
+ h
+ rad
, MapSizeY());
533 int y1
= max(y
- rad
, 0);
540 TileArea
ta(TileXY(x1
, y1
), TileXY(x2
- 1, y2
- 1));
542 /* Loop over all tiles to get the produced cargo of
543 * everything except industries */
544 TILE_AREA_LOOP(tile
, ta
) AddProducedCargo(tile
, produced
);
546 /* Loop over the industries. They produce cargo for
547 * anything that is within 'rad' from their bounding
548 * box. As such if you have e.g. a oil well the tile
549 * area loop might not hit an industry tile while
550 * the industry would produce cargo for the station.
553 FOR_ALL_INDUSTRIES(i
) {
554 if (!ta
.Intersects(i
->location
)) continue;
556 for (uint j
= 0; j
< lengthof(i
->produced_cargo
); j
++) {
557 CargoID cargo
= i
->produced_cargo
[j
];
558 if (cargo
!= CT_INVALID
) produced
[cargo
]++;
566 * Get the acceptance of cargoes around the tile in 1/8.
567 * @param tile Center of the search area
568 * @param w X extent of area
569 * @param h Y extent of area
570 * @param rad Search radius in addition to given area
571 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be NULL
573 CargoArray
GetAcceptanceAroundTiles(TileIndex tile
, int w
, int h
, int rad
, uint32
*always_accepted
)
575 CargoArray acceptance
;
576 if (always_accepted
!= NULL
) *always_accepted
= 0;
581 /* expand the region by rad tiles on each side
582 * while making sure that we remain inside the board. */
583 int x2
= min(x
+ w
+ rad
, MapSizeX());
584 int y2
= min(y
+ h
+ rad
, MapSizeY());
585 int x1
= max(x
- rad
, 0);
586 int y1
= max(y
- rad
, 0);
593 for (int yc
= y1
; yc
!= y2
; yc
++) {
594 for (int xc
= x1
; xc
!= x2
; xc
++) {
595 TileIndex tile
= TileXY(xc
, yc
);
596 AddAcceptedCargo(tile
, acceptance
, always_accepted
);
604 * Update the acceptance for a station.
605 * @param st Station to update
606 * @param show_msg controls whether to display a message that acceptance was changed.
608 void UpdateStationAcceptance(Station
*st
, bool show_msg
)
610 /* old accepted goods types */
611 uint old_acc
= GetAcceptanceMask(st
);
613 /* And retrieve the acceptance. */
614 CargoArray acceptance
;
615 if (!st
->rect
.IsEmpty()) {
616 acceptance
= GetAcceptanceAroundTiles(
617 TileXY(st
->rect
.left
, st
->rect
.top
),
618 st
->rect
.right
- st
->rect
.left
+ 1,
619 st
->rect
.bottom
- st
->rect
.top
+ 1,
620 st
->GetCatchmentRadius(),
625 /* Adjust in case our station only accepts fewer kinds of goods */
626 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
627 uint amt
= acceptance
[i
];
629 /* Make sure the station can accept the goods type. */
630 bool is_passengers
= IsCargoInClass(i
, CC_PASSENGERS
);
631 if ((!is_passengers
&& !(st
->facilities
& ~FACIL_BUS_STOP
)) ||
632 (is_passengers
&& !(st
->facilities
& ~FACIL_TRUCK_STOP
))) {
636 GoodsEntry
&ge
= st
->goods
[i
];
637 SB(ge
.status
, GoodsEntry::GES_ACCEPTANCE
, 1, amt
>= 8);
638 if (LinkGraph::IsValidID(ge
.link_graph
)) {
639 (*LinkGraph::Get(ge
.link_graph
))[ge
.node
].SetDemand(amt
/ 8);
643 /* Only show a message in case the acceptance was actually changed. */
644 uint new_acc
= GetAcceptanceMask(st
);
645 if (old_acc
== new_acc
) return;
647 /* show a message to report that the acceptance was changed? */
648 if (show_msg
&& st
->owner
== _local_company
&& st
->IsInUse()) {
649 /* List of accept and reject strings for different number of
651 static const StringID accept_msg
[] = {
652 STR_NEWS_STATION_NOW_ACCEPTS_CARGO
,
653 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO
,
655 static const StringID reject_msg
[] = {
656 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO
,
657 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO
,
660 /* Array of accepted and rejected cargo types */
661 CargoID accepts
[2] = { CT_INVALID
, CT_INVALID
};
662 CargoID rejects
[2] = { CT_INVALID
, CT_INVALID
};
666 /* Test each cargo type to see if its acceptance has changed */
667 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
668 if (HasBit(new_acc
, i
)) {
669 if (!HasBit(old_acc
, i
) && num_acc
< lengthof(accepts
)) {
670 /* New cargo is accepted */
671 accepts
[num_acc
++] = i
;
674 if (HasBit(old_acc
, i
) && num_rej
< lengthof(rejects
)) {
675 /* Old cargo is no longer accepted */
676 rejects
[num_rej
++] = i
;
681 /* Show news message if there are any changes */
682 if (num_acc
> 0) ShowRejectOrAcceptNews(st
, num_acc
, accepts
, accept_msg
[num_acc
- 1]);
683 if (num_rej
> 0) ShowRejectOrAcceptNews(st
, num_rej
, rejects
, reject_msg
[num_rej
- 1]);
686 /* redraw the station view since acceptance changed */
687 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ACCEPT_RATING_LIST
);
688 if (Overlays::Instance()->HasStation(st
)) st
->MarkAcceptanceTilesDirty();
691 static void UpdateStationSignCoord(BaseStation
*st
)
693 const StationRect
*r
= &st
->rect
;
695 if (r
->IsEmpty()) return; // no tiles belong to this station
697 /* clamp sign coord to be inside the station rect */
698 st
->xy
= TileXY(ClampU(TileX(st
->xy
), r
->left
, r
->right
), ClampU(TileY(st
->xy
), r
->top
, r
->bottom
));
699 st
->UpdateVirtCoord();
701 if (!Station::IsExpected(st
)) return;
702 Station
*full_station
= Station::From(st
);
703 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
704 LinkGraphID lg
= full_station
->goods
[c
].link_graph
;
705 if (!LinkGraph::IsValidID(lg
)) continue;
706 (*LinkGraph::Get(lg
))[full_station
->goods
[c
].node
].UpdateLocation(st
->xy
);
711 * Common part of building various station parts and possibly attaching them to an existing one.
712 * @param [in,out] st Station to attach to
713 * @param flags Command flags
714 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
715 * @param area Area occupied by the new part
716 * @param name_class Station naming class to use to generate the new station's name
717 * @return Command error that occurred, if any
719 static CommandCost
BuildStationPart(Station
**st
, DoCommandFlag flags
, bool reuse
, TileArea area
, StationNaming name_class
)
721 /* Find a deleted station close to us */
722 if (*st
== NULL
&& reuse
) *st
= GetClosestDeletedStation(area
.tile
);
725 if ((*st
)->owner
!= _current_company
) {
726 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION
);
729 CommandCost ret
= (*st
)->rect
.BeforeAddRect(area
.tile
, area
.w
, area
.h
, StationRect::ADD_TEST
);
730 if (ret
.Failed()) return ret
;
732 /* allocate and initialize new station */
733 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING
);
735 if (flags
& DC_EXEC
) {
736 *st
= new Station(area
.tile
);
738 (*st
)->town
= ClosestTownFromTile(area
.tile
, UINT_MAX
);
739 (*st
)->string_id
= GenerateStationName(*st
, area
.tile
, area
.w
, area
.h
, name_class
);
741 if (Company::IsValidID(_current_company
)) {
742 SetBit((*st
)->town
->have_ratings
, _current_company
);
746 return CommandCost();
750 * This is called right after a station was deleted.
751 * It checks if the whole station is free of substations, and if so, the station will be
752 * deleted after a little while.
755 static void DeleteStationIfEmpty(BaseStation
*st
)
757 if (!st
->IsInUse()) {
758 if (Station::IsExpected(st
)) Overlays::Instance()->RemoveStation((Station
*)st
);
760 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
762 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
763 UpdateStationSignCoord(st
);
765 if (Station::IsExpected(st
)) {
766 MarkWholeScreenDirty();
770 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
);
773 * Checks if the given tile is buildable, flat and has a certain height.
774 * @param tile TileIndex to check.
775 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
776 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
777 * @param allow_steep Whether steep slopes are allowed.
778 * @param check_bridge Check for the existence of a bridge.
779 * @return The cost in case of success, or an error code if it failed.
781 CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
= true)
783 if (check_bridge
&& IsBridgeAbove(tile
)) {
784 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
787 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
788 if (ret
.Failed()) return ret
;
791 Slope tileh
= GetTileSlope(tile
, &z
);
793 /* Prohibit building if
794 * 1) The tile is "steep" (i.e. stretches two height levels).
795 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
797 if ((!allow_steep
&& IsSteepSlope(tileh
)) ||
798 ((!_settings_game
.construction
.build_on_slopes
) && tileh
!= SLOPE_FLAT
)) {
799 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
802 CommandCost
cost(EXPENSES_CONSTRUCTION
);
803 int flat_z
= z
+ GetSlopeMaxZ(tileh
);
804 if (tileh
!= SLOPE_FLAT
) {
805 /* Forbid building if the tile faces a slope in a invalid direction. */
806 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
!= DIAGDIR_END
; dir
++) {
807 if (HasBit(invalid_dirs
, dir
) && !CanBuildDepotByTileh(dir
, tileh
)) {
808 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
811 cost
.AddCost(_price
[PR_BUILD_FOUNDATION
]);
814 /* The level of this tile must be equal to allowed_z. */
818 } else if (allowed_z
!= flat_z
) {
819 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
826 * Tries to clear the given area.
827 * @param tile_area Area to check.
828 * @param flags Operation to perform.
829 * @return The cost in case of success, or an error code if it failed.
831 CommandCost
CheckFlatLand(TileArea tile_area
, DoCommandFlag flags
)
833 CommandCost
cost(EXPENSES_CONSTRUCTION
);
836 TILE_AREA_LOOP(tile_cur
, tile_area
) {
837 CommandCost ret
= CheckBuildableTile(tile_cur
, 0, allowed_z
, true);
838 if (ret
.Failed()) return ret
;
841 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
842 if (ret
.Failed()) return ret
;
850 * Checks given water area for obstacles.
851 * @param tile_area Area to check.
852 * @param flags Operation to perform.
853 * @return The cost in case of success, or an error code if it failed.
855 CommandCost
CheckClearWater(TileArea tile_area
, DoCommandFlag flags
)
857 CommandCost
cost(EXPENSES_CONSTRUCTION
);
859 TILE_AREA_LOOP(tile_cur
, tile_area
) {
860 if (!IsWaterTile(tile_cur
) || GetTileSlope(tile_cur
) != SLOPE_FLAT
) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
861 if (IsBridgeAbove(tile_cur
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
862 CommandCost ret
= EnsureNoVehicleOnGround(tile_cur
);
863 if (ret
.Failed()) return ret
;
870 * Checks if a rail station can be built at the given area.
871 * @param tile_area Area to check.
872 * @param flags Operation to perform.
873 * @param axis Rail station axis.
874 * @param station StationID to be queried and returned if available.
875 * @param rt The rail type to check for (overbuilding rail stations over rail).
876 * @param affected_vehicles List of trains with PBS reservations on the tiles
877 * @param spec_class Station class.
878 * @param spec_index Index into the station class.
879 * @param plat_len Platform length.
880 * @param numtracks Number of platforms.
881 * @return The cost in case of success, or an error code if it failed.
883 static CommandCost
CheckFlatLandRailStation(TileArea tile_area
, DoCommandFlag flags
, Axis axis
, StationID
*station
, RailType rt
, SmallVector
<Train
*, 4> &affected_vehicles
, StationClassID spec_class
, byte spec_index
, byte plat_len
, byte numtracks
)
885 CommandCost
cost(EXPENSES_CONSTRUCTION
);
887 uint invalid_dirs
= 5 << axis
;
889 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
890 bool slope_cb
= statspec
!= NULL
&& HasBit(statspec
->callback_mask
, CBM_STATION_SLOPE_CHECK
);
892 TILE_AREA_LOOP(tile_cur
, tile_area
) {
893 CommandCost ret
= CheckBuildableTile(tile_cur
, invalid_dirs
, allowed_z
, false);
894 if (ret
.Failed()) return ret
;
898 /* Do slope check if requested. */
899 ret
= PerformStationTileSlopeCheck(tile_area
.tile
, tile_cur
, statspec
, axis
, plat_len
, numtracks
);
900 if (ret
.Failed()) return ret
;
903 /* if station is set, then we have special handling to allow building on top of already existing stations.
904 * so station points to INVALID_STATION if we can build on any station.
905 * Or it points to a station if we're only allowed to build on exactly that station. */
906 if (station
!= NULL
&& IsTileType(tile_cur
, MP_STATION
)) {
907 if (!IsRailStation(tile_cur
)) {
908 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
910 StationID st
= GetStationIndex(tile_cur
);
911 if (*station
== INVALID_STATION
) {
913 } else if (*station
!= st
) {
914 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
918 /* Rail type is only valid when building a railway station; if station to
919 * build isn't a rail station it's INVALID_RAILTYPE. */
920 if (rt
!= INVALID_RAILTYPE
&&
921 IsPlainRailTile(tile_cur
) && !HasSignals(tile_cur
) &&
922 HasPowerOnRail(GetRailType(tile_cur
), rt
)) {
923 /* Allow overbuilding if the tile:
924 * - has rail, but no signals
925 * - it has exactly one track
926 * - the track is in line with the station
927 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
929 TrackBits tracks
= GetTrackBits(tile_cur
);
930 Track track
= RemoveFirstTrack(&tracks
);
931 Track expected_track
= HasBit(invalid_dirs
, DIAGDIR_NE
) ? TRACK_X
: TRACK_Y
;
933 if (tracks
== TRACK_BIT_NONE
&& track
== expected_track
) {
934 /* Check for trains having a reservation for this tile. */
935 if (HasBit(GetRailReservationTrackBits(tile_cur
), track
)) {
936 Train
*v
= GetTrainForReservation(tile_cur
, track
);
938 *affected_vehicles
.Append() = v
;
941 CommandCost ret
= DoCommand(tile_cur
, 0, track
, flags
, CMD_REMOVE_SINGLE_RAIL
);
942 if (ret
.Failed()) return ret
;
944 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
948 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
949 if (ret
.Failed()) return ret
;
958 * Checks if a road stop can be built at the given tile.
959 * @param tile_area Area to check.
960 * @param flags Operation to perform.
961 * @param invalid_dirs Prohibited directions (set of DiagDirections).
962 * @param is_drive_through True if trying to build a drive-through station.
963 * @param is_truck_stop True when building a truck stop, false otherwise.
964 * @param axis Axis of a drive-through road stop.
965 * @param station StationID to be queried and returned if available.
966 * @param rts Road types to build.
967 * @return The cost in case of success, or an error code if it failed.
969 static CommandCost
CheckFlatLandRoadStop(TileArea tile_area
, DoCommandFlag flags
, uint invalid_dirs
, bool is_drive_through
, bool is_truck_stop
, Axis axis
, StationID
*station
, RoadTypes rts
)
971 CommandCost
cost(EXPENSES_CONSTRUCTION
);
974 TILE_AREA_LOOP(cur_tile
, tile_area
) {
975 CommandCost ret
= CheckBuildableTile(cur_tile
, invalid_dirs
, allowed_z
, !is_drive_through
);
976 if (ret
.Failed()) return ret
;
979 /* If station is set, then we have special handling to allow building on top of already existing stations.
980 * Station points to INVALID_STATION if we can build on any station.
981 * Or it points to a station if we're only allowed to build on exactly that station. */
982 if (station
!= NULL
&& IsTileType(cur_tile
, MP_STATION
)) {
983 if (!IsRoadStop(cur_tile
)) {
984 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
986 if (is_truck_stop
!= IsTruckStop(cur_tile
) ||
987 is_drive_through
!= IsDriveThroughStopTile(cur_tile
)) {
988 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
990 /* Drive-through station in the wrong direction. */
991 if (is_drive_through
&& IsDriveThroughStopTile(cur_tile
) && DiagDirToAxis(GetRoadStopDir(cur_tile
)) != axis
){
992 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
994 StationID st
= GetStationIndex(cur_tile
);
995 if (*station
== INVALID_STATION
) {
997 } else if (*station
!= st
) {
998 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
1002 bool build_over_road
= is_drive_through
&& IsNormalRoadTile(cur_tile
);
1003 /* Road bits in the wrong direction. */
1004 RoadBits rb
= IsNormalRoadTile(cur_tile
) ? GetAllRoadBits(cur_tile
) : ROAD_NONE
;
1005 if (build_over_road
&& (rb
& (axis
== AXIS_X
? ROAD_Y
: ROAD_X
)) != 0) {
1006 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1007 switch (CountBits(rb
)) {
1009 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
1012 if (rb
== ROAD_X
|| rb
== ROAD_Y
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
1013 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER
);
1016 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION
);
1020 RoadTypes cur_rts
= IsNormalRoadTile(cur_tile
) ? GetRoadTypes(cur_tile
) : ROADTYPES_NONE
;
1021 uint num_roadbits
= 0;
1022 if (build_over_road
) {
1023 /* There is a road, check if we can build road+tram stop over it. */
1024 if (HasBit(cur_rts
, ROADTYPE_ROAD
)) {
1025 Owner road_owner
= GetRoadOwner(cur_tile
, ROADTYPE_ROAD
);
1026 if (road_owner
== OWNER_TOWN
) {
1027 if (!_settings_game
.construction
.road_stop_on_town_road
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD
);
1028 } else if (!_settings_game
.construction
.road_stop_on_competitor_road
&& road_owner
!= OWNER_NONE
) {
1029 CommandCost ret
= CheckOwnership(road_owner
);
1030 if (ret
.Failed()) return ret
;
1032 num_roadbits
+= CountBits(GetRoadBits(cur_tile
, ROADTYPE_ROAD
));
1035 /* There is a tram, check if we can build road+tram stop over it. */
1036 if (HasBit(cur_rts
, ROADTYPE_TRAM
)) {
1037 Owner tram_owner
= GetRoadOwner(cur_tile
, ROADTYPE_TRAM
);
1038 if (Company::IsValidID(tram_owner
) &&
1039 (!_settings_game
.construction
.road_stop_on_competitor_road
||
1040 /* Disallow breaking end-of-line of someone else
1041 * so trams can still reverse on this tile. */
1042 HasExactlyOneBit(GetRoadBits(cur_tile
, ROADTYPE_TRAM
)))) {
1043 CommandCost ret
= CheckOwnership(tram_owner
);
1044 if (ret
.Failed()) return ret
;
1046 num_roadbits
+= CountBits(GetRoadBits(cur_tile
, ROADTYPE_TRAM
));
1049 /* Take into account existing roadbits. */
1052 ret
= DoCommand(cur_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
1053 if (ret
.Failed()) return ret
;
1057 uint roadbits_to_build
= CountBits(rts
) * 2 - num_roadbits
;
1058 cost
.AddCost(_price
[PR_BUILD_ROAD
] * roadbits_to_build
);
1065 /** /// Checks if an airport can be built at the given area.
1066 * @param tile_area Area to check.
1067 * @param flags Operation to perform.
1068 * @param station StationID of airport allowed in search area.
1069 * @return The cost in case of success, or an error code if it failed.
1071 static CommandCost
CheckFlatLandAirport(TileArea tile_area
, DoCommandFlag flags
, StationID
*station
)
1073 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1076 TILE_AREA_LOOP(tile_cur
, tile_area
) {
1077 CommandCost ret
= CheckBuildableTile(tile_cur
, 0, allowed_z
, true);
1078 if (ret
.Failed()) return ret
;
1081 /* if station is set, then allow building on top of an already
1082 * existing airport, either the one in *station if it is not
1083 * INVALID_STATION, or anyone otherwise and store which one
1085 if (station
!= NULL
&& IsTileType(tile_cur
, MP_STATION
)) {
1086 if (!IsAirport(tile_cur
)) {
1087 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
1089 StationID st
= GetStationIndex(tile_cur
);
1090 if (*station
== INVALID_STATION
) {
1092 } else if (*station
!= st
) {
1093 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
1097 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
1098 if (ret
.Failed()) return ret
;
1107 * Check whether we can expand the rail part of the given station.
1108 * @param st the station to expand
1109 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1110 * @param axis the axis of the newly build rail
1111 * @return Succeeded or failed command.
1113 CommandCost
CanExpandRailStation(const BaseStation
*st
, TileArea
&new_ta
, Axis axis
)
1115 TileArea cur_ta
= st
->train_station
;
1117 /* determine new size of train station region.. */
1118 int x
= min(TileX(cur_ta
.tile
), TileX(new_ta
.tile
));
1119 int y
= min(TileY(cur_ta
.tile
), TileY(new_ta
.tile
));
1120 new_ta
.w
= max(TileX(cur_ta
.tile
) + cur_ta
.w
, TileX(new_ta
.tile
) + new_ta
.w
) - x
;
1121 new_ta
.h
= max(TileY(cur_ta
.tile
) + cur_ta
.h
, TileY(new_ta
.tile
) + new_ta
.h
) - y
;
1122 new_ta
.tile
= TileXY(x
, y
);
1124 /* make sure the final size is not too big. */
1125 if (new_ta
.w
> _settings_game
.station
.station_spread
|| new_ta
.h
> _settings_game
.station
.station_spread
) {
1126 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1129 return CommandCost();
1132 static inline byte
*CreateSingle(byte
*layout
, int n
)
1135 do *layout
++ = 0; while (--i
);
1136 layout
[((n
- 1) >> 1) - n
] = 2;
1140 static inline byte
*CreateMulti(byte
*layout
, int n
, byte b
)
1143 do *layout
++ = b
; while (--i
);
1146 layout
[n
- 1 - n
] = 0;
1152 * Create the station layout for the given number of tracks and platform length.
1153 * @param layout The layout to write to.
1154 * @param numtracks The number of tracks to write.
1155 * @param plat_len The length of the platforms.
1156 * @param statspec The specification of the station to (possibly) get the layout from.
1158 void GetStationLayout(byte
*layout
, int numtracks
, int plat_len
, const StationSpec
*statspec
)
1160 if (statspec
!= NULL
&& statspec
->lengths
>= plat_len
&&
1161 statspec
->platforms
[plat_len
- 1] >= numtracks
&&
1162 statspec
->layouts
[plat_len
- 1][numtracks
- 1]) {
1163 /* Custom layout defined, follow it. */
1164 memcpy(layout
, statspec
->layouts
[plat_len
- 1][numtracks
- 1],
1165 plat_len
* numtracks
);
1169 if (plat_len
== 1) {
1170 CreateSingle(layout
, numtracks
);
1172 if (numtracks
& 1) layout
= CreateSingle(layout
, plat_len
);
1175 while (--numtracks
>= 0) {
1176 layout
= CreateMulti(layout
, plat_len
, 4);
1177 layout
= CreateMulti(layout
, plat_len
, 6);
1183 * Find a nearby station that joins this station.
1184 * /// @tparam T the class to find a station for
1185 * @param existing_station an existing station we build over
1186 * @param station_to_join the station to join to
1187 * @param adjacent whether adjacent stations are allowed
1188 * @param ta the area of the newly build station
1189 * @param st 'return' pointer for the found station
1190 * @param error_message the error message when building a station on top of others
1191 * @return command cost with the error or 'okay'
1194 CommandCost
FindJoiningBaseStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, T
**st
, StringID error_message
)
1196 assert(*st
== NULL
);
1197 bool check_surrounding
= true;
1199 if (_settings_game
.station
.adjacent_stations
) {
1200 if (existing_station
!= INVALID_STATION
) {
1201 if (adjacent
&& existing_station
!= station_to_join
) {
1202 /* You can't build an adjacent station over the top of one that
1203 * already exists. */
1204 return_cmd_error(error_message
);
1206 /* Extend the current station, and don't check whether it will
1207 * be near any other stations. */
1208 *st
= T::GetIfValid(existing_station
);
1209 check_surrounding
= (*st
== NULL
);
1212 /* There's no station here. Don't check the tiles surrounding this
1213 * one if the company wanted to build an adjacent station. */
1214 if (adjacent
) check_surrounding
= false;
1218 if (check_surrounding
) {
1219 /* Make sure there are no similar stations around us. */
1220 CommandCost ret
= GetStationAround(ta
, existing_station
, st
);
1221 if (ret
.Failed()) return ret
;
1225 if (*st
== NULL
&& station_to_join
!= INVALID_STATION
) *st
= T::GetIfValid(station_to_join
);
1227 return CommandCost();
1231 * Find a nearby station that joins this station.
1232 * @param existing_station an existing station we build over
1233 * @param station_to_join the station to join to
1234 * @param adjacent whether adjacent stations are allowed
1235 * @param ta the area of the newly build station
1236 * @param st 'return' pointer for the found station
1237 * @param error_message the error message when building a station on top of others
1238 * @return command cost with the error or 'okay'
1240 static CommandCost
FindJoiningStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, Station
**st
, StringID error_message
= STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST
)
1242 return FindJoiningBaseStation
<Station
>(existing_station
, station_to_join
, adjacent
, ta
, st
, error_message
);
1246 * Find a nearby waypoint that joins this waypoint.
1247 * @param existing_waypoint an existing waypoint we build over
1248 * @param waypoint_to_join the waypoint to join to
1249 * @param adjacent whether adjacent waypoints are allowed
1250 * @param ta the area of the newly build waypoint
1251 * @param wp 'return' pointer for the found waypoint
1252 * @return command cost with the error or 'okay'
1254 CommandCost
FindJoiningWaypoint(StationID existing_waypoint
, StationID waypoint_to_join
, bool adjacent
, TileArea ta
, Waypoint
**wp
)
1256 return FindJoiningBaseStation
<Waypoint
>(existing_waypoint
, waypoint_to_join
, adjacent
, ta
, wp
, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST
);
1260 * Clear platform reservation during station building/removing.
1261 * @param v vehicle which holds reservation
1263 static void FreeTrainReservation(Train
*v
)
1265 FreeTrainTrackReservation(v
);
1266 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(v
->GetVehicleTrackdir()), false);
1268 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(ReverseTrackdir(v
->GetVehicleTrackdir())), false);
1272 * Restore platform reservation during station building/removing.
1273 * @param v vehicle which held reservation
1275 static void RestoreTrainReservation(Train
*v
)
1277 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(v
->GetVehicleTrackdir()), true);
1278 TryPathReserve(v
, true, true);
1280 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(ReverseTrackdir(v
->GetVehicleTrackdir())), true);
1284 * Build rail station
1285 * @param tile_org northern most position of station dragging/placement
1286 * @param flags operation to perform
1287 * @param p1 various bitstuffed elements
1288 * - p1 = (bit 0- 4) - railtype
1289 * - p1 = (bit 5) - orientation (Axis)
1290 * - p1 = (bit 8-15) - number of tracks
1291 * - p1 = (bit 16-23) - platform length
1292 * - p1 = (bit 24) - allow stations directly adjacent to other stations.
1293 * @param p2 various bitstuffed elements
1294 * - p2 = (bit 0- 7) - custom station class
1295 * - p2 = (bit 8-15) - custom station id
1296 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
1297 * @param text unused
1298 * @return the cost of this operation or an error
1300 CommandCost
CmdBuildRailStation(TileIndex tile_org
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1302 /* Unpack parameters */
1303 RailType rt
= Extract
<RailType
, 0, 5>(p1
);
1304 Axis axis
= Extract
<Axis
, 5, 1>(p1
);
1305 byte numtracks
= GB(p1
, 8, 8);
1306 byte plat_len
= GB(p1
, 16, 8);
1307 bool adjacent
= HasBit(p1
, 24);
1309 StationClassID spec_class
= Extract
<StationClassID
, 0, 8>(p2
);
1310 byte spec_index
= GB(p2
, 8, 8);
1311 StationID station_to_join
= GB(p2
, 16, 16);
1313 /* Does the authority allow this? */
1314 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile_org
, flags
);
1315 if (ret
.Failed()) return ret
;
1317 if (!ValParamRailtype(rt
)) return CMD_ERROR
;
1319 /* Check if the given station class is valid */
1320 if ((uint
)spec_class
>= StationClass::GetClassCount() || spec_class
== STAT_CLASS_WAYP
) return CMD_ERROR
;
1321 if (spec_index
>= StationClass::Get(spec_class
)->GetSpecCount()) return CMD_ERROR
;
1322 if (plat_len
== 0 || numtracks
== 0) return CMD_ERROR
;
1325 if (axis
== AXIS_X
) {
1333 bool reuse
= (station_to_join
!= NEW_STATION
);
1334 if (!reuse
) station_to_join
= INVALID_STATION
;
1335 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1337 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1339 if (h_org
> _settings_game
.station
.station_spread
|| w_org
> _settings_game
.station
.station_spread
) return CMD_ERROR
;
1341 /* these values are those that will be stored in train_tile and station_platforms */
1342 TileArea
new_location(tile_org
, w_org
, h_org
);
1344 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1345 StationID est
= INVALID_STATION
;
1346 SmallVector
<Train
*, 4> affected_vehicles
;
1347 /* Clear the land below the station. */
1348 CommandCost cost
= CheckFlatLandRailStation(new_location
, flags
, axis
, &est
, rt
, affected_vehicles
, spec_class
, spec_index
, plat_len
, numtracks
);
1349 if (cost
.Failed()) return cost
;
1350 /* Add construction expenses. */
1351 cost
.AddCost((numtracks
* _price
[PR_BUILD_STATION_RAIL
] + _price
[PR_BUILD_STATION_RAIL_LENGTH
]) * plat_len
);
1352 cost
.AddCost(numtracks
* plat_len
* RailBuildCost(rt
));
1355 ret
= FindJoiningStation(est
, station_to_join
, adjacent
, new_location
, &st
);
1356 if (ret
.Failed()) return ret
;
1358 ret
= BuildStationPart(&st
, flags
, reuse
, new_location
, STATIONNAMING_RAIL
);
1359 if (ret
.Failed()) return ret
;
1361 if (st
!= NULL
&& st
->train_station
.tile
!= INVALID_TILE
) {
1362 CommandCost ret
= CanExpandRailStation(st
, new_location
, axis
);
1363 if (ret
.Failed()) return ret
;
1366 /* Check if we can allocate a custom stationspec to this station */
1367 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
1368 int specindex
= AllocateSpecToStation(statspec
, st
, (flags
& DC_EXEC
) != 0);
1369 if (specindex
== -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS
);
1371 if (statspec
!= NULL
) {
1372 /* Perform NewStation checks */
1374 /* Check if the station size is permitted */
1375 if (HasBit(statspec
->disallowed_platforms
, min(numtracks
- 1, 7)) || HasBit(statspec
->disallowed_lengths
, min(plat_len
- 1, 7))) {
1379 /* Check if the station is buildable */
1380 if (HasBit(statspec
->callback_mask
, CBM_STATION_AVAIL
)) {
1381 uint16 cb_res
= GetStationCallback(CBID_STATION_AVAILABILITY
, 0, 0, statspec
, NULL
, INVALID_TILE
);
1382 if (cb_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(statspec
->grf_prop
.grffile
, CBID_STATION_AVAILABILITY
, cb_res
)) return CMD_ERROR
;
1386 if (flags
& DC_EXEC
) {
1387 TileIndexDiff tile_delta
;
1389 byte numtracks_orig
;
1392 st
->train_station
= new_location
;
1393 st
->AddFacility(FACIL_TRAIN
, new_location
.tile
);
1395 st
->rect
.BeforeAddRect(tile_org
, w_org
, h_org
, StationRect::ADD_TRY
);
1396 st
->catchment
.BeforeAddRect(tile_org
, w_org
, h_org
, CA_TRAIN
);
1398 if (statspec
!= NULL
) {
1399 /* Include this station spec's animation trigger bitmask
1400 * in the station's cached copy. */
1401 st
->cached_anim_triggers
|= statspec
->animation
.triggers
;
1404 tile_delta
= (axis
== AXIS_X
? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1405 track
= AxisToTrack(axis
);
1407 layout_ptr
= AllocaM(byte
, numtracks
* plat_len
);
1408 GetStationLayout(layout_ptr
, numtracks
, plat_len
, statspec
);
1410 numtracks_orig
= numtracks
;
1412 Company
*c
= Company::Get(st
->owner
);
1413 TileIndex tile_track
= tile_org
;
1415 TileIndex tile
= tile_track
;
1418 byte layout
= *layout_ptr
++;
1419 if (IsRailStationTile(tile
) && HasStationReservation(tile
)) {
1420 /* Check for trains having a reservation for this tile. */
1421 Train
*v
= GetTrainForReservation(tile
, AxisToTrack(GetRailStationAxis(tile
)));
1423 *affected_vehicles
.Append() = v
;
1424 FreeTrainReservation(v
);
1428 /* Railtype can change when overbuilding. */
1429 if (IsRailStationTile(tile
)) {
1430 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[GetRailType(tile
)]--;
1431 c
->infrastructure
.station
--;
1434 /* Remove animation if overbuilding */
1435 DeleteAnimatedTile(tile
);
1436 byte old_specindex
= HasStationTileRail(tile
) ? GetCustomStationSpecIndex(tile
) : 0;
1437 MakeRailStation(tile
, st
->owner
, st
->index
, axis
, layout
& ~1, rt
);
1438 /* Free the spec if we overbuild something */
1439 DeallocateSpecFromStation(st
, old_specindex
);
1441 SetCustomStationSpecIndex(tile
, specindex
);
1442 SetStationTileRandomBits(tile
, GB(Random(), 0, 4));
1443 SetAnimationFrame(tile
, 0);
1445 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[rt
]++;
1446 c
->infrastructure
.station
++;
1448 if (statspec
!= NULL
) {
1449 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1450 uint32 platinfo
= GetPlatformInfo(AXIS_X
, GetStationGfx(tile
), plat_len
, numtracks_orig
, plat_len
- w
, numtracks_orig
- numtracks
, false);
1452 /* As the station is not yet completely finished, the station does not yet exist. */
1453 uint16 callback
= GetStationCallback(CBID_STATION_TILE_LAYOUT
, platinfo
, 0, statspec
, NULL
, tile
);
1454 if (callback
!= CALLBACK_FAILED
) {
1456 SetStationGfx(tile
, (callback
& ~1) + axis
);
1458 ErrorUnknownCallbackResult(statspec
->grf_prop
.grffile
->grfid
, CBID_STATION_TILE_LAYOUT
, callback
);
1462 /* Trigger station animation -- after building? */
1463 TriggerStationAnimation(st
, tile
, SAT_BUILT
);
1468 AddTrackToSignalBuffer(tile_track
, track
, _current_company
);
1469 YapfNotifyTrackLayoutChange(tile_track
, track
);
1470 tile_track
+= tile_delta
^ TileDiffXY(1, 1); // perpendicular to tile_delta
1471 } while (--numtracks
);
1473 for (uint i
= 0; i
< affected_vehicles
.Length(); ++i
) {
1474 /* Restore reservations of trains. */
1475 RestoreTrainReservation(affected_vehicles
[i
]);
1478 /* Check whether we need to expand the reservation of trains already on the station. */
1479 TileArea update_reservation_area
;
1480 if (axis
== AXIS_X
) {
1481 update_reservation_area
= TileArea(tile_org
, 1, numtracks_orig
);
1483 update_reservation_area
= TileArea(tile_org
, numtracks_orig
, 1);
1486 TILE_AREA_LOOP(tile
, update_reservation_area
) {
1487 /* Don't even try to make eye candy parts reserved. */
1488 if (IsStationTileBlocked(tile
)) continue;
1490 DiagDirection dir
= AxisToDiagDir(axis
);
1491 TileIndexDiff tile_offset
= TileOffsByDiagDir(dir
);
1492 TileIndex platform_begin
= tile
;
1493 TileIndex platform_end
= tile
;
1495 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1496 for (TileIndex next_tile
= platform_begin
- tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_begin
); next_tile
-= tile_offset
) {
1497 platform_begin
= next_tile
;
1499 for (TileIndex next_tile
= platform_end
+ tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_end
); next_tile
+= tile_offset
) {
1500 platform_end
= next_tile
;
1503 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1504 bool reservation
= false;
1505 for (TileIndex t
= platform_begin
; !reservation
&& t
<= platform_end
; t
+= tile_offset
) {
1506 reservation
= HasStationReservation(t
);
1510 SetRailStationPlatformReservation(platform_begin
, dir
, true);
1514 st
->MarkTilesDirty(false);
1515 st
->UpdateVirtCoord();
1516 UpdateStationAcceptance(st
, false);
1517 st
->RecomputeIndustriesNear();
1518 ZoningMarkDirtyStationCoverageArea(st
);
1519 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
1520 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
1521 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1522 DirtyCompanyInfrastructureWindows(st
->owner
);
1528 static void MakeRailStationAreaSmaller(BaseStation
*st
)
1530 TileArea ta
= st
->train_station
;
1535 if (ta
.w
!= 0 && ta
.h
!= 0) {
1536 /* check the left side, x = constant, y changes */
1537 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(0, i
));) {
1538 /* the left side is unused? */
1540 ta
.tile
+= TileDiffXY(1, 0);
1546 /* check the right side, x = constant, y changes */
1547 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(ta
.w
- 1, i
));) {
1548 /* the right side is unused? */
1555 /* check the upper side, y = constant, x changes */
1556 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(i
, 0));) {
1557 /* the left side is unused? */
1559 ta
.tile
+= TileDiffXY(0, 1);
1565 /* check the lower side, y = constant, x changes */
1566 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(i
, ta
.h
- 1));) {
1567 /* the left side is unused? */
1577 st
->train_station
= ta
;
1581 * Remove a number of tiles from any rail station within the area.
1582 * @param ta the area to clear station tile from.
1583 * @param affected_stations the stations affected.
1584 * @param flags the command flags.
1585 * @param removal_cost the cost for removing the tile, including the rail.
1586 * @param keep_rail whether to keep the rail of the station.
1587 * @tparam T the type of station to remove.
1588 * @return the number of cleared tiles or an error.
1591 CommandCost
RemoveFromRailBaseStation(TileArea ta
, SmallVector
<T
*, 4> &affected_stations
, DoCommandFlag flags
, Money removal_cost
, bool keep_rail
)
1593 /* Count of the number of tiles removed */
1595 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
1596 /* Accumulator for the errors seen during clearing. If no errors happen,
1597 * and the quantity is 0 there is no station. Otherwise it will be one
1598 * of the other error that got accumulated. */
1601 /* Do the action for every tile into the area */
1602 TILE_AREA_LOOP(tile
, ta
) {
1603 /* Make sure the specified tile is a rail station */
1604 if (!HasStationTileRail(tile
)) continue;
1606 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1607 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1609 if (ret
.Failed()) continue;
1611 /* Check ownership of station */
1612 T
*st
= T::GetByTile(tile
);
1613 if (st
== NULL
) continue;
1615 if (_current_company
!= OWNER_WATER
) {
1616 CommandCost ret
= CheckOwnership(st
->owner
);
1618 if (ret
.Failed()) continue;
1621 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1624 if (keep_rail
|| IsStationTileBlocked(tile
)) {
1625 /* Don't refund the 'steel' of the track when we keep the
1626 * rail, or when the tile didn't have any rail at all. */
1627 total_cost
.AddCost(-_price
[PR_CLEAR_RAIL
]);
1630 if (flags
& DC_EXEC
) {
1631 bool already_affected
= affected_stations
.Include(st
);
1632 if (!already_affected
) ZoningMarkDirtyStationCoverageArea(st
);
1634 /* read variables before the station tile is removed */
1635 uint specindex
= GetCustomStationSpecIndex(tile
);
1636 Track track
= GetRailStationTrack(tile
);
1637 Owner owner
= GetTileOwner(tile
);
1638 RailType rt
= GetRailType(tile
);
1639 if (Station::IsExpected(st
)) ((Station
*)st
)->catchment
.AfterRemoveTile(tile
, CA_TRAIN
);
1642 if (HasStationReservation(tile
)) {
1643 v
= GetTrainForReservation(tile
, track
);
1644 if (v
!= NULL
) FreeTrainReservation(v
);
1647 bool build_rail
= keep_rail
&& !IsStationTileBlocked(tile
);
1648 if (!build_rail
&& !IsStationTileBlocked(tile
)) Company::Get(owner
)->infrastructure
.rail
[rt
]--;
1650 DoClearSquare(tile
);
1651 DeleteNewGRFInspectWindow(GSF_STATIONS
, tile
);
1652 if (Station::IsExpected(st
) && Overlays::Instance()->HasStation((Station
*)st
)) ((Station
*)st
)->MarkAcceptanceTilesDirty();
1653 if (build_rail
) MakeRailNormal(tile
, owner
, TrackToTrackBits(track
), rt
);
1654 if (Station::IsExpected(st
) && Overlays::Instance()->HasStation((Station
*)st
)) ((Station
*)st
)->MarkAcceptanceTilesDirty();
1655 Company::Get(owner
)->infrastructure
.station
--;
1656 DirtyCompanyInfrastructureWindows(owner
);
1658 st
->rect
.AfterRemoveTile(st
, tile
);
1659 AddTrackToSignalBuffer(tile
, track
, owner
);
1660 YapfNotifyTrackLayoutChange(tile
, track
);
1662 DeallocateSpecFromStation(st
, specindex
);
1664 if (v
!= NULL
) RestoreTrainReservation(v
);
1668 if (quantity
== 0) return error
.Failed() ? error
: CommandCost(STR_ERROR_THERE_IS_NO_STATION
);
1670 for (T
**stp
= affected_stations
.Begin(); stp
!= affected_stations
.End(); stp
++) {
1673 /* now we need to make the "spanned" area of the railway station smaller
1674 * if we deleted something at the edges.
1675 * we also need to adjust train_tile. */
1676 MakeRailStationAreaSmaller(st
);
1677 UpdateStationSignCoord(st
);
1679 /* if we deleted the whole station, delete the train facility. */
1680 if (st
->train_station
.tile
== INVALID_TILE
) {
1681 st
->facilities
&= ~FACIL_TRAIN
;
1682 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1683 st
->UpdateVirtCoord();
1684 DeleteStationIfEmpty(st
);
1688 total_cost
.AddCost(quantity
* removal_cost
);
1693 * Remove a single tile from a rail station.
1694 * This allows for custom-built station with holes and weird layouts
1695 * @param start tile of station piece to remove
1696 * @param flags operation to perform
1697 * @param p1 start_tile
1698 * @param p2 various bitstuffed elements
1699 * - p2 = bit 0 - if set keep the rail
1700 * @param text unused
1701 * @return the cost of this operation or an error
1703 CommandCost
CmdRemoveFromRailStation(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1705 TileIndex end
= p1
== 0 ? start
: p1
;
1706 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1708 TileArea
ta(start
, end
);
1709 SmallVector
<Station
*, 4> affected_stations
;
1711 CommandCost ret
= RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_STATION_RAIL
], HasBit(p2
, 0));
1712 if (ret
.Failed()) return ret
;
1714 /* Do all station specific functions here. */
1715 for (Station
**stp
= affected_stations
.Begin(); stp
!= affected_stations
.End(); stp
++) {
1718 if (st
->train_station
.tile
== INVALID_TILE
) SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1719 if (Overlays::Instance()->HasStation(st
)) st
->MarkAcceptanceTilesDirty();
1720 st
->MarkTilesDirty(false);
1721 st
->RecomputeIndustriesNear();
1724 /* Now apply the rail cost to the number that we deleted */
1729 * Remove a single tile from a waypoint.
1730 * This allows for custom-built waypoint with holes and weird layouts
1731 * @param start tile of waypoint piece to remove
1732 * @param flags operation to perform
1733 * @param p1 start_tile
1734 * @param p2 various bitstuffed elements
1735 * - p2 = bit 0 - if set keep the rail
1736 * @param text unused
1737 * @return the cost of this operation or an error
1739 CommandCost
CmdRemoveFromRailWaypoint(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1741 TileIndex end
= p1
== 0 ? start
: p1
;
1742 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1744 TileArea
ta(start
, end
);
1745 SmallVector
<Waypoint
*, 4> affected_stations
;
1747 return RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
], HasBit(p2
, 0));
1752 * Remove a rail station/waypoint
1753 * @param st The station/waypoint to remove the rail part from
1754 * @param flags operation to perform
1755 * @param removal_cost the cost for removing a tile
1756 * @tparam T the type of station to remove
1757 * @return cost or failure of operation
1760 CommandCost
RemoveRailStation(T
*st
, DoCommandFlag flags
, Money removal_cost
)
1762 /* Current company owns the station? */
1763 if (_current_company
!= OWNER_WATER
) {
1764 CommandCost ret
= CheckOwnership(st
->owner
);
1765 if (ret
.Failed()) return ret
;
1768 /* determine width and height of platforms */
1769 TileArea ta
= st
->train_station
;
1771 assert(ta
.w
!= 0 && ta
.h
!= 0);
1773 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1774 /* clear all areas of the station */
1775 TILE_AREA_LOOP(tile
, ta
) {
1776 /* only remove tiles that are actually train station tiles */
1777 if (st
->TileBelongsToRailStation(tile
)) {
1778 SmallVector
<T
*, 4> affected_stations
; // dummy
1779 CommandCost ret
= RemoveFromRailBaseStation(TileArea(tile
, 1, 1), affected_stations
, flags
, removal_cost
, false);
1780 if (ret
.Failed()) return ret
;
1789 * Remove a rail station
1790 * @param tile Tile of the station.
1791 * @param flags operation to perform
1792 * @return cost or failure of operation
1794 static CommandCost
RemoveRailStation(TileIndex tile
, DoCommandFlag flags
)
1796 /* if there is flooding, remove platforms tile by tile */
1797 if (_current_company
== OWNER_WATER
) {
1798 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_STATION
);
1801 Station
*st
= Station::GetByTile(tile
);
1803 if (flags
& DC_EXEC
) ZoningMarkDirtyStationCoverageArea(st
);
1805 CommandCost cost
= RemoveRailStation(st
, flags
, _price
[PR_CLEAR_STATION_RAIL
]);
1807 if (flags
& DC_EXEC
) st
->RecomputeIndustriesNear();
1813 * Remove a rail waypoint
1814 * @param tile Tile of the waypoint.
1815 * @param flags operation to perform
1816 * @return cost or failure of operation
1818 static CommandCost
RemoveRailWaypoint(TileIndex tile
, DoCommandFlag flags
)
1820 /* if there is flooding, remove waypoints tile by tile */
1821 if (_current_company
== OWNER_WATER
) {
1822 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_WAYPOINT
);
1825 return RemoveRailStation(Waypoint::GetByTile(tile
), flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
]);
1830 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1831 * @param st The Station to do the whole procedure for
1832 * @return a pointer to where to link a new RoadStop*
1834 static RoadStop
**FindRoadStopSpot(bool truck_station
, Station
*st
)
1836 RoadStop
**primary_stop
= (truck_station
) ? &st
->truck_stops
: &st
->bus_stops
;
1838 if (*primary_stop
== NULL
) {
1839 /* we have no roadstop of the type yet, so write a "primary stop" */
1840 return primary_stop
;
1842 /* there are stops already, so append to the end of the list */
1843 RoadStop
*stop
= *primary_stop
;
1844 while (stop
->next
!= NULL
) stop
= stop
->next
;
1849 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
);
1852 * Find a nearby station that joins this road stop.
1853 * @param existing_stop an existing road stop we build over
1854 * @param station_to_join the station to join to
1855 * @param adjacent whether adjacent stations are allowed
1856 * @param ta the area of the newly build station
1857 * @param st 'return' pointer for the found station
1858 * @return command cost with the error or 'okay'
1860 static CommandCost
FindJoiningRoadStop(StationID existing_stop
, StationID station_to_join
, bool adjacent
, TileArea ta
, Station
**st
)
1862 return FindJoiningBaseStation
<Station
>(existing_stop
, station_to_join
, adjacent
, ta
, st
, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST
);
1866 * Build a bus or truck stop.
1867 * @param tile Northernmost tile of the stop.
1868 * @param flags Operation to perform.
1869 * @param p1 bit 0..7: Width of the road stop.
1870 * bit 8..15: Length of the road stop.
1871 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1872 * bit 1: 0 For normal stops, 1 for drive-through.
1873 * bit 2..3: The roadtypes.
1874 * bit 5: Allow stations directly adjacent to other stations.
1875 * bit 6..7: Entrance direction (#DiagDirection) for normal stops.
1876 * bit 6: #Axis of the road for drive-through stops.
1877 * bit 16..31: Station ID to join (NEW_STATION if build new one).
1878 * @param text Unused.
1879 * @return The cost of this operation or an error.
1881 CommandCost
CmdBuildRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1883 bool type
= HasBit(p2
, 0);
1884 bool is_drive_through
= HasBit(p2
, 1);
1885 RoadTypes rts
= Extract
<RoadTypes
, 2, 2>(p2
);
1886 StationID station_to_join
= GB(p2
, 16, 16);
1887 bool reuse
= (station_to_join
!= NEW_STATION
);
1888 if (!reuse
) station_to_join
= INVALID_STATION
;
1889 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1891 uint8 width
= (uint8
)GB(p1
, 0, 8);
1892 uint8 lenght
= (uint8
)GB(p1
, 8, 8);
1894 /* Check if the requested road stop is too big */
1895 if (width
> _settings_game
.station
.station_spread
|| lenght
> _settings_game
.station
.station_spread
) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1896 /* Check for incorrect width / length. */
1897 if (width
== 0 || lenght
== 0) return CMD_ERROR
;
1898 /* Check if the first tile and the last tile are valid */
1899 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, lenght
- 1) == INVALID_TILE
) return CMD_ERROR
;
1901 TileArea
roadstop_area(tile
, width
, lenght
);
1903 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1905 if (!HasExactlyOneBit(rts
) || !HasRoadTypesAvail(_current_company
, rts
)) return CMD_ERROR
;
1907 /* Trams only have drive through stops */
1908 if (!is_drive_through
&& HasBit(rts
, ROADTYPE_TRAM
)) return CMD_ERROR
;
1912 if (is_drive_through
) {
1913 /* By definition axis is valid, due to there being 2 axes and reading 1 bit. */
1914 axis
= Extract
<Axis
, 6, 1>(p2
);
1915 ddir
= AxisToDiagDir(axis
);
1917 /* By definition ddir is valid, due to there being 4 diagonal directions and reading 2 bits. */
1918 ddir
= Extract
<DiagDirection
, 6, 2>(p2
);
1919 axis
= DiagDirToAxis(ddir
);
1922 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
1923 if (ret
.Failed()) return ret
;
1925 /* Total road stop cost. */
1926 CommandCost
cost(EXPENSES_CONSTRUCTION
, roadstop_area
.w
* roadstop_area
.h
* _price
[type
? PR_BUILD_STATION_TRUCK
: PR_BUILD_STATION_BUS
]);
1927 StationID est
= INVALID_STATION
;
1928 ret
= CheckFlatLandRoadStop(roadstop_area
, flags
, is_drive_through
? 5 << axis
: 1 << ddir
, is_drive_through
, type
, axis
, &est
, rts
);
1929 if (ret
.Failed()) return ret
;
1933 ret
= FindJoiningRoadStop(est
, station_to_join
, HasBit(p2
, 5), roadstop_area
, &st
);
1934 if (ret
.Failed()) return ret
;
1936 /* Check if this number of road stops can be allocated. */
1937 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
);
1939 ret
= BuildStationPart(&st
, flags
, reuse
, roadstop_area
, STATIONNAMING_ROAD
);
1940 if (ret
.Failed()) return ret
;
1942 if (flags
& DC_EXEC
) {
1943 /* Check every tile in the area. */
1944 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
1945 RoadTypes cur_rts
= GetRoadTypes(cur_tile
);
1946 Owner road_owner
= HasBit(cur_rts
, ROADTYPE_ROAD
) ? GetRoadOwner(cur_tile
, ROADTYPE_ROAD
) : _current_company
;
1947 Owner tram_owner
= HasBit(cur_rts
, ROADTYPE_TRAM
) ? GetRoadOwner(cur_tile
, ROADTYPE_TRAM
) : _current_company
;
1949 if (IsTileType(cur_tile
, MP_STATION
) && IsRoadStop(cur_tile
)) {
1950 RemoveRoadStop(cur_tile
, flags
);
1953 RoadStop
*road_stop
= new RoadStop(cur_tile
);
1954 /* Insert into linked list of RoadStops. */
1955 RoadStop
**currstop
= FindRoadStopSpot(type
, st
);
1956 *currstop
= road_stop
;
1959 st
->truck_station
.Add(cur_tile
);
1961 st
->bus_station
.Add(cur_tile
);
1964 /* Initialize an empty station. */
1965 st
->AddFacility((type
) ? FACIL_TRUCK_STOP
: FACIL_BUS_STOP
, cur_tile
);
1967 st
->rect
.BeforeAddTile(cur_tile
, StationRect::ADD_TRY
);
1968 st
->catchment
.BeforeAddTile(cur_tile
, type
? CA_TRUCK
: CA_BUS
);
1970 RoadStopType rs_type
= type
? ROADSTOP_TRUCK
: ROADSTOP_BUS
;
1971 if (is_drive_through
) {
1972 /* Update company infrastructure counts. If the current tile is a normal
1973 * road tile, count only the new road bits needed to get a full diagonal road. */
1975 FOR_EACH_SET_ROADTYPE(rt
, cur_rts
| rts
) {
1976 Company
*c
= Company::GetIfValid(rt
== ROADTYPE_ROAD
? road_owner
: tram_owner
);
1978 c
->infrastructure
.road
[rt
] += 2 - (IsNormalRoadTile(cur_tile
) && HasBit(cur_rts
, rt
) ? CountBits(GetRoadBits(cur_tile
, rt
)) : 0);
1979 DirtyCompanyInfrastructureWindows(c
->index
);
1983 MakeDriveThroughRoadStop(cur_tile
, st
->owner
, road_owner
, tram_owner
, st
->index
, rs_type
, rts
| cur_rts
, axis
);
1984 road_stop
->MakeDriveThrough();
1986 /* Non-drive-through stop never overbuild and always count as two road bits. */
1987 Company::Get(st
->owner
)->infrastructure
.road
[FIND_FIRST_BIT(rts
)] += 2;
1988 MakeRoadStop(cur_tile
, st
->owner
, st
->index
, rs_type
, rts
, ddir
);
1990 Company::Get(st
->owner
)->infrastructure
.station
++;
1991 DirtyCompanyInfrastructureWindows(st
->owner
);
1993 MarkTileDirtyByTile(cur_tile
);
1995 ZoningMarkDirtyStationCoverageArea(st
);
1999 st
->UpdateVirtCoord();
2000 UpdateStationAcceptance(st
, false);
2001 st
->RecomputeIndustriesNear();
2002 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2003 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2004 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ROADVEHS
);
2010 static Vehicle
*ClearRoadStopStatusEnum(Vehicle
*v
, void *)
2012 if (v
->type
== VEH_ROAD
) {
2013 /* Okay... we are a road vehicle on a drive through road stop.
2014 * But that road stop has just been removed, so we need to make
2015 * sure we are in a valid state... however, vehicles can also
2016 * turn on road stop tiles, so only clear the 'road stop' state
2017 * bits and only when the state was 'in road stop', otherwise
2018 * we'll end up clearing the turn around bits. */
2019 RoadVehicle
*rv
= RoadVehicle::From(v
);
2020 if (HasBit(rv
->state
, RVS_IN_DT_ROAD_STOP
)) rv
->state
&= RVSB_ROAD_STOP_TRACKDIR_MASK
;
2028 * Remove a bus station/truck stop
2029 * @param tile TileIndex been queried
2030 * @param flags operation to perform
2031 * @return cost or failure of operation
2033 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
)
2035 Station
*st
= Station::GetByTile(tile
);
2037 if (_current_company
!= OWNER_WATER
) {
2038 CommandCost ret
= CheckOwnership(st
->owner
);
2039 if (ret
.Failed()) return ret
;
2042 bool is_truck
= IsTruckStop(tile
);
2044 RoadStop
**primary_stop
;
2046 if (is_truck
) { // truck stop
2047 primary_stop
= &st
->truck_stops
;
2048 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_TRUCK
);
2050 primary_stop
= &st
->bus_stops
;
2051 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_BUS
);
2054 assert(cur_stop
!= NULL
);
2056 /* don't do the check for drive-through road stops when company bankrupts */
2057 if (IsDriveThroughStopTile(tile
) && (flags
& DC_BANKRUPT
)) {
2058 /* remove the 'going through road stop' status from all vehicles on that tile */
2059 if (flags
& DC_EXEC
) FindVehicleOnPos(tile
, NULL
, &ClearRoadStopStatusEnum
);
2061 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
2062 if (ret
.Failed()) return ret
;
2065 if (flags
& DC_EXEC
) {
2066 ZoningMarkDirtyStationCoverageArea(st
);
2067 if (*primary_stop
== cur_stop
) {
2068 /* removed the first stop in the list */
2069 *primary_stop
= cur_stop
->next
;
2070 /* removed the only stop? */
2071 if (*primary_stop
== NULL
) {
2072 st
->facilities
&= (is_truck
? ~FACIL_TRUCK_STOP
: ~FACIL_BUS_STOP
);
2075 /* tell the predecessor in the list to skip this stop */
2076 RoadStop
*pred
= *primary_stop
;
2077 while (pred
->next
!= cur_stop
) pred
= pred
->next
;
2078 pred
->next
= cur_stop
->next
;
2081 /* Update company infrastructure counts. */
2083 FOR_EACH_SET_ROADTYPE(rt
, GetRoadTypes(tile
)) {
2084 Company
*c
= Company::GetIfValid(GetRoadOwner(tile
, rt
));
2086 c
->infrastructure
.road
[rt
] -= 2;
2087 DirtyCompanyInfrastructureWindows(c
->index
);
2090 Company::Get(st
->owner
)->infrastructure
.station
--;
2091 DirtyCompanyInfrastructureWindows(st
->owner
);
2093 if (IsDriveThroughStopTile(tile
)) {
2094 /* Clears the tile for us */
2095 cur_stop
->ClearDriveThrough();
2097 DoClearSquare(tile
);
2100 if (Overlays::Instance()->HasStation(st
)) st
->MarkAcceptanceTilesDirty();
2101 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ROADVEHS
);
2104 /* Make sure no vehicle is going to the old roadstop */
2106 FOR_ALL_ROADVEHICLES(v
) {
2107 if (v
->First() == v
&& v
->current_order
.IsType(OT_GOTO_STATION
) &&
2108 v
->dest_tile
== tile
) {
2109 v
->dest_tile
= v
->GetOrderStationLocation(st
->index
);
2113 st
->rect
.AfterRemoveTile(st
, tile
);
2114 st
->catchment
.AfterRemoveTile(tile
, is_truck
? CA_TRUCK
: CA_BUS
);
2116 st
->UpdateVirtCoord();
2117 st
->RecomputeIndustriesNear();
2118 DeleteStationIfEmpty(st
);
2120 /* Update the tile area of the truck/bus stop */
2122 st
->truck_station
.Clear();
2123 for (const RoadStop
*rs
= st
->truck_stops
; rs
!= NULL
; rs
= rs
->next
) st
->truck_station
.Add(rs
->xy
);
2125 st
->bus_station
.Clear();
2126 for (const RoadStop
*rs
= st
->bus_stops
; rs
!= NULL
; rs
= rs
->next
) st
->bus_station
.Add(rs
->xy
);
2130 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[is_truck
? PR_CLEAR_STATION_TRUCK
: PR_CLEAR_STATION_BUS
]);
2134 * Remove bus or truck stops.
2135 * @param tile Northernmost tile of the removal area.
2136 * @param flags Operation to perform.
2137 * @param p1 bit 0..7: Width of the removal area.
2138 * bit 8..15: Height of the removal area.
2139 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
2140 * @param p2 bit 1: 0 to keep roads of all drive-through stops, 1 to remove them.
2141 * @param text Unused.
2142 * @return The cost of this operation or an error.
2144 CommandCost
CmdRemoveRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2146 uint8 width
= (uint8
)GB(p1
, 0, 8);
2147 uint8 height
= (uint8
)GB(p1
, 8, 8);
2148 bool keep_drive_through_roads
= !HasBit(p2
, 1);
2150 /* Check for incorrect width / height. */
2151 if (width
== 0 || height
== 0) return CMD_ERROR
;
2152 /* Check if the first tile and the last tile are valid */
2153 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, height
- 1) == INVALID_TILE
) return CMD_ERROR
;
2154 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2155 if (!keep_drive_through_roads
&& (flags
& DC_BANKRUPT
)) return CMD_ERROR
;
2157 TileArea
roadstop_area(tile
, width
, height
);
2159 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2160 CommandCost
last_error(STR_ERROR_THERE_IS_NO_STATION
);
2161 bool had_success
= false;
2163 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
2164 /* Make sure the specified tile is a road stop of the correct type */
2165 if (!IsTileType(cur_tile
, MP_STATION
) || !IsRoadStop(cur_tile
) || (uint32
)GetRoadStopType(cur_tile
) != GB(p2
, 0, 1)) continue;
2167 /* Save information on to-be-restored roads before the stop is removed. */
2168 RoadTypes rts
= ROADTYPES_NONE
;
2169 RoadBits road_bits
= ROAD_NONE
;
2170 Owner road_owner
[] = { OWNER_NONE
, OWNER_NONE
};
2171 assert_compile(lengthof(road_owner
) == ROADTYPE_END
);
2172 if (IsDriveThroughStopTile(cur_tile
)) {
2174 FOR_EACH_SET_ROADTYPE(rt
, GetRoadTypes(cur_tile
)) {
2175 road_owner
[rt
] = GetRoadOwner(cur_tile
, rt
);
2176 /* If we don't want to preserve our roads then restore only roads of others. */
2177 if (keep_drive_through_roads
|| road_owner
[rt
] != _current_company
) SetBit(rts
, rt
);
2179 road_bits
= AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile
)));
2182 CommandCost ret
= RemoveRoadStop(cur_tile
, flags
);
2190 /* Restore roads. */
2191 if ((flags
& DC_EXEC
) && rts
!= ROADTYPES_NONE
) {
2192 MakeRoadNormal(cur_tile
, road_bits
, rts
, ClosestTownFromTile(cur_tile
, UINT_MAX
)->index
,
2193 road_owner
[ROADTYPE_ROAD
], road_owner
[ROADTYPE_TRAM
]);
2195 /* Update company infrastructure counts. */
2197 FOR_EACH_SET_ROADTYPE(rt
, rts
) {
2198 Company
*c
= Company::GetIfValid(GetRoadOwner(cur_tile
, rt
));
2200 c
->infrastructure
.road
[rt
] += CountBits(road_bits
);
2201 DirtyCompanyInfrastructureWindows(c
->index
);
2207 return had_success
? cost
: last_error
;
2211 * Computes the minimal distance from town's xy to any airport's tile.
2212 * @param it An iterator over all airport tiles.
2213 * @param town_tile town's tile (t->xy)
2214 * @return minimal manhattan distance from town_tile to any airport's tile
2216 static uint
GetMinimalAirportDistanceToTile(TileIterator
&it
, TileIndex town_tile
)
2218 uint mindist
= UINT_MAX
;
2220 for (TileIndex cur_tile
= it
; cur_tile
!= INVALID_TILE
; cur_tile
= ++it
) {
2221 mindist
= min(mindist
, DistanceManhattan(town_tile
, cur_tile
));
2228 * Get a possible noise reduction factor based on distance from town center.
2229 * The further you get, the less noise you generate.
2230 * So all those folks at city council can now happily slee... work in their offices
2231 * @param as airport information
2232 * @param it An iterator over all airport tiles.
2233 * @param town_tile TileIndex of town's center, the one who will receive the airport's candidature
2234 * @return the noise that will be generated, according to distance
2236 uint8
GetAirportNoiseLevelForTown(const AirportSpec
*as
, TileIterator
&it
, TileIndex town_tile
)
2238 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2239 * So no need to go any further*/
2240 if (as
->noise_level
< 2) return as
->noise_level
;
2242 uint distance
= GetMinimalAirportDistanceToTile(it
, town_tile
);
2244 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2245 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2246 * Basically, it says that the less tolerant a town is, the bigger the distance before
2247 * an actual decrease can be granted */
2248 uint8 town_tolerance_distance
= 8 + (_settings_game
.difficulty
.town_council_tolerance
* 4);
2250 /* now, we want to have the distance segmented using the distance judged bareable by town
2251 * This will give us the coefficient of reduction the distance provides. */
2252 uint noise_reduction
= distance
/ town_tolerance_distance
;
2254 /* If the noise reduction equals the airport noise itself, don't give it for free.
2255 * Otherwise, simply reduce the airport's level. */
2256 return noise_reduction
>= as
->noise_level
? 1 : as
->noise_level
- noise_reduction
;
2260 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2261 * If two towns have the same distance, town with lower index is returned.
2262 * @param as airport's description
2263 * @param it An iterator over all airport tiles
2264 * @return nearest town to airport
2266 Town
*AirportGetNearestTown(const AirportSpec
*as
, const TileIterator
&it
)
2268 Town
*t
, *nearest
= NULL
;
2269 uint add
= as
->size_x
+ as
->size_y
- 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2270 uint mindist
= UINT_MAX
- add
; // prevent overflow
2272 if (DistanceManhattan(t
->xy
, it
) < mindist
+ add
) { // avoid calling GetMinimalAirportDistanceToTile too often
2273 TileIterator
*copy
= it
.Clone();
2274 uint dist
= GetMinimalAirportDistanceToTile(*copy
, t
->xy
);
2276 if (dist
< mindist
) {
2287 /** Recalculate the noise generated by the airports of each town */
2288 void UpdateAirportsNoise()
2293 FOR_ALL_TOWNS(t
) t
->noise_reached
= 0;
2295 FOR_ALL_STATIONS(st
) {
2296 if (st
->airport
.tile
!= INVALID_TILE
&& st
->airport
.type
!= AT_OILRIG
) {
2297 const AirportSpec
*as
= st
->airport
.GetSpec();
2298 AirportTileIterator
it(st
);
2299 Town
*nearest
= AirportGetNearestTown(as
, it
);
2300 nearest
->noise_reached
+= GetAirportNoiseLevelForTown(as
, it
, nearest
->xy
);
2307 * /// Checks if an airport can be removed (no aircraft on it or landing)
2308 * @param st Station whose airport is to be removed
2309 * @param flags Operation to perform
2310 * @return Cost or failure of operation
2312 static CommandCost
CanRemoveAirport(Station
*st
, DoCommandFlag flags
)
2315 FOR_ALL_AIRCRAFT(a
) {
2316 if (!a
->IsNormalAircraft()) continue;
2317 if (a
->targetairport
== st
->index
&& a
->state
!= FLYING
)
2318 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY
);
2321 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2323 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2324 if (!st
->TileBelongsToAirport(tile_cur
)) continue;
2326 CommandCost ret
= EnsureNoVehicleOnGround(tile_cur
);
2327 if (ret
.Failed()) return ret
;
2329 cost
.AddCost(_price
[PR_CLEAR_STATION_AIRPORT
]);
2338 * @param tile tile where airport will be built
2339 * @param flags operation to perform
2341 * - p1 = (bit 0- 7) - airport type, @see airport.h
2342 * - p1 = (bit 8-15) - airport layout
2343 * @param p2 various bitstuffed elements
2344 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2345 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2346 * @param text unused
2347 * @return the cost of this operation or an error
2349 CommandCost
CmdBuildAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2351 StationID station_to_join
= GB(p2
, 16, 16);
2352 bool reuse
= (station_to_join
!= NEW_STATION
);
2353 if (!reuse
) station_to_join
= INVALID_STATION
;
2354 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2355 byte airport_type
= GB(p1
, 0, 8);
2356 byte layout
= GB(p1
, 8, 8);
2358 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2360 if (airport_type
>= NUM_AIRPORTS
) return CMD_ERROR
;
2362 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2363 if (ret
.Failed()) return ret
;
2365 /* Check if a valid, buildable airport was chosen for construction */
2366 const AirportSpec
*as
= AirportSpec::Get(airport_type
);
2367 if (!as
->IsAvailable() || layout
>= as
->num_table
) return CMD_ERROR
;
2369 Direction rotation
= as
->rotation
[layout
];
2372 if (rotation
== DIR_E
|| rotation
== DIR_W
) Swap(w
, h
);
2373 TileArea airport_area
= TileArea(tile
, w
, h
);
2375 if (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
) {
2376 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
2379 StationID est
= INVALID_STATION
;
2380 CommandCost cost
= CheckFlatLandAirport(airport_area
, flags
, &est
);
2381 if (cost
.Failed()) return cost
;
2384 ret
= FindJoiningStation(est
, station_to_join
, HasBit(p2
, 0), airport_area
, &st
, STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
2385 if (ret
.Failed()) return ret
;
2388 if (st
== NULL
&& distant_join
) st
= Station::GetIfValid(station_to_join
);
2390 ret
= BuildStationPart(&st
, flags
, reuse
, airport_area
, (GetAirport(airport_type
)->flags
& AirportFTAClass::AIRPLANES
) ? STATIONNAMING_AIRPORT
: STATIONNAMING_HELIPORT
);
2391 if (ret
.Failed()) return ret
;
2393 /* action to be performed */
2395 AIRPORT_NEW
, // airport is a new station
2396 AIRPORT_ADD
, // add an airport to an existing station
2397 AIRPORT_UPGRADE
, // upgrade the airport in a station
2399 (est
!= INVALID_STATION
) ? AIRPORT_UPGRADE
:
2400 (st
!= NULL
) ? AIRPORT_ADD
: AIRPORT_NEW
;
2402 if (action
== AIRPORT_ADD
&& st
->airport
.tile
!= INVALID_TILE
) {
2403 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT
);
2406 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2407 AirportTileTableIterator
iter(as
->table
[layout
], tile
);
2408 Town
*nearest
= AirportGetNearestTown(as
, iter
);
2409 uint newnoise_level
= nearest
->noise_reached
+ GetAirportNoiseLevelForTown(as
, iter
, nearest
->xy
);
2411 if (action
== AIRPORT_UPGRADE
) {
2412 const AirportSpec
*old_as
= st
->airport
.GetSpec();
2413 AirportTileTableIterator
old_iter(old_as
->table
[st
->airport
.layout
], st
->airport
.tile
);
2414 Town
*old_nearest
= AirportGetNearestTown(old_as
, old_iter
);
2415 if (old_nearest
== nearest
) {
2416 newnoise_level
-= GetAirportNoiseLevelForTown(old_as
, old_iter
, nearest
->xy
);
2420 /* Check if local auth would allow a new airport */
2421 StringID authority_refuse_message
= STR_NULL
;
2422 Town
*authority_refuse_town
= NULL
;
2424 if (_settings_game
.economy
.station_noise_level
) {
2425 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2426 if (newnoise_level
> nearest
->MaxTownNoise()) {
2427 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE
;
2428 authority_refuse_town
= nearest
;
2430 } else if (action
!= AIRPORT_UPGRADE
) {
2431 Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
2434 FOR_ALL_STATIONS(st
) {
2435 if (st
->town
== t
&& (st
->facilities
& FACIL_AIRPORT
) && st
->airport
.type
!= AT_OILRIG
) num
++;
2438 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT
;
2439 authority_refuse_town
= t
;
2443 if (authority_refuse_message
!= STR_NULL
) {
2444 SetDParam(0, authority_refuse_town
->index
);
2445 return_cmd_error(authority_refuse_message
);
2448 if (action
== AIRPORT_UPGRADE
) {
2449 /* check that the old airport can be removed */
2450 CommandCost r
= CanRemoveAirport(st
, flags
);
2451 if (r
.Failed()) return r
;
2455 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2456 cost
.AddCost(_price
[PR_BUILD_STATION_AIRPORT
]);
2459 if (flags
& DC_EXEC
) {
2460 if (action
== AIRPORT_UPGRADE
) {
2461 /* delete old airport if upgrading */
2462 const AirportSpec
*old_as
= st
->airport
.GetSpec();
2463 AirportTileTableIterator
old_iter(old_as
->table
[st
->airport
.layout
], st
->airport
.tile
);
2464 Town
*old_nearest
= AirportGetNearestTown(old_as
, old_iter
);
2466 if (old_nearest
!= nearest
) {
2467 old_nearest
->noise_reached
-= GetAirportNoiseLevelForTown(old_as
, old_iter
, old_nearest
->xy
);
2468 if (_settings_game
.economy
.station_noise_level
) {
2469 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2473 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2474 if (IsHangarTile(tile_cur
)) OrderBackup::Reset(tile_cur
, false);
2475 DeleteAnimatedTile(tile_cur
);
2476 DoClearSquare(tile_cur
);
2477 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
);
2480 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2482 WC_VEHICLE_DEPOT
, st
->airport
.GetHangarTile(i
)
2486 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2487 st
->airport
.Clear();
2490 /* Always add the noise, so there will be no need to recalculate when option toggles */
2491 nearest
->noise_reached
= newnoise_level
;
2493 st
->AddFacility(FACIL_AIRPORT
, tile
);
2494 st
->airport
.type
= airport_type
;
2495 st
->airport
.layout
= layout
;
2496 st
->airport
.flags
= 0;
2497 st
->airport
.rotation
= rotation
;
2499 st
->rect
.BeforeAddRect(tile
, w
, h
, StationRect::ADD_TRY
);
2501 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2502 MakeAirport(iter
, st
->owner
, st
->index
, iter
.GetStationGfx(), WATER_CLASS_INVALID
);
2503 SetStationTileRandomBits(iter
, GB(Random(), 0, 4));
2504 st
->airport
.Add(iter
);
2505 st
->catchment
.BeforeAddTile(iter
, as
->catchment
);
2507 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter
.GetStationGfx()))->animation
.status
!= ANIM_STATUS_NO_ANIMATION
) AddAnimatedTile(iter
);
2510 /* Only call the animation trigger after all tiles have been built */
2511 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2512 AirportTileAnimationTrigger(st
, iter
, AAT_BUILT
);
2515 if (action
!= AIRPORT_NEW
) UpdateAirplanesOnNewStation(st
);
2517 if (action
== AIRPORT_UPGRADE
) {
2518 UpdateStationSignCoord(st
);
2520 Company::Get(st
->owner
)->infrastructure
.airport
++;
2521 DirtyCompanyInfrastructureWindows(st
->owner
);
2522 st
->UpdateVirtCoord();
2525 UpdateStationAcceptance(st
, false);
2526 st
->RecomputeIndustriesNear();
2527 ZoningMarkDirtyStationCoverageArea(st
);
2528 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2529 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2530 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2532 if (_settings_game
.economy
.station_noise_level
) {
2533 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2541 * Place a Seaplane Airport.
2542 * @param tile tile where airport will be built
2543 * @param flags operation to perform
2545 * - p1 = (bit 0- 7) - airport type, @see airport.h
2546 * - p1 = (bit 8-15) - airport layout
2547 * @param p2 various bitstuffed elements
2548 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2549 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2550 * @param text unused
2551 * @return the cost of this operation or an error
2553 CommandCost
CmdBuildSeaplaneAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2556 StationID station_to_join
= GB(p2
, 16, 16);
2557 bool reuse
= (station_to_join
!= NEW_STATION
);
2558 if (!reuse
) station_to_join
= INVALID_STATION
;
2559 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2560 byte airport_type
= GB(p1
, 0, 8);
2561 byte layout
= GB(p1
, 8, 8);
2563 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2565 if (airport_type
>= NUM_AIRPORTS
) return CMD_ERROR
;
2568 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2569 if (ret
.Failed()) return ret
;
2571 /* Check if a valid, buildable airport was chosen for construction */
2572 const AirportSpec
*as
= AirportSpec::Get(airport_type
);
2573 if (!as
->IsAvailable() || layout
>= as
->num_table
) return CMD_ERROR
;
2575 Direction rotation
= as
->rotation
[layout
];
2578 if (rotation
== DIR_E
|| rotation
== DIR_W
) Swap(w
, h
);
2579 TileArea airport_area
= TileArea(tile
, w
, h
);
2581 if (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
) {
2582 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
2585 CommandCost cost
= CheckClearWater(airport_area
, flags
);
2586 if (cost
.Failed()) return cost
;
2588 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2589 AirportTileTableIterator
iter(as
->table
[layout
], tile
);
2590 Town
*nearest
= AirportGetNearestTown(as
, iter
);
2591 uint newnoise_level
= GetAirportNoiseLevelForTown(as
, iter
, nearest
->xy
);
2593 /* Check if local auth would allow a new airport */
2594 StringID authority_refuse_message
= STR_NULL
;
2595 Town
*authority_refuse_town
= NULL
;
2597 if (_settings_game
.economy
.station_noise_level
) {
2598 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2599 if ((nearest
->noise_reached
+ newnoise_level
) > nearest
->MaxTownNoise()) {
2600 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE
;
2601 authority_refuse_town
= nearest
;
2604 Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
2607 FOR_ALL_STATIONS(st
) {
2608 if (st
->town
== t
&& (st
->facilities
& FACIL_AIRPORT
) && st
->airport
.type
!= AT_OILRIG
) num
++;
2611 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT
;
2612 authority_refuse_town
= t
;
2616 if (authority_refuse_message
!= STR_NULL
) {
2617 SetDParam(0, authority_refuse_town
->index
);
2618 return_cmd_error(authority_refuse_message
);
2622 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, HasBit(p2
, 0), airport_area
, &st
);
2623 if (ret
.Failed()) return ret
;
2626 if (st
== NULL
&& distant_join
) st
= Station::GetIfValid(station_to_join
);
2628 ret
= BuildStationPart(&st
, flags
, reuse
, airport_area
, STATIONNAMING_AIRPORT
);
2629 if (ret
.Failed()) return ret
;
2631 if (st
!= NULL
&& st
->airport
.tile
!= INVALID_TILE
) {
2632 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT
);
2635 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2636 cost
.AddCost(_price
[PR_BUILD_STATION_AIRPORT
]);
2639 if (flags
& DC_EXEC
) {
2640 /* Always add the noise, so there will be no need to recalculate when option toggles */
2641 nearest
->noise_reached
+= newnoise_level
;
2643 st
->AddFacility(FACIL_AIRPORT
, tile
);
2644 st
->airport
.type
= airport_type
;
2645 st
->airport
.layout
= layout
;
2646 st
->airport
.flags
= 0;
2647 st
->airport
.rotation
= rotation
;
2649 st
->rect
.BeforeAddRect(tile
, w
, h
, StationRect::ADD_TRY
);
2651 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2652 MakeAirport(iter
, st
->owner
, st
->index
, iter
.GetStationGfx(), GetWaterClass(iter
));
2653 SetStationTileRandomBits(iter
, GB(Random(), 0, 4));
2654 st
->airport
.Add(iter
);
2655 st
->catchment
.BeforeAddTile(iter
, as
->catchment
);
2657 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter
.GetStationGfx()))->animation
.status
!= ANIM_STATUS_NO_ANIMATION
) AddAnimatedTile(iter
);
2660 /* Only call the animation trigger after all tiles have been built */
2661 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2662 AirportTileAnimationTrigger(st
, iter
, AAT_BUILT
);
2665 UpdateAirplanesOnNewStation(st
);
2667 Company::Get(st
->owner
)->infrastructure
.airport
++;
2668 DirtyCompanyInfrastructureWindows(st
->owner
);
2670 st
->UpdateVirtCoord();
2671 UpdateStationAcceptance(st
, false);
2672 st
->RecomputeIndustriesNear();
2673 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2674 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2675 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2677 if (_settings_game
.economy
.station_noise_level
) {
2678 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2687 * @param tile TileIndex been queried
2688 * @param flags operation to perform
2689 * @return cost or failure of operation
2691 static CommandCost
RemoveAirport(TileIndex tile
, DoCommandFlag flags
)
2693 Station
*st
= Station::GetByTile(tile
);
2695 if (_current_company
!= OWNER_WATER
) {
2696 CommandCost ret
= CheckOwnership(st
->owner
);
2697 if (ret
.Failed()) return ret
;
2700 CommandCost cost
= CanRemoveAirport(st
, flags
);
2701 if (cost
.Failed()) return cost
;
2703 if (flags
& DC_EXEC
) {
2704 const AirportSpec
*as
= st
->airport
.GetSpec();
2705 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2706 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2707 * need of recalculation */
2708 AirportTileIterator
it(st
);
2709 Town
*nearest
= AirportGetNearestTown(as
, it
);
2710 nearest
->noise_reached
-= GetAirportNoiseLevelForTown(as
, it
, nearest
->xy
);
2712 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2713 ZoningMarkDirtyStationCoverageArea(st
);
2714 const AirportSpec
*as
= st
->airport
.GetSpec();
2715 if (IsHangarTile(tile_cur
)) OrderBackup::Reset(tile_cur
, false);
2716 DeleteAnimatedTile(tile_cur
);
2717 st
->catchment
.AfterRemoveTile(tile_cur
, as
->catchment
);
2718 WaterClass wc
= GetWaterClass(tile_cur
);
2719 DoClearSquare(tile_cur
);
2721 if (wc
!= WATER_CLASS_INVALID
){
2722 SetTileType(tile_cur
, MP_WATER
);
2723 SetWaterClass(tile_cur
, wc
);
2724 if (wc
== WATER_CLASS_CANAL
) {
2725 SetTileOwner(tile_cur
, st
->owner
);
2729 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
);
2732 /* Clear the persistent storage. */
2733 delete st
->airport
.psa
;
2735 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2737 WC_VEHICLE_DEPOT
, st
->airport
.GetHangarTile(i
)
2741 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2743 st
->airport
.Clear();
2744 st
->facilities
&= ~FACIL_AIRPORT
;
2746 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2748 if (_settings_game
.economy
.station_noise_level
) {
2749 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2752 Company::Get(st
->owner
)->infrastructure
.airport
--;
2753 DirtyCompanyInfrastructureWindows(st
->owner
);
2755 st
->UpdateVirtCoord();
2756 st
->RecomputeIndustriesNear();
2757 DeleteStationIfEmpty(st
);
2758 DeleteNewGRFInspectWindow(GSF_AIRPORTS
, st
->index
);
2765 * Open/close an airport to incoming aircraft.
2766 * @param tile Unused.
2767 * @param flags Operation to perform.
2768 * @param p1 Station ID of the airport.
2770 * @param text unused
2771 * @return the cost of this operation or an error
2773 CommandCost
CmdOpenCloseAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2775 if (!Station::IsValidID(p1
)) return CMD_ERROR
;
2776 Station
*st
= Station::Get(p1
);
2778 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->owner
== OWNER_NONE
) return CMD_ERROR
;
2780 CommandCost ret
= CheckOwnership(st
->owner
);
2781 if (ret
.Failed()) return ret
;
2783 if (flags
& DC_EXEC
) {
2784 st
->airport
.flags
^= AIRPORT_CLOSED_block
;
2785 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_CLOSE_AIRPORT
);
2787 return CommandCost();
2791 * Tests whether the company's vehicles have this station in orders
2792 * @param station station ID
2793 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2794 * @param company company ID
2796 bool HasStationInUse(StationID station
, bool include_company
, CompanyID company
)
2799 FOR_ALL_VEHICLES(v
) {
2800 if ((v
->owner
== company
) == include_company
) {
2802 FOR_VEHICLE_ORDERS(v
, order
) {
2803 if ((order
->IsType(OT_GOTO_STATION
) || order
->IsType(OT_GOTO_WAYPOINT
)) && order
->GetDestination() == station
) {
2812 static const TileIndexDiffC _dock_tileoffs_chkaround
[] = {
2818 static const byte _dock_w_chk
[4] = { 2, 1, 2, 1 };
2819 static const byte _dock_h_chk
[4] = { 1, 2, 1, 2 };
2822 * Build a dock/haven.
2823 * @param tile tile where dock will be built
2824 * @param flags operation to perform
2825 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
2826 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
2827 * @param text unused
2828 * @return the cost of this operation or an error
2830 CommandCost
CmdBuildDock(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2832 StationID station_to_join
= GB(p2
, 16, 16);
2833 bool reuse
= (station_to_join
!= NEW_STATION
);
2834 if (!reuse
) station_to_join
= INVALID_STATION
;
2835 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2837 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2839 TileIndex slope_tile
= tile
;
2841 DiagDirection direction
= GetInclinedSlopeDirection(GetTileSlope(slope_tile
));
2842 if (direction
== INVALID_DIAGDIR
) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2843 direction
= ReverseDiagDir(direction
);
2845 TileIndex flat_tile
= slope_tile
+ TileOffsByDiagDir(direction
);
2847 /* Docks cannot be placed on rapids */
2848 if (HasTileWaterGround(slope_tile
)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2850 CommandCost ret
= CheckIfAuthorityAllowsNewStation(slope_tile
, flags
);
2851 if (ret
.Failed()) return ret
;
2853 if (IsBridgeAbove(slope_tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2855 ret
= DoCommand(slope_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2856 if (ret
.Failed()) return ret
;
2858 if (!IsTileType(flat_tile
, MP_WATER
) || !IsTileFlat(flat_tile
)) {
2859 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2862 if (IsBridgeAbove(flat_tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2864 /* Get the water class of the water tile before it is cleared.*/
2865 WaterClass wc
= GetWaterClass(flat_tile
);
2867 ret
= DoCommand(flat_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2868 if (ret
.Failed()) return ret
;
2870 TileIndex adjacent_tile
= flat_tile
+ TileOffsByDiagDir(direction
);
2871 if (!IsTileType(adjacent_tile
, MP_WATER
) || !IsTileFlat(adjacent_tile
)) {
2872 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2875 TileArea dock_area
= TileArea(slope_tile
+ ToTileIndexDiff(_dock_tileoffs_chkaround
[direction
]),
2876 _dock_w_chk
[direction
], _dock_h_chk
[direction
]);
2880 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, HasBit(p1
, 0), dock_area
, &st
);
2881 if (ret
.Failed()) return ret
;
2884 if (st
== NULL
&& distant_join
) st
= Station::GetIfValid(station_to_join
);
2886 if (!Dock::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_DOCKS
);
2888 ret
= BuildStationPart(&st
, flags
, reuse
, dock_area
, STATIONNAMING_DOCK
);
2889 if (ret
.Failed()) return ret
;
2891 if (flags
& DC_EXEC
) {
2892 /* Create the dock and insert it into the list of docks. */
2893 Dock
*dock
= new Dock(slope_tile
, flat_tile
);
2894 dock
->next
= st
->docks
;
2897 st
->dock_station
.Add(slope_tile
);
2898 st
->dock_station
.Add(flat_tile
);
2899 st
->AddFacility(FACIL_DOCK
, slope_tile
);
2901 st
->rect
.BeforeAddRect(dock_area
.tile
, dock_area
.w
, dock_area
.h
, StationRect::ADD_TRY
);
2902 st
->catchment
.BeforeAddRect(dock_area
.tile
, dock_area
.w
, dock_area
.h
, CA_DOCK
);
2904 /* If the water part of the dock is on a canal, update infrastructure counts.
2905 * This is needed as we've unconditionally cleared that tile before. */
2906 if (wc
== WATER_CLASS_CANAL
) {
2907 Company::Get(st
->owner
)->infrastructure
.water
++;
2909 Company::Get(st
->owner
)->infrastructure
.station
+= 2;
2910 DirtyCompanyInfrastructureWindows(st
->owner
);
2912 MakeDock(slope_tile
, st
->owner
, st
->index
, direction
, wc
);
2914 st
->UpdateVirtCoord();
2915 UpdateStationAcceptance(st
, false);
2916 st
->RecomputeIndustriesNear();
2917 ZoningMarkDirtyStationCoverageArea(st
);
2918 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2919 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2920 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_SHIPS
);
2923 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_STATION_DOCK
]);
2928 * @param tile TileIndex been queried
2929 * @param flags operation to perform
2930 * @return cost or failure of operation
2932 static CommandCost
RemoveDock(TileIndex tile
, DoCommandFlag flags
)
2934 Station
*st
= Station::GetByTile(tile
);
2935 CommandCost ret
= CheckOwnership(st
->owner
);
2936 if (ret
.Failed()) return ret
;
2938 Dock
*removing_dock
= Dock::GetByTile(tile
);
2939 assert(removing_dock
!= NULL
);
2941 TileIndex tile1
= removing_dock
->sloped
;
2942 TileIndex tile2
= removing_dock
->flat
;
2944 DiagDirection direction
= DiagdirBetweenTiles(removing_dock
->sloped
, removing_dock
->flat
);
2945 TileIndex docking_location
= removing_dock
->flat
+ TileOffsByDiagDir(direction
);
2947 ret
= EnsureNoVehicleOnGround(tile1
);
2948 if (ret
.Succeeded()) ret
= EnsureNoVehicleOnGround(tile2
);
2949 if (ret
.Failed()) return ret
;
2951 if (flags
& DC_EXEC
) {
2952 st
->catchment
.AfterRemoveTile(tile1
, CA_DOCK
);
2953 st
->catchment
.AfterRemoveTile(tile2
, CA_DOCK
);
2954 ZoningMarkDirtyStationCoverageArea(st
);
2956 if (st
->docks
== removing_dock
) {
2957 /* The first dock in the list is removed. */
2958 st
->docks
= removing_dock
->next
;
2959 /* Last dock is removed. */
2960 if (st
->docks
== NULL
) {
2961 st
->facilities
&= ~FACIL_DOCK
;
2964 /* Tell the predecessor in the list to skip this dock. */
2965 Dock
*pred
= st
->docks
;
2966 while (pred
->next
!= removing_dock
) pred
= pred
->next
;
2967 pred
->next
= removing_dock
->next
;
2970 delete removing_dock
;
2972 DoClearSquare(tile1
);
2973 MarkTileDirtyByTile(tile1
);
2974 MakeWaterKeepingClass(tile2
, st
->owner
);
2976 if (Overlays::Instance()->HasStation(st
)) st
->MarkAcceptanceTilesDirty();
2977 st
->rect
.AfterRemoveTile(st
, tile1
);
2978 st
->rect
.AfterRemoveTile(st
, tile2
);
2980 st
->dock_station
.Clear();
2981 for (Dock
*dock
= st
->docks
; dock
!= NULL
; dock
= dock
->next
) {
2982 st
->dock_station
.Add(dock
->flat
);
2983 st
->dock_station
.Add(dock
->sloped
);
2986 Company::Get(st
->owner
)->infrastructure
.station
-= 2;
2987 DirtyCompanyInfrastructureWindows(st
->owner
);
2989 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_SHIPS
);
2990 st
->UpdateVirtCoord();
2991 st
->RecomputeIndustriesNear();
2992 DeleteStationIfEmpty(st
);
2994 /* All ships that were going to our station, can't go to it anymore.
2995 * Just clear the order, then automatically the next appropriate order
2996 * will be selected and in case of no appropriate order it will just
2997 * wander around the world. */
3000 if (s
->current_order
.IsType(OT_LOADING
) && s
->tile
== docking_location
) {
3004 if (s
->dest_tile
== docking_location
) {
3006 s
->current_order
.Free();
3011 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_STATION_DOCK
]);
3014 #include "table/station_land.h"
3016 const DrawTileSprites
*GetStationTileLayout(StationType st
, byte gfx
)
3018 return &_station_display_datas
[st
][gfx
];
3022 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
3023 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
3024 * is set to the overlay to draw.
3025 * @param ti Positional info for the tile to decide snowyness etc. May be NULL.
3026 * @param [in,out] ground Groundsprite to draw.
3027 * @param [out] overlay_offset Overlay to draw.
3028 * @return true if overlay can be drawn.
3030 bool SplitGroundSpriteForOverlay(const TileInfo
*ti
, SpriteID
*ground
, RailTrackOffset
*overlay_offset
)
3034 case SPR_RAIL_TRACK_X
:
3035 snow_desert
= false;
3036 *overlay_offset
= RTO_X
;
3039 case SPR_RAIL_TRACK_Y
:
3040 snow_desert
= false;
3041 *overlay_offset
= RTO_Y
;
3044 case SPR_RAIL_TRACK_X_SNOW
:
3046 *overlay_offset
= RTO_X
;
3049 case SPR_RAIL_TRACK_Y_SNOW
:
3051 *overlay_offset
= RTO_Y
;
3059 /* Decide snow/desert from tile */
3060 switch (_settings_game
.game_creation
.landscape
) {
3062 snow_desert
= (uint
)ti
->z
> GetSnowLine() * TILE_HEIGHT
;
3066 snow_desert
= GetTropicZone(ti
->tile
) == TROPICZONE_DESERT
;
3074 *ground
= snow_desert
? SPR_FLAT_SNOW_DESERT_TILE
: SPR_FLAT_GRASS_TILE
;
3078 static void DrawTile_Station(TileInfo
*ti
)
3080 const NewGRFSpriteLayout
*layout
= NULL
;
3081 DrawTileSprites tmp_rail_layout
;
3082 const DrawTileSprites
*t
= NULL
;
3083 RoadTypes roadtypes
;
3085 const RailtypeInfo
*rti
= NULL
;
3086 uint32 relocation
= 0;
3087 uint32 ground_relocation
= 0;
3088 BaseStation
*st
= NULL
;
3089 const StationSpec
*statspec
= NULL
;
3090 uint tile_layout
= 0;
3092 if (HasStationRail(ti
->tile
)) {
3093 rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
3094 roadtypes
= ROADTYPES_NONE
;
3095 total_offset
= rti
->GetRailtypeSpriteOffset();
3097 if (IsCustomStationSpecIndex(ti
->tile
)) {
3098 /* look for customization */
3099 st
= BaseStation::GetByTile(ti
->tile
);
3100 statspec
= st
->speclist
[GetCustomStationSpecIndex(ti
->tile
)].spec
;
3102 if (statspec
!= NULL
) {
3103 tile_layout
= GetStationGfx(ti
->tile
);
3105 if (HasBit(statspec
->callback_mask
, CBM_STATION_SPRITE_LAYOUT
)) {
3106 uint16 callback
= GetStationCallback(CBID_STATION_SPRITE_LAYOUT
, 0, 0, statspec
, st
, ti
->tile
);
3107 if (callback
!= CALLBACK_FAILED
) tile_layout
= (callback
& ~1) + GetRailStationAxis(ti
->tile
);
3110 /* Ensure the chosen tile layout is valid for this custom station */
3111 if (statspec
->renderdata
!= NULL
) {
3112 layout
= &statspec
->renderdata
[tile_layout
< statspec
->tiles
? tile_layout
: (uint
)GetRailStationAxis(ti
->tile
)];
3113 if (!layout
->NeedsPreprocessing()) {
3121 roadtypes
= IsRoadStop(ti
->tile
) ? GetRoadTypes(ti
->tile
) : ROADTYPES_NONE
;
3125 StationGfx gfx
= GetStationGfx(ti
->tile
);
3126 if (IsAirport(ti
->tile
)) {
3127 gfx
= GetAirportGfx(ti
->tile
);
3128 if (gfx
>= NEW_AIRPORTTILE_OFFSET
) {
3129 const AirportTileSpec
*ats
= AirportTileSpec::Get(gfx
);
3130 if (ats
->grf_prop
.spritegroup
[0] != NULL
&& DrawNewAirportTile(ti
, Station::GetByTile(ti
->tile
), gfx
, ats
)) {
3133 /* No sprite group (or no valid one) found, meaning no graphics associated.
3134 * Use the substitute one instead */
3135 assert(ats
->grf_prop
.subst_id
!= INVALID_AIRPORTTILE
);
3136 gfx
= ats
->grf_prop
.subst_id
;
3139 case APT_RADAR_GRASS_FENCE_SW
:
3140 t
= &_station_display_datas_airport_radar_grass_fence_sw
[GetAnimationFrame(ti
->tile
)];
3142 case APT_GRASS_FENCE_NE_FLAG
:
3143 t
= &_station_display_datas_airport_flag_grass_fence_ne
[GetAnimationFrame(ti
->tile
)];
3145 case APT_RADAR_FENCE_SW
:
3146 t
= &_station_display_datas_airport_radar_fence_sw
[GetAnimationFrame(ti
->tile
)];
3148 case APT_RADAR_FENCE_NE
:
3149 t
= &_station_display_datas_airport_radar_fence_ne
[GetAnimationFrame(ti
->tile
)];
3151 case APT_GRASS_FENCE_NE_FLAG_2
:
3152 t
= &_station_display_datas_airport_flag_grass_fence_ne_2
[GetAnimationFrame(ti
->tile
)];
3157 Owner owner
= GetTileOwner(ti
->tile
);
3160 if (Company::IsValidID(owner
)) {
3161 palette
= COMPANY_SPRITE_COLOUR(owner
);
3163 /* Some stations are not owner by a company, namely oil rigs */
3164 palette
= PALETTE_TO_GREY
;
3167 if (layout
== NULL
&& (t
== NULL
|| t
->seq
== NULL
)) t
= GetStationTileLayout(GetStationType(ti
->tile
), gfx
);
3169 /* don't show foundation for docks */
3170 if (ti
->tileh
!= SLOPE_FLAT
&& !IsDock(ti
->tile
)) {
3171 if (statspec
!= NULL
&& HasBit(statspec
->flags
, SSF_CUSTOM_FOUNDATIONS
)) {
3172 /* Station has custom foundations.
3173 * Check whether the foundation continues beyond the tile's upper sides. */
3176 Slope slope
= GetFoundationPixelSlope(ti
->tile
, &z
);
3177 if (!HasFoundationNW(ti
->tile
, slope
, z
)) SetBit(edge_info
, 0);
3178 if (!HasFoundationNE(ti
->tile
, slope
, z
)) SetBit(edge_info
, 1);
3179 SpriteID image
= GetCustomStationFoundationRelocation(statspec
, st
, ti
->tile
, tile_layout
, edge_info
);
3180 if (image
== 0) goto draw_default_foundation
;
3182 if (HasBit(statspec
->flags
, SSF_EXTENDED_FOUNDATIONS
)) {
3183 /* Station provides extended foundations. */
3185 static const uint8 foundation_parts
[] = {
3186 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3187 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3188 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3189 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3192 AddSortableSpriteToDraw(image
+ foundation_parts
[ti
->tileh
], PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
3194 /* Draw simple foundations, built up from 8 possible foundation sprites. */
3196 /* Each set bit represents one of the eight composite sprites to be drawn.
3197 * 'Invalid' entries will not drawn but are included for completeness. */
3198 static const uint8 composite_foundation_parts
[] = {
3199 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
3200 0x00, 0xD1, 0xE4, 0xE0,
3201 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
3202 0xCA, 0xC9, 0xC4, 0xC0,
3203 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
3204 0xD2, 0x91, 0xE4, 0xA0,
3205 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
3209 uint8 parts
= composite_foundation_parts
[ti
->tileh
];
3211 /* If foundations continue beyond the tile's upper sides then
3212 * mask out the last two pieces. */
3213 if (HasBit(edge_info
, 0)) ClrBit(parts
, 6);
3214 if (HasBit(edge_info
, 1)) ClrBit(parts
, 7);
3217 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
3218 * correct offset for the childsprites.
3219 * So, draw the (completely empty) sprite of the default foundations. */
3220 goto draw_default_foundation
;
3223 StartSpriteCombine();
3224 for (int i
= 0; i
< 8; i
++) {
3225 if (HasBit(parts
, i
)) {
3226 AddSortableSpriteToDraw(image
+ i
, PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
3232 OffsetGroundSprite(31, 1);
3233 ti
->z
+= ApplyPixelFoundationToSlope(FOUNDATION_LEVELED
, &ti
->tileh
);
3235 draw_default_foundation
:
3236 DrawFoundation(ti
, FOUNDATION_LEVELED
);
3240 if (IsBuoy(ti
->tile
)) {
3241 DrawWaterClassGround(ti
);
3242 SpriteID sprite
= GetCanalSprite(CF_BUOY
, ti
->tile
);
3243 if (sprite
!= 0) total_offset
= sprite
- SPR_IMG_BUOY
;
3244 } else if (IsDock(ti
->tile
) || (IsOilRig(ti
->tile
) && IsTileOnWater(ti
->tile
))) {
3245 if (ti
->tileh
== SLOPE_FLAT
) {
3246 DrawWaterClassGround(ti
);
3248 assert(IsDock(ti
->tile
));
3249 TileIndex water_tile
= ti
->tile
+ TileOffsByDiagDir(GetDockDirection(ti
->tile
));
3250 WaterClass wc
= GetWaterClass(water_tile
);
3251 if (wc
== WATER_CLASS_SEA
) {
3252 DrawShoreTile(ti
->tileh
);
3254 DrawClearLandTile(ti
, 3);
3258 if (layout
!= NULL
) {
3259 /* Sprite layout which needs preprocessing */
3260 bool separate_ground
= HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
);
3261 uint32 var10_values
= layout
->PrepareLayout(total_offset
, rti
->fallback_railtype
, 0, 0, separate_ground
);
3263 FOR_EACH_SET_BIT(var10
, var10_values
) {
3264 uint32 var10_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, var10
);
3265 layout
->ProcessRegisters(var10
, var10_relocation
, separate_ground
);
3267 tmp_rail_layout
.seq
= layout
->GetLayout(&tmp_rail_layout
.ground
);
3268 t
= &tmp_rail_layout
;
3270 } else if (statspec
!= NULL
) {
3271 /* Simple sprite layout */
3272 ground_relocation
= relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 0);
3273 if (HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
)) {
3274 ground_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 1);
3276 ground_relocation
+= rti
->fallback_railtype
;
3279 SpriteID image
= t
->ground
.sprite
;
3280 PaletteID pal
= t
->ground
.pal
;
3281 RailTrackOffset overlay_offset
;
3282 if (rti
!= NULL
&& rti
->UsesOverlay() && SplitGroundSpriteForOverlay(ti
, &image
, &overlay_offset
)) {
3283 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
);
3284 DrawGroundSprite(image
, PAL_NONE
);
3285 DrawGroundSprite(ground
+ overlay_offset
, PAL_NONE
);
3287 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationReservation(ti
->tile
)) {
3288 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
3289 DrawGroundSprite(overlay
+ overlay_offset
, PALETTE_CRASH
);
3292 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
3293 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
3294 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
));
3296 /* PBS debugging, draw reserved tracks darker */
3297 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationRail(ti
->tile
) && HasStationReservation(ti
->tile
)) {
3298 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
3299 DrawGroundSprite(GetRailStationAxis(ti
->tile
) == AXIS_X
? rti
->base_sprites
.single_x
: rti
->base_sprites
.single_y
, PALETTE_CRASH
);
3304 DrawOverlay(ti
, MP_STATION
);
3306 if (HasStationRail(ti
->tile
) && HasRailCatenaryDrawn(GetRailType(ti
->tile
))) DrawRailCatenary(ti
);
3309 if (HasBit(roadtypes
, ROADTYPE_TRAM
)) {
3310 Axis axis
= GetRoadStopDir(ti
->tile
) == DIAGDIR_NE
? AXIS_X
: AXIS_Y
;
3311 DrawGroundSprite((HasBit(roadtypes
, ROADTYPE_ROAD
) ? SPR_TRAMWAY_OVERLAY
: SPR_TRAMWAY_TRAM
) + (axis
^ 1), PAL_NONE
);
3312 DrawRoadCatenary(ti
, axis
== AXIS_X
? ROAD_X
: ROAD_Y
);
3315 if (IsRailWaypoint(ti
->tile
)) {
3316 /* Don't offset the waypoint graphics; they're always the same. */
3320 DrawRailTileSeq(ti
, t
, TO_BUILDINGS
, total_offset
, relocation
, palette
);
3323 void StationPickerDrawSprite(int x
, int y
, StationType st
, RailType railtype
, RoadType roadtype
, int image
)
3325 int32 total_offset
= 0;
3326 PaletteID pal
= COMPANY_SPRITE_COLOUR(_local_company
);
3327 const DrawTileSprites
*t
= GetStationTileLayout(st
, image
);
3328 const RailtypeInfo
*rti
= NULL
;
3330 if (railtype
!= INVALID_RAILTYPE
) {
3331 rti
= GetRailTypeInfo(railtype
);
3332 total_offset
= rti
->GetRailtypeSpriteOffset();
3335 SpriteID img
= t
->ground
.sprite
;
3336 RailTrackOffset overlay_offset
;
3337 if (rti
!= NULL
&& rti
->UsesOverlay() && SplitGroundSpriteForOverlay(NULL
, &img
, &overlay_offset
)) {
3338 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
3339 DrawSprite(img
, PAL_NONE
, x
, y
);
3340 DrawSprite(ground
+ overlay_offset
, PAL_NONE
, x
, y
);
3342 DrawSprite(img
+ total_offset
, HasBit(img
, PALETTE_MODIFIER_COLOUR
) ? pal
: PAL_NONE
, x
, y
);
3345 if (roadtype
== ROADTYPE_TRAM
) {
3346 DrawSprite(SPR_TRAMWAY_TRAM
+ (t
->ground
.sprite
== SPR_ROAD_PAVED_STRAIGHT_X
? 1 : 0), PAL_NONE
, x
, y
);
3349 /* Default waypoint has no railtype specific sprites */
3350 DrawRailTileSeqInGUI(x
, y
, t
, st
== STATION_WAYPOINT
? 0 : total_offset
, 0, pal
);
3353 static int GetSlopePixelZ_Station(TileIndex tile
, uint x
, uint y
)
3355 return GetTileMaxPixelZ(tile
);
3358 static Foundation
GetFoundation_Station(TileIndex tile
, Slope tileh
)
3360 return FlatteningFoundation(tileh
);
3363 static void GetTileDesc_Station(TileIndex tile
, TileDesc
*td
)
3365 td
->owner
[0] = GetTileOwner(tile
);
3366 if (IsDriveThroughStopTile(tile
)) {
3367 Owner road_owner
= INVALID_OWNER
;
3368 Owner tram_owner
= INVALID_OWNER
;
3369 RoadTypes rts
= GetRoadTypes(tile
);
3370 if (HasBit(rts
, ROADTYPE_ROAD
)) road_owner
= GetRoadOwner(tile
, ROADTYPE_ROAD
);
3371 if (HasBit(rts
, ROADTYPE_TRAM
)) tram_owner
= GetRoadOwner(tile
, ROADTYPE_TRAM
);
3373 /* Is there a mix of owners? */
3374 if ((tram_owner
!= INVALID_OWNER
&& tram_owner
!= td
->owner
[0]) ||
3375 (road_owner
!= INVALID_OWNER
&& road_owner
!= td
->owner
[0])) {
3377 if (road_owner
!= INVALID_OWNER
) {
3378 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_ROAD_OWNER
;
3379 td
->owner
[i
] = road_owner
;
3382 if (tram_owner
!= INVALID_OWNER
) {
3383 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_TRAM_OWNER
;
3384 td
->owner
[i
] = tram_owner
;
3388 td
->build_date
= BaseStation::GetByTile(tile
)->build_date
;
3390 if (HasStationTileRail(tile
)) {
3391 const StationSpec
*spec
= GetStationSpec(tile
);
3394 td
->station_class
= StationClass::Get(spec
->cls_id
)->name
;
3395 td
->station_name
= spec
->name
;
3397 if (spec
->grf_prop
.grffile
!= NULL
) {
3398 const GRFConfig
*gc
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
);
3399 td
->grf
= gc
->GetName();
3403 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(tile
));
3404 td
->rail_speed
= rti
->max_speed
;
3405 td
->railtype
= rti
->strings
.name
;
3408 if (IsAirport(tile
)) {
3409 const AirportSpec
*as
= Station::GetByTile(tile
)->airport
.GetSpec();
3410 td
->airport_class
= AirportClass::Get(as
->cls_id
)->name
;
3411 td
->airport_name
= as
->name
;
3413 const AirportTileSpec
*ats
= AirportTileSpec::GetByTile(tile
);
3414 td
->airport_tile_name
= ats
->name
;
3416 if (as
->grf_prop
.grffile
!= NULL
) {
3417 const GRFConfig
*gc
= GetGRFConfig(as
->grf_prop
.grffile
->grfid
);
3418 td
->grf
= gc
->GetName();
3419 } else if (ats
->grf_prop
.grffile
!= NULL
) {
3420 const GRFConfig
*gc
= GetGRFConfig(ats
->grf_prop
.grffile
->grfid
);
3421 td
->grf
= gc
->GetName();
3426 switch (GetStationType(tile
)) {
3427 default: NOT_REACHED();
3428 case STATION_RAIL
: str
= STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION
; break;
3429 case STATION_AIRPORT
:
3430 str
= (IsHangar(tile
) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR
: STR_LAI_STATION_DESCRIPTION_AIRPORT
);
3432 case STATION_TRUCK
: str
= STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA
; break;
3433 case STATION_BUS
: str
= STR_LAI_STATION_DESCRIPTION_BUS_STATION
; break;
3434 case STATION_OILRIG
: str
= STR_INDUSTRY_NAME_OIL_RIG
; break;
3435 case STATION_DOCK
: str
= STR_LAI_STATION_DESCRIPTION_SHIP_DOCK
; break;
3436 case STATION_BUOY
: str
= STR_LAI_STATION_DESCRIPTION_BUOY
; break;
3437 case STATION_WAYPOINT
: str
= STR_LAI_STATION_DESCRIPTION_WAYPOINT
; break;
3443 static TrackStatus
GetTileTrackStatus_Station(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
3445 TrackBits trackbits
= TRACK_BIT_NONE
;
3448 case TRANSPORT_RAIL
:
3449 if (HasStationRail(tile
) && !IsStationTileBlocked(tile
)) {
3450 trackbits
= TrackToTrackBits(GetRailStationTrack(tile
));
3454 case TRANSPORT_WATER
:
3455 /* buoy is coded as a station, it is always on open water */
3457 trackbits
= TRACK_BIT_ALL
;
3458 /* remove tracks that connect NE map edge */
3459 if (TileX(tile
) == 0) trackbits
&= ~(TRACK_BIT_X
| TRACK_BIT_UPPER
| TRACK_BIT_RIGHT
);
3460 /* remove tracks that connect NW map edge */
3461 if (TileY(tile
) == 0) trackbits
&= ~(TRACK_BIT_Y
| TRACK_BIT_LEFT
| TRACK_BIT_UPPER
);
3465 case TRANSPORT_ROAD
:
3466 if ((GetRoadTypes(tile
) & sub_mode
) != 0 && IsRoadStop(tile
)) {
3467 DiagDirection dir
= GetRoadStopDir(tile
);
3468 Axis axis
= DiagDirToAxis(dir
);
3470 if (side
!= INVALID_DIAGDIR
) {
3471 if (axis
!= DiagDirToAxis(side
) || (IsStandardRoadStopTile(tile
) && dir
!= side
)) break;
3474 trackbits
= AxisToTrackBits(axis
);
3482 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits
), TRACKDIR_BIT_NONE
);
3486 static void TileLoop_Station(TileIndex tile
)
3488 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3489 * hardcoded.....not good */
3490 switch (GetStationType(tile
)) {
3491 case STATION_AIRPORT
:
3492 AirportTileAnimationTrigger(Station::GetByTile(tile
), tile
, AAT_TILELOOP
);
3496 if (!IsTileFlat(tile
)) break; // only handle water part
3499 case STATION_OILRIG
: //(station part)
3501 TileLoop_Water(tile
);
3509 static void AnimateTile_Station(TileIndex tile
)
3511 if (HasStationRail(tile
)) {
3512 AnimateStationTile(tile
);
3516 if (IsAirport(tile
)) {
3517 AnimateAirportTile(tile
);
3522 static bool ClickTile_Station(TileIndex tile
)
3524 const BaseStation
*bst
= BaseStation::GetByTile(tile
);
3526 if (bst
->facilities
& FACIL_WAYPOINT
) {
3527 ShowWaypointWindow(Waypoint::From(bst
));
3528 } else if (IsHangar(tile
)) {
3529 const Station
*st
= Station::From(bst
);
3530 ShowDepotWindow(st
->airport
.GetHangarTile(st
->airport
.GetHangarNum(tile
)), VEH_AIRCRAFT
);
3532 ShowStationViewWindow(bst
->index
);
3537 static VehicleEnterTileStatus
VehicleEnter_Station(Vehicle
*v
, TileIndex tile
, int x
, int y
)
3539 if (v
->type
== VEH_TRAIN
) {
3540 StationID station_id
= GetStationIndex(tile
);
3541 if (v
->current_order
.IsType(OT_GOTO_WAYPOINT
) && v
->current_order
.GetDestination() == station_id
&& v
->current_order
.GetWaypointFlags() & OWF_REVERSE
) {
3542 Train
*t
= Train::From(v
);
3543 // reverse at waypoint
3544 if (t
->reverse_distance
== 0) t
->reverse_distance
= t
->gcache
.cached_total_length
;
3546 if (!v
->current_order
.ShouldStopAtStation(v
, station_id
)) return VETSB_CONTINUE
;
3547 if (!IsRailStation(tile
) || !v
->IsFrontEngine()) return VETSB_CONTINUE
;
3551 int stop
= GetTrainStopLocation(station_id
, tile
, Train::From(v
), &station_ahead
, &station_length
);
3553 /* Stop whenever that amount of station ahead + the distance from the
3554 * begin of the platform to the stop location is longer than the length
3555 * of the platform. Station ahead 'includes' the current tile where the
3556 * vehicle is on, so we need to subtract that. */
3557 if (stop
+ station_ahead
- (int)TILE_SIZE
>= station_length
) return VETSB_CONTINUE
;
3559 DiagDirection dir
= DirToDiagDir(v
->direction
);
3564 if (DiagDirToAxis(dir
) != AXIS_X
) Swap(x
, y
);
3565 if (y
== TILE_SIZE
/ 2) {
3566 if (dir
!= DIAGDIR_SE
&& dir
!= DIAGDIR_SW
) x
= TILE_SIZE
- 1 - x
;
3567 stop
&= TILE_SIZE
- 1;
3570 return VETSB_ENTERED_STATION
| (VehicleEnterTileStatus
)(station_id
<< VETS_STATION_ID_OFFSET
); // enter station
3571 } else if (x
< stop
) {
3572 v
->vehstatus
|= VS_TRAIN_SLOWING
;
3573 uint16 spd
= max(0, (stop
- x
) * 20 - 15);
3574 if (spd
< v
->cur_speed
) v
->cur_speed
= spd
;
3577 } else if (v
->type
== VEH_ROAD
) {
3578 RoadVehicle
*rv
= RoadVehicle::From(v
);
3579 if (rv
->state
< RVSB_IN_ROAD_STOP
&& !IsReversingRoadTrackdir((Trackdir
)rv
->state
) && rv
->frame
== 0) {
3580 if (IsRoadStop(tile
) && rv
->IsFrontEngine()) {
3581 /* Attempt to allocate a parking bay in a road stop */
3582 return RoadStop::GetByTile(tile
, GetRoadStopType(tile
))->Enter(rv
) ? VETSB_CONTINUE
: VETSB_CANNOT_ENTER
;
3587 return VETSB_CONTINUE
;
3591 * Run the watched cargo callback for all houses in the catchment area.
3592 * @param st Station.
3594 void TriggerWatchedCargoCallbacks(Station
*st
)
3596 /* Collect cargoes accepted since the last big tick. */
3598 for (CargoID cid
= 0; cid
< NUM_CARGO
; cid
++) {
3599 if (HasBit(st
->goods
[cid
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
)) SetBit(cargoes
, cid
);
3602 /* Anything to do? */
3603 if (cargoes
== 0) return;
3605 /* Loop over all houses in the catchment. */
3606 Rect r
= st
->GetCatchmentRect();
3607 TileArea
ta(TileXY(r
.left
, r
.top
), TileXY(r
.right
, r
.bottom
));
3608 TILE_AREA_LOOP(tile
, ta
) {
3609 if (IsTileType(tile
, MP_HOUSE
)) {
3610 WatchedCargoCallback(tile
, cargoes
);
3616 * This function is called for each station once every 250 ticks.
3617 * Not all stations will get the tick at the same time.
3618 * @param st the station receiving the tick.
3619 * @return true if the station is still valid (wasn't deleted)
3621 static bool StationHandleBigTick(BaseStation
*st
)
3623 if (!st
->IsInUse()) {
3624 if (++st
->delete_ctr
>= 8) delete st
;
3628 if (Station::IsExpected(st
)) {
3629 TriggerWatchedCargoCallbacks(Station::From(st
));
3631 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3632 ClrBit(Station::From(st
)->goods
[i
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
);
3637 if ((st
->facilities
& FACIL_WAYPOINT
) == 0) UpdateStationAcceptance(Station::From(st
), true);
3642 static inline void byte_inc_sat(byte
*p
)
3649 * Truncate the cargo by a specific amount.
3650 * @param cs The type of cargo to perform the truncation for.
3651 * @param ge The goods entry, of the station, to truncate.
3652 * @param amount The amount to truncate the cargo by.
3654 static void TruncateCargo(const CargoSpec
*cs
, GoodsEntry
*ge
, uint amount
= UINT_MAX
)
3656 /* If truncating also punish the source stations' ratings to
3657 * decrease the flow of incoming cargo. */
3659 StationCargoAmountMap waiting_per_source
;
3660 ge
->cargo
.Truncate(amount
, &waiting_per_source
);
3661 for (StationCargoAmountMap::iterator
i(waiting_per_source
.begin()); i
!= waiting_per_source
.end(); ++i
) {
3662 Station
*source_station
= Station::GetIfValid(i
->first
);
3663 if (source_station
== NULL
) continue;
3665 GoodsEntry
&source_ge
= source_station
->goods
[cs
->Index()];
3666 uint source_avg_waiting
= source_ge
.cargo
.AvailableCount() / max(1u, (uint
)source_ge
.cargo
.Packets()->MapSize());
3668 if (i
->second
> source_avg_waiting
) {
3669 source_ge
.max_waiting_cargo
= i
->second
;
3670 source_ge
.punishment_triggered
= true;
3675 static void UpdateStationRating(Station
*st
)
3677 bool waiting_changed
= false;
3679 byte_inc_sat(&st
->time_since_load
);
3680 byte_inc_sat(&st
->time_since_unload
);
3682 const CargoSpec
*cs
;
3683 FOR_ALL_CARGOSPECS(cs
) {
3684 GoodsEntry
*ge
= &st
->goods
[cs
->Index()];
3685 /* Slowly increase the rating back to his original level in the case we
3686 * didn't deliver cargo yet to this station. This happens when a bribe
3687 * failed while you didn't moved that cargo yet to a station. */
3688 if (!ge
->HasRating() && ge
->rating
< INITIAL_STATION_RATING
) {
3692 /* Only change the rating if we are moving this cargo */
3693 if (ge
->HasRating()) {
3694 byte_inc_sat(&ge
->time_since_pickup
);
3695 if (ge
->time_since_pickup
== 255 && _settings_game
.order
.selectgoods
) {
3696 ClrBit(ge
->status
, GoodsEntry::GES_RATING
);
3698 TruncateCargo(cs
, ge
);
3699 waiting_changed
= true;
3705 uint waiting
= ge
->cargo
.AvailableCount();
3707 /* num_dests is at least 1 if there is any cargo as
3708 * INVALID_STATION is also a destination.
3710 uint num_dests
= max(1u, (uint
)ge
->cargo
.Packets()->MapSize());
3712 /* Average amount of cargo per next hop, but prefer solitary stations
3713 * with only one or two next hops. They are allowed to have more
3714 * cargo waiting per next hop.
3715 * With manual cargo distribution waiting_avg = waiting / 1 as then
3716 * INVALID_STATION is the only destination.
3718 uint waiting_avg
= waiting
/ num_dests
;
3720 if (HasBit(cs
->callback_mask
, CBM_CARGO_STATION_RATING_CALC
)) {
3721 /* Perform custom station rating. If it succeeds the speed, days in transit and
3722 * waiting cargo ratings must not be executed. */
3724 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3725 uint last_speed
= ge
->HasVehicleEverTriedLoading() ? ge
->last_speed
: 0xFF;
3727 uint32 var18
= min(ge
->time_since_pickup
, 0xFF) | (min(ge
->max_waiting_cargo
, 0xFFFF) << 8) | (min(last_speed
, 0xFF) << 24);
3728 /* Convert to the 'old' vehicle types */
3729 uint32 var10
= (st
->last_vehicle_type
== VEH_INVALID
) ? 0x0 : (st
->last_vehicle_type
+ 0x10);
3730 uint16 callback
= GetCargoCallback(CBID_CARGO_STATION_RATING_CALC
, var10
, var18
, cs
);
3731 if (callback
!= CALLBACK_FAILED
) {
3733 rating
= GB(callback
, 0, 14);
3735 /* Simulate a 15 bit signed value */
3736 if (HasBit(callback
, 14)) rating
-= 0x4000;
3741 int b
= ge
->last_speed
- 15;
3742 if (b
>= 0) rating
+= b
>> 2;
3744 (rating
-= 90, ge
->max_waiting_cargo
> 2000) ||
3745 (rating
+= 52, ge
->max_waiting_cargo
> 1000) ||
3746 (rating
+= 52, ge
->max_waiting_cargo
> 500) ||
3747 (rating
+= 52, ge
->max_waiting_cargo
> 250) ||
3748 (rating
+= 52, ge
->max_waiting_cargo
> 125) ||
3749 (rating
+= 52, true);
3752 if (Company::IsValidID(st
->owner
) && HasBit(st
->town
->statues
, st
->owner
)) rating
+= 26;
3754 byte age
= ge
->last_age
;
3756 (rating
+= 10, age
>= 20) ||
3757 (rating
+= 10, age
>= 10) ||
3758 (rating
+= 13, true);
3761 int or_
= ge
->rating
; // old rating
3763 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3764 ge
->rating
= rating
= or_
+ Clamp(Clamp(rating
, 0, 255) - or_
, -2, 2);
3766 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3767 * remove some random amount of goods from the station */
3768 if (rating
<= 64 && waiting_avg
>= 100) {
3769 int dec
= Random() & 0x1F;
3770 if (waiting_avg
< 200) dec
&= 7;
3771 waiting
-= (dec
+ 1) * num_dests
;
3772 waiting_changed
= true;
3775 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3776 if (rating
<= 127 && waiting
!= 0) {
3777 uint32 r
= Random();
3778 if (rating
<= (int)GB(r
, 0, 7)) {
3779 /* Need to have int, otherwise it will just overflow etc. */
3780 waiting
= max((int)waiting
- (int)((GB(r
, 8, 2) - 1) * num_dests
), 0);
3781 waiting_changed
= true;
3785 /* At some point we really must cap the cargo. Previously this
3786 * was a strict 4095, but now we'll have a less strict, but
3787 * increasingly aggressive truncation of the amount of cargo. */
3788 static const uint WAITING_CARGO_THRESHOLD
= 1 << 12;
3789 static const uint WAITING_CARGO_CUT_FACTOR
= 1 << 6;
3790 static const uint MAX_WAITING_CARGO
= 1 << 15;
3792 if (waiting
> WAITING_CARGO_THRESHOLD
) {
3793 uint difference
= waiting
- WAITING_CARGO_THRESHOLD
;
3794 waiting
-= (difference
/ WAITING_CARGO_CUT_FACTOR
);
3796 waiting
= min(waiting
, MAX_WAITING_CARGO
);
3797 waiting_changed
= true;
3800 /* We can't truncate cargo that's already reserved for loading.
3801 * Thus StoredCount() here. */
3802 if (waiting_changed
&& waiting
< ge
->cargo
.AvailableCount()) {
3803 /* Feed back the exact own waiting cargo at this station for the
3804 * next rating calculation. */
3805 TruncateCargo(cs
, ge
, ge
->cargo
.AvailableCount() - waiting
);
3808 if (ge
->punishment_triggered
) {
3809 // We were punished by another station. Delay the update of waiting cargo until next rating.
3810 ge
->punishment_in_effect
= true;
3811 ge
->punishment_triggered
= false;
3815 ge
->punishment_in_effect
= false;
3816 ge
->max_waiting_cargo
= waiting_avg
;
3822 StationID index
= st
->index
;
3823 if (waiting_changed
) {
3824 SetWindowDirty(WC_STATION_VIEW
, index
); // update whole window
3826 SetWindowWidgetDirty(WC_STATION_VIEW
, index
, WID_SV_ACCEPT_RATING_LIST
); // update only ratings list
3831 * Reroute cargo of type c at station st or in any vehicles unloading there.
3832 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3833 * @param st Station to be rerouted at.
3834 * @param c Type of cargo.
3835 * @param avoid Original next hop of cargo, avoid this.
3836 * @param avoid2 Another station to be avoided when rerouting.
3838 void RerouteCargo(Station
*st
, CargoID c
, StationID avoid
, StationID avoid2
)
3840 GoodsEntry
&ge
= st
->goods
[c
];
3842 /* Reroute cargo in station. */
3843 ge
.cargo
.Reroute(UINT_MAX
, &ge
.cargo
, avoid
, avoid2
, &ge
);
3845 /* Reroute cargo staged to be transfered. */
3846 for (Vehicle
*v
: st
->loading_vehicles
) {
3847 for (; v
!= NULL
; v
= v
->Next()) {
3848 if (v
->cargo_type
!= c
) continue;
3849 v
->cargo
.Reroute(UINT_MAX
, &v
->cargo
, avoid
, avoid2
, &ge
);
3855 * Check all next hops of cargo packets in this station for existance of a
3856 * a valid link they may use to travel on. Reroute any cargo not having a valid
3857 * link and remove timed out links found like this from the linkgraph. We're
3858 * not all links here as that is expensive and useless. A link no one is using
3859 * doesn't hurt either.
3860 * @param from Station to check.
3862 void DeleteStaleLinks(Station
*from
)
3864 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
3865 const bool auto_distributed
= (_settings_game
.linkgraph
.GetDistributionType(c
) != DT_MANUAL
);
3866 GoodsEntry
&ge
= from
->goods
[c
];
3867 LinkGraph
*lg
= LinkGraph::GetIfValid(ge
.link_graph
);
3868 if (lg
== NULL
) continue;
3869 Node node
= (*lg
)[ge
.node
];
3870 for (EdgeIterator
it(node
.Begin()); it
!= node
.End();) {
3871 Edge edge
= it
->second
;
3872 Station
*to
= Station::Get((*lg
)[it
->first
].Station());
3873 assert(to
->goods
[c
].node
== it
->first
);
3874 ++it
; // Do that before removing the edge. Anything else may crash.
3875 assert(_date
>= edge
.LastUpdate());
3876 uint timeout
= max
<uint
>((LinkGraph::MIN_TIMEOUT_DISTANCE
+ (DistanceManhattan(from
->xy
, to
->xy
) >> 3)) / _settings_game
.economy
.daylength
, 1);
3877 if ((uint
)(_date
- edge
.LastUpdate()) > timeout
) {
3878 bool updated
= false;
3880 if (auto_distributed
) {
3881 /* Have all vehicles refresh their next hops before deciding to
3882 * remove the node. */
3884 SmallVector
<Vehicle
*, 32> vehicles
;
3885 FOR_ALL_ORDER_LISTS(l
) {
3886 bool found_from
= false;
3887 bool found_to
= false;
3888 for (Order
*order
= l
->GetFirstOrder(); order
!= NULL
; order
= order
->next
) {
3889 if (!order
->IsType(OT_GOTO_STATION
) && !order
->IsType(OT_IMPLICIT
)) continue;
3890 if (order
->GetDestination() == from
->index
) {
3892 if (found_to
) break;
3893 } else if (order
->GetDestination() == to
->index
) {
3895 if (found_from
) break;
3898 if (!found_to
|| !found_from
) continue;
3899 *(vehicles
.Append()) = l
->GetFirstSharedVehicle();
3902 Vehicle
**iter
= vehicles
.Begin();
3903 while (iter
!= vehicles
.End()) {
3906 LinkRefresher::Run(v
, false); // Don't allow merging. Otherwise lg might get deleted.
3907 if (edge
.LastUpdate() == _date
) {
3912 Vehicle
*next_shared
= v
->NextShared();
3914 *iter
= next_shared
;
3917 vehicles
.Erase(iter
);
3920 if (iter
== vehicles
.End()) iter
= vehicles
.Begin();
3925 /* If it's still considered dead remove it. */
3926 node
.RemoveEdge(to
->goods
[c
].node
);
3927 ge
.flows
.DeleteFlows(to
->index
);
3928 RerouteCargo(from
, c
, to
->index
, from
->index
);
3930 } else if (edge
.LastUnrestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastUnrestrictedUpdate()) > timeout
) {
3932 ge
.flows
.RestrictFlows(to
->index
);
3933 RerouteCargo(from
, c
, to
->index
, from
->index
);
3934 } else if (edge
.LastRestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastRestrictedUpdate()) > timeout
) {
3938 assert(_date
>= lg
->LastCompression());
3939 if ((uint
)(_date
- lg
->LastCompression()) > max
<uint
>(LinkGraph::COMPRESSION_INTERVAL
/ _settings_game
.economy
.daylength
, 1)) {
3946 * Increase capacity for a link stat given by station cargo and next hop.
3947 * @param st Station to get the link stats from.
3948 * @param cargo Cargo to increase stat for.
3949 * @param next_station_id Station the consist will be travelling to next.
3950 * @param capacity Capacity to add to link stat.
3951 * @param usage Usage to add to link stat.
3952 * @param mode Update mode to be applied.
3954 void IncreaseStats(Station
*st
, CargoID cargo
, StationID next_station_id
, uint capacity
, uint usage
, EdgeUpdateMode mode
)
3956 GoodsEntry
&ge1
= st
->goods
[cargo
];
3957 Station
*st2
= Station::Get(next_station_id
);
3958 GoodsEntry
&ge2
= st2
->goods
[cargo
];
3959 LinkGraph
*lg
= NULL
;
3960 if (ge1
.link_graph
== INVALID_LINK_GRAPH
) {
3961 if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3962 if (LinkGraph::CanAllocateItem()) {
3963 lg
= new LinkGraph(cargo
);
3964 LinkGraphSchedule::instance
.Queue(lg
);
3965 ge2
.link_graph
= lg
->index
;
3966 ge2
.node
= lg
->AddNode(st2
);
3968 DEBUG(misc
, 0, "Can't allocate link graph");
3971 lg
= LinkGraph::Get(ge2
.link_graph
);
3974 ge1
.link_graph
= lg
->index
;
3975 ge1
.node
= lg
->AddNode(st
);
3977 } else if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3978 lg
= LinkGraph::Get(ge1
.link_graph
);
3979 ge2
.link_graph
= lg
->index
;
3980 ge2
.node
= lg
->AddNode(st2
);
3982 lg
= LinkGraph::Get(ge1
.link_graph
);
3983 if (ge1
.link_graph
!= ge2
.link_graph
) {
3984 LinkGraph
*lg2
= LinkGraph::Get(ge2
.link_graph
);
3985 if (lg
->Size() < lg2
->Size()) {
3986 LinkGraphSchedule::instance
.Unqueue(lg
);
3987 lg2
->Merge(lg
); // Updates GoodsEntries of lg
3990 LinkGraphSchedule::instance
.Unqueue(lg2
);
3991 lg
->Merge(lg2
); // Updates GoodsEntries of lg2
3996 (*lg
)[ge1
.node
].UpdateEdge(ge2
.node
, capacity
, usage
, mode
);
4000 /* called for every station each tick */
4001 static void StationHandleSmallTick(BaseStation
*st
)
4003 if ((st
->facilities
& FACIL_WAYPOINT
) != 0 || !st
->IsInUse()) return;
4005 byte b
= st
->delete_ctr
+ 1;
4006 if (b
>= STATION_RATING_TICKS
) b
= 0;
4009 if (b
== 0) UpdateStationRating(Station::From(st
));
4012 void OnTick_Station()
4014 if (_game_mode
== GM_EDITOR
) return;
4017 FOR_ALL_BASE_STATIONS(st
) {
4018 StationHandleSmallTick(st
);
4020 /* Clean up the link graph about once a week. */
4021 if (Station::IsExpected(st
) && (_tick_counter
+ st
->index
) % STATION_LINKGRAPH_TICKS
== 0) {
4022 DeleteStaleLinks(Station::From(st
));
4025 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
4026 * Station index is included so that triggers are not all done
4027 * at the same time. */
4028 if ((_tick_counter
+ st
->index
) % STATION_ACCEPTANCE_TICKS
== 0) {
4029 /* Stop processing this station if it was deleted */
4030 if (!StationHandleBigTick(st
)) continue;
4031 TriggerStationAnimation(st
, st
->xy
, SAT_250_TICKS
);
4032 if (Station::IsExpected(st
)) AirportAnimationTrigger(Station::From(st
), AAT_STATION_250_TICKS
);
4037 /** Monthly loop for stations. */
4038 void StationMonthlyLoop()
4042 FOR_ALL_STATIONS(st
) {
4043 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
4044 GoodsEntry
*ge
= &st
->goods
[i
];
4045 SB(ge
->status
, GoodsEntry::GES_LAST_MONTH
, 1, GB(ge
->status
, GoodsEntry::GES_CURRENT_MONTH
, 1));
4046 ClrBit(ge
->status
, GoodsEntry::GES_CURRENT_MONTH
);
4052 void ModifyStationRatingAround(TileIndex tile
, Owner owner
, int amount
, uint radius
)
4056 FOR_ALL_STATIONS(st
) {
4057 if (st
->owner
== owner
&&
4058 DistanceManhattan(tile
, st
->xy
) <= radius
) {
4059 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
4060 GoodsEntry
*ge
= &st
->goods
[i
];
4062 if (ge
->status
!= 0) {
4063 ge
->rating
= Clamp(ge
->rating
+ amount
, 0, 255);
4070 static uint
UpdateStationWaiting(Station
*st
, CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
)
4072 /* We can't allocate a CargoPacket? Then don't do anything
4073 * at all; i.e. just discard the incoming cargo. */
4074 if (!CargoPacket::CanAllocateItem()) return 0;
4076 GoodsEntry
&ge
= st
->goods
[type
];
4077 amount
+= ge
.amount_fract
;
4078 ge
.amount_fract
= GB(amount
, 0, 8);
4081 /* No new "real" cargo item yet. */
4082 if (amount
== 0) return 0;
4084 StationID next
= ge
.GetVia(st
->index
);
4085 ge
.cargo
.Append(new CargoPacket(st
->index
, st
->xy
, amount
, source_type
, source_id
), next
);
4086 LinkGraph
*lg
= NULL
;
4087 if (ge
.link_graph
== INVALID_LINK_GRAPH
) {
4088 if (LinkGraph::CanAllocateItem()) {
4089 lg
= new LinkGraph(type
);
4090 LinkGraphSchedule::instance
.Queue(lg
);
4091 ge
.link_graph
= lg
->index
;
4092 ge
.node
= lg
->AddNode(st
);
4094 DEBUG(misc
, 0, "Can't allocate link graph");
4097 lg
= LinkGraph::Get(ge
.link_graph
);
4099 if (lg
!= NULL
) (*lg
)[ge
.node
].UpdateSupply(amount
);
4101 if (!ge
.HasRating()) {
4102 InvalidateWindowData(WC_STATION_LIST
, st
->index
);
4103 SetBit(ge
.status
, GoodsEntry::GES_RATING
);
4106 TriggerStationRandomisation(st
, st
->xy
, SRT_NEW_CARGO
, type
);
4107 TriggerStationAnimation(st
, st
->xy
, SAT_NEW_CARGO
, type
);
4108 AirportAnimationTrigger(st
, AAT_STATION_NEW_CARGO
, type
);
4110 SetWindowDirty(WC_STATION_VIEW
, st
->index
);
4111 st
->MarkTilesDirty(true);
4115 static bool IsUniqueStationName(const char *name
)
4119 FOR_ALL_STATIONS(st
) {
4120 if (st
->name
!= NULL
&& strcmp(st
->name
, name
) == 0) return false;
4128 * @param tile unused
4129 * @param flags operation to perform
4130 * @param p1 station ID that is to be renamed
4132 * @param text the new name or an empty string when resetting to the default
4133 * @return the cost of this operation or an error
4135 CommandCost
CmdRenameStation(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
4137 Station
*st
= Station::GetIfValid(p1
);
4138 if (st
== NULL
) return CMD_ERROR
;
4140 CommandCost ret
= CheckOwnership(st
->owner
);
4141 if (ret
.Failed()) return ret
;
4143 bool reset
= StrEmpty(text
);
4146 if (Utf8StringLength(text
) >= MAX_LENGTH_STATION_NAME_CHARS
) return CMD_ERROR
;
4147 if (!IsUniqueStationName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
4150 if (flags
& DC_EXEC
) {
4152 st
->name
= reset
? NULL
: stredup(text
);
4154 st
->UpdateVirtCoord();
4155 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 1);
4158 return CommandCost();
4162 * Find all stations around a rectangular producer (industry, house, headquarter, ...)
4164 * @param location The location/area of the producer
4165 * @param stations The list to store the stations in
4167 void FindStationsAroundTiles(const TileArea
&location
, StationList
*stations
)
4169 /* area to search = producer plus station catchment radius */
4170 uint max_rad
= (_settings_game
.station
.modified_catchment
? MAX_CATCHMENT
: CA_UNMODIFIED
);
4172 uint x
= TileX(location
.tile
);
4173 uint y
= TileY(location
.tile
);
4175 uint min_x
= (x
> max_rad
) ? x
- max_rad
: 0;
4176 uint max_x
= x
+ location
.w
+ max_rad
;
4177 uint min_y
= (y
> max_rad
) ? y
- max_rad
: 0;
4178 uint max_y
= y
+ location
.h
+ max_rad
;
4180 if (min_x
== 0 && _settings_game
.construction
.freeform_edges
) min_x
= 1;
4181 if (min_y
== 0 && _settings_game
.construction
.freeform_edges
) min_y
= 1;
4182 if (max_x
>= MapSizeX()) max_x
= MapSizeX() - 1;
4183 if (max_y
>= MapSizeY()) max_y
= MapSizeY() - 1;
4185 for (uint cy
= min_y
; cy
< max_y
; cy
++) {
4186 for (uint cx
= min_x
; cx
< max_x
; cx
++) {
4187 TileIndex cur_tile
= TileXY(cx
, cy
);
4188 if (!IsTileType(cur_tile
, MP_STATION
)) continue;
4190 Station
*st
= Station::GetByTile(cur_tile
);
4191 /* st can be NULL in case of waypoints */
4192 if (st
== NULL
) continue;
4194 if (_settings_game
.station
.modified_catchment
) {
4195 int rad
= st
->GetCatchmentRadius();
4199 if (rad_x
< -rad
|| rad_x
>= rad
+ location
.w
) continue;
4200 if (rad_y
< -rad
|| rad_y
>= rad
+ location
.h
) continue;
4203 /* Insert the station in the set. This will fail if it has
4204 * already been added.
4206 stations
->Include(st
);
4212 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
4213 * @return pointer to a StationList containing all stations found
4215 const StationList
*StationFinder::GetStations()
4217 if (this->tile
!= INVALID_TILE
) {
4218 FindStationsAroundTiles(*this, &this->stations
);
4219 this->tile
= INVALID_TILE
;
4221 return &this->stations
;
4224 uint
MoveGoodsToStation(CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
, const StationList
*all_stations
)
4226 /* Return if nothing to do. Also the rounding below fails for 0. */
4227 if (amount
== 0) return 0;
4229 Station
*st1
= NULL
; // Station with best rating
4230 Station
*st2
= NULL
; // Second best station
4231 uint best_rating1
= 0; // rating of st1
4232 uint best_rating2
= 0; // rating of st2
4234 for (Station
* const *st_iter
= all_stations
->Begin(); st_iter
!= all_stations
->End(); ++st_iter
) {
4235 Station
*st
= *st_iter
;
4237 /* Is the station reserved exclusively for somebody else? */
4238 if (st
->town
->exclusive_counter
> 0 && st
->town
->exclusivity
!= st
->owner
) continue;
4240 if (st
->goods
[type
].rating
== 0) continue; // Lowest possible rating, better not to give cargo anymore
4242 if (_settings_game
.order
.selectgoods
&& !st
->goods
[type
].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
4244 if (IsCargoInClass(type
, CC_PASSENGERS
)) {
4245 if (st
->facilities
== FACIL_TRUCK_STOP
) continue; // passengers are never served by just a truck stop
4247 if (st
->facilities
== FACIL_BUS_STOP
) continue; // non-passengers are never served by just a bus stop
4250 /* This station can be used, add it to st1/st2 */
4251 if (st1
== NULL
|| st
->goods
[type
].rating
>= best_rating1
) {
4252 st2
= st1
; best_rating2
= best_rating1
; st1
= st
; best_rating1
= st
->goods
[type
].rating
;
4253 } else if (st2
== NULL
|| st
->goods
[type
].rating
>= best_rating2
) {
4254 st2
= st
; best_rating2
= st
->goods
[type
].rating
;
4258 /* no stations around at all? */
4259 if (st1
== NULL
) return 0;
4261 /* From now we'll calculate with fractal cargo amounts.
4262 * First determine how much cargo we really have. */
4263 amount
*= best_rating1
+ 1;
4266 /* only one station around */
4267 return UpdateStationWaiting(st1
, type
, amount
, source_type
, source_id
);
4270 /* several stations around, the best two (highest rating) are in st1 and st2 */
4271 assert(st1
!= NULL
);
4272 assert(st2
!= NULL
);
4273 assert(best_rating1
!= 0 || best_rating2
!= 0);
4275 /* Then determine the amount the worst station gets. We do it this way as the
4276 * best should get a bonus, which in this case is the rounding difference from
4277 * this calculation. In reality that will mean the bonus will be pretty low.
4278 * Nevertheless, the best station should always get the most cargo regardless
4279 * of rounding issues. */
4280 uint worst_cargo
= amount
* best_rating2
/ (best_rating1
+ best_rating2
);
4281 assert(worst_cargo
<= (amount
- worst_cargo
));
4283 /* And then send the cargo to the stations! */
4284 uint moved
= UpdateStationWaiting(st1
, type
, amount
- worst_cargo
, source_type
, source_id
);
4285 /* These two UpdateStationWaiting's can't be in the statement as then the order
4286 * of execution would be undefined and that could cause desyncs with callbacks. */
4287 return moved
+ UpdateStationWaiting(st2
, type
, worst_cargo
, source_type
, source_id
);
4290 void BuildOilRig(TileIndex tile
)
4292 if (!Station::CanAllocateItem()) {
4293 DEBUG(misc
, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile
);
4297 Station
*st
= new Station(tile
);
4298 st
->town
= ClosestTownFromTile(tile
, UINT_MAX
);
4300 st
->string_id
= GenerateStationName(st
, tile
, 1, 1, STATIONNAMING_OILRIG
);
4302 assert(IsTileType(tile
, MP_INDUSTRY
));
4303 DeleteAnimatedTile(tile
);
4304 MakeOilrig(tile
, st
->index
, GetWaterClass(tile
));
4306 st
->owner
= OWNER_NONE
;
4307 st
->airport
.type
= AT_OILRIG
;
4308 st
->airport
.Add(tile
);
4309 st
->dock_station
.tile
= tile
;
4310 st
->facilities
= FACIL_AIRPORT
;
4312 if (!Dock::CanAllocateItem()) {
4313 DEBUG(misc
, 0, "Can't allocate dock for oilrig at 0x%X, reverting to oilrig with airport only", tile
);
4315 st
->docks
= new Dock(tile
, tile
+ ToTileIndexDiff({1, 0}));
4316 st
->dock_station
.tile
= tile
;
4317 st
->facilities
|= FACIL_DOCK
;
4320 st
->build_date
= _date
;
4322 st
->rect
.BeforeAddTile(tile
, StationRect::ADD_FORCE
);
4323 st
->catchment
.BeforeAddTile(tile
, st
->GetCatchmentRadius());
4325 st
->UpdateVirtCoord();
4326 UpdateStationAcceptance(st
, false);
4327 st
->RecomputeIndustriesNear();
4328 ZoningMarkDirtyStationCoverageArea(st
);
4331 void DeleteOilRig(TileIndex tile
)
4333 Station
*st
= Station::GetByTile(tile
);
4334 ZoningMarkDirtyStationCoverageArea(st
);
4336 st
->catchment
.AfterRemoveTile(tile
, st
->GetCatchmentRadius());
4337 MakeWaterKeepingClass(tile
, OWNER_NONE
);
4339 st
->dock_station
.tile
= INVALID_TILE
;
4340 if (st
->docks
!= NULL
) {
4344 st
->airport
.Clear();
4345 st
->facilities
&= ~(FACIL_AIRPORT
| FACIL_DOCK
);
4346 st
->airport
.flags
= 0;
4348 if (Overlays::Instance()->HasStation(st
)) st
->MarkAcceptanceTilesDirty();
4349 st
->rect
.AfterRemoveTile(st
, tile
);
4351 st
->UpdateVirtCoord();
4352 st
->RecomputeIndustriesNear();
4353 if (!st
->IsInUse()) delete st
;
4356 static void ChangeTileOwner_Station(TileIndex tile
, Owner old_owner
, Owner new_owner
)
4358 if (IsRoadStopTile(tile
)) {
4359 for (RoadType rt
= ROADTYPE_ROAD
; rt
< ROADTYPE_END
; rt
++) {
4360 /* Update all roadtypes, no matter if they are present */
4361 if (GetRoadOwner(tile
, rt
) == old_owner
) {
4362 if (HasTileRoadType(tile
, rt
)) {
4363 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4364 Company::Get(old_owner
)->infrastructure
.road
[rt
] -= 2;
4365 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.road
[rt
] += 2;
4367 SetRoadOwner(tile
, rt
, new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
);
4372 if (!IsTileOwner(tile
, old_owner
)) return;
4374 if (new_owner
!= INVALID_OWNER
) {
4375 /* Update company infrastructure counts. Only do it here
4376 * if the new owner is valid as otherwise the clear
4377 * command will do it for us. No need to dirty windows
4378 * here, we'll redraw the whole screen anyway.*/
4379 Company
*old_company
= Company::Get(old_owner
);
4380 Company
*new_company
= Company::Get(new_owner
);
4382 /* Update counts for underlying infrastructure. */
4383 switch (GetStationType(tile
)) {
4385 case STATION_WAYPOINT
:
4386 if (!IsStationTileBlocked(tile
)) {
4387 old_company
->infrastructure
.rail
[GetRailType(tile
)]--;
4388 new_company
->infrastructure
.rail
[GetRailType(tile
)]++;
4394 /* Road stops were already handled above. */
4399 if (GetWaterClass(tile
) == WATER_CLASS_CANAL
) {
4400 old_company
->infrastructure
.water
--;
4401 new_company
->infrastructure
.water
++;
4409 /* Update station tile count. */
4410 if (!IsBuoy(tile
) && !IsAirport(tile
)) {
4411 old_company
->infrastructure
.station
--;
4412 new_company
->infrastructure
.station
++;
4415 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4416 SetTileOwner(tile
, new_owner
);
4417 InvalidateWindowClassesData(WC_STATION_LIST
, 0);
4419 if (IsDriveThroughStopTile(tile
)) {
4420 /* Remove the drive-through road stop */
4421 DoCommand(tile
, 1 | 1 << 8, (GetStationType(tile
) == STATION_TRUCK
) ? ROADSTOP_TRUCK
: ROADSTOP_BUS
, DC_EXEC
| DC_BANKRUPT
, CMD_REMOVE_ROAD_STOP
);
4422 assert(IsTileType(tile
, MP_ROAD
));
4423 /* Change owner of tile and all roadtypes */
4424 ChangeTileOwner(tile
, old_owner
, new_owner
);
4426 DoCommand(tile
, 0, 0, DC_EXEC
| DC_BANKRUPT
, CMD_LANDSCAPE_CLEAR
);
4427 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4428 * Update owner of buoy if it was not removed (was in orders).
4429 * Do not update when owned by OWNER_WATER (sea and rivers). */
4430 if ((IsTileType(tile
, MP_WATER
) || IsBuoyTile(tile
)) && IsTileOwner(tile
, old_owner
)) SetTileOwner(tile
, OWNER_NONE
);
4436 * Check if a drive-through road stop tile can be cleared.
4437 * Road stops built on town-owned roads check the conditions
4438 * that would allow clearing of the original road.
4439 * @param tile road stop tile to check
4440 * @param flags command flags
4441 * @return true if the road can be cleared
4443 static bool CanRemoveRoadWithStop(TileIndex tile
, DoCommandFlag flags
)
4445 /* Yeah... water can always remove stops, right? */
4446 if (_current_company
== OWNER_WATER
) return true;
4448 RoadTypes rts
= GetRoadTypes(tile
);
4449 if (HasBit(rts
, ROADTYPE_TRAM
)) {
4450 Owner tram_owner
= GetRoadOwner(tile
, ROADTYPE_TRAM
);
4451 if (tram_owner
!= OWNER_NONE
&& CheckOwnership(tram_owner
).Failed()) return false;
4453 if (HasBit(rts
, ROADTYPE_ROAD
)) {
4454 Owner road_owner
= GetRoadOwner(tile
, ROADTYPE_ROAD
);
4455 if (road_owner
!= OWNER_TOWN
) {
4456 if (road_owner
!= OWNER_NONE
&& CheckOwnership(road_owner
).Failed()) return false;
4458 if (CheckAllowRemoveRoad(tile
, GetAnyRoadBits(tile
, ROADTYPE_ROAD
), OWNER_TOWN
, ROADTYPE_ROAD
, flags
).Failed()) return false;
4466 * Clear a single tile of a station.
4467 * @param tile The tile to clear.
4468 * @param flags The DoCommand flags related to the "command".
4469 * @return The cost, or error of clearing.
4471 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
)
4473 if (flags
& DC_AUTO
) {
4474 switch (GetStationType(tile
)) {
4476 case STATION_RAIL
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD
);
4477 case STATION_WAYPOINT
: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
4478 case STATION_AIRPORT
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
4479 case STATION_TRUCK
: return_cmd_error(HasTileRoadType(tile
, ROADTYPE_TRAM
) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST
: STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST
);
4480 case STATION_BUS
: return_cmd_error(HasTileRoadType(tile
, ROADTYPE_TRAM
) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST
: STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST
);
4481 case STATION_BUOY
: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY
);
4482 case STATION_DOCK
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST
);
4483 case STATION_OILRIG
:
4484 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG
);
4485 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY
);
4489 switch (GetStationType(tile
)) {
4490 case STATION_RAIL
: return RemoveRailStation(tile
, flags
);
4491 case STATION_WAYPOINT
: return RemoveRailWaypoint(tile
, flags
);
4492 case STATION_AIRPORT
: return RemoveAirport(tile
, flags
);
4494 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4495 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST
);
4497 return RemoveRoadStop(tile
, flags
);
4499 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4500 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST
);
4502 return RemoveRoadStop(tile
, flags
);
4503 case STATION_BUOY
: return RemoveBuoy(tile
, flags
);
4504 case STATION_DOCK
: return RemoveDock(tile
, flags
);
4511 static CommandCost
TerraformTile_Station(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
4513 if (_settings_game
.construction
.build_on_slopes
&& AutoslopeEnabled()) {
4514 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4515 * TTDP does not call it.
4517 if (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
)) {
4518 switch (GetStationType(tile
)) {
4519 case STATION_WAYPOINT
:
4520 case STATION_RAIL
: {
4521 DiagDirection direction
= AxisToDiagDir(GetRailStationAxis(tile
));
4522 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4523 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4524 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4527 case STATION_AIRPORT
:
4528 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4532 DiagDirection direction
= GetRoadStopDir(tile
);
4533 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4534 if (IsDriveThroughStopTile(tile
)) {
4535 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4537 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4544 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
4548 * Get flow for a station.
4549 * @param st Station to get flow for.
4550 * @return Flow for st.
4552 uint
FlowStat::GetShare(StationID st
) const
4555 for (SharesMap::const_iterator it
= this->shares
.begin(); it
!= this->shares
.end(); ++it
) {
4556 if (it
->second
== st
) {
4557 return it
->first
- prev
;
4566 * Get a station a package can be routed to, but exclude the given ones.
4567 * @param excluded StationID not to be selected.
4568 * @param excluded2 Another StationID not to be selected.
4569 * @return A station ID from the shares map.
4571 StationID
FlowStat::GetVia(StationID excluded
, StationID excluded2
) const
4573 if (this->unrestricted
== 0) return INVALID_STATION
;
4574 assert(!this->shares
.empty());
4575 SharesMap::const_iterator it
= this->shares
.upper_bound(RandomRange(this->unrestricted
));
4576 assert(it
!= this->shares
.end() && it
->first
<= this->unrestricted
);
4577 if (it
->second
!= excluded
&& it
->second
!= excluded2
) return it
->second
;
4579 /* We've hit one of the excluded stations.
4580 * Draw another share, from outside its range. */
4582 uint end
= it
->first
;
4583 uint begin
= (it
== this->shares
.begin() ? 0 : (--it
)->first
);
4584 uint interval
= end
- begin
;
4585 if (interval
>= this->unrestricted
) return INVALID_STATION
; // Only one station in the map.
4586 uint new_max
= this->unrestricted
- interval
;
4587 uint rand
= RandomRange(new_max
);
4588 SharesMap::const_iterator it2
= (rand
< begin
) ? this->shares
.upper_bound(rand
) :
4589 this->shares
.upper_bound(rand
+ interval
);
4590 assert(it2
!= this->shares
.end() && it2
->first
<= this->unrestricted
);
4591 if (it2
->second
!= excluded
&& it2
->second
!= excluded2
) return it2
->second
;
4593 /* We've hit the second excluded station.
4594 * Same as before, only a bit more complicated. */
4596 uint end2
= it2
->first
;
4597 uint begin2
= (it2
== this->shares
.begin() ? 0 : (--it2
)->first
);
4598 uint interval2
= end2
- begin2
;
4599 if (interval2
>= new_max
) return INVALID_STATION
; // Only the two excluded stations in the map.
4600 new_max
-= interval2
;
4601 if (begin
> begin2
) {
4602 Swap(begin
, begin2
);
4604 Swap(interval
, interval2
);
4606 rand
= RandomRange(new_max
);
4607 SharesMap::const_iterator it3
= this->shares
.upper_bound(this->unrestricted
);
4609 it3
= this->shares
.upper_bound(rand
);
4610 } else if (rand
< begin2
- interval
) {
4611 it3
= this->shares
.upper_bound(rand
+ interval
);
4613 it3
= this->shares
.upper_bound(rand
+ interval
+ interval2
);
4615 assert(it3
!= this->shares
.end() && it3
->first
<= this->unrestricted
);
4620 * Reduce all flows to minimum capacity so that they don't get in the way of
4621 * link usage statistics too much. Keep them around, though, to continue
4622 * routing any remaining cargo.
4624 void FlowStat::Invalidate()
4626 assert(!this->shares
.empty());
4627 SharesMap new_shares
;
4629 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4630 new_shares
[++i
] = it
->second
;
4631 if (it
->first
== this->unrestricted
) this->unrestricted
= i
;
4633 this->shares
.swap(new_shares
);
4634 assert(!this->shares
.empty() && this->unrestricted
<= (--this->shares
.end())->first
);
4638 * Change share for specified station. By specifing INT_MIN as parameter you
4639 * can erase a share. Newly added flows will be unrestricted.
4640 * @param st Next Hop to be removed.
4641 * @param flow Share to be added or removed.
4643 void FlowStat::ChangeShare(StationID st
, int flow
)
4645 /* We assert only before changing as afterwards the shares can actually
4646 * be empty. In that case the whole flow stat must be deleted then. */
4647 assert(!this->shares
.empty());
4649 uint removed_shares
= 0;
4650 uint added_shares
= 0;
4651 uint last_share
= 0;
4652 SharesMap new_shares
;
4653 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4654 if (it
->second
== st
) {
4656 uint share
= it
->first
- last_share
;
4657 if (flow
== INT_MIN
|| (uint
)(-flow
) >= share
) {
4658 removed_shares
+= share
;
4659 if (it
->first
<= this->unrestricted
) this->unrestricted
-= share
;
4660 if (flow
!= INT_MIN
) flow
+= share
;
4661 last_share
= it
->first
;
4662 continue; // remove the whole share
4664 removed_shares
+= (uint
)(-flow
);
4666 added_shares
+= (uint
)(flow
);
4668 if (it
->first
<= this->unrestricted
) this->unrestricted
+= flow
;
4670 /* If we don't continue above the whole flow has been added or
4674 new_shares
[it
->first
+ added_shares
- removed_shares
] = it
->second
;
4675 last_share
= it
->first
;
4678 new_shares
[last_share
+ (uint
)flow
] = st
;
4679 if (this->unrestricted
< last_share
) {
4680 this->ReleaseShare(st
);
4682 this->unrestricted
+= flow
;
4685 this->shares
.swap(new_shares
);
4689 * Restrict a flow by moving it to the end of the map and decreasing the amount
4690 * of unrestricted flow.
4691 * @param st Station of flow to be restricted.
4693 void FlowStat::RestrictShare(StationID st
)
4695 assert(!this->shares
.empty());
4697 uint last_share
= 0;
4698 SharesMap new_shares
;
4699 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4701 if (it
->first
> this->unrestricted
) return; // Not present or already restricted.
4702 if (it
->second
== st
) {
4703 flow
= it
->first
- last_share
;
4704 this->unrestricted
-= flow
;
4706 new_shares
[it
->first
] = it
->second
;
4709 new_shares
[it
->first
- flow
] = it
->second
;
4711 last_share
= it
->first
;
4713 if (flow
== 0) return;
4714 new_shares
[last_share
+ flow
] = st
;
4715 this->shares
.swap(new_shares
);
4716 assert(!this->shares
.empty());
4720 * Release ("unrestrict") a flow by moving it to the begin of the map and
4721 * increasing the amount of unrestricted flow.
4722 * @param st Station of flow to be released.
4724 void FlowStat::ReleaseShare(StationID st
)
4726 assert(!this->shares
.empty());
4728 uint next_share
= 0;
4730 for (SharesMap::reverse_iterator
it(this->shares
.rbegin()); it
!= this->shares
.rend(); ++it
) {
4731 if (it
->first
< this->unrestricted
) return; // Note: not <= as the share may hit the limit.
4733 flow
= next_share
- it
->first
;
4734 this->unrestricted
+= flow
;
4737 if (it
->first
== this->unrestricted
) return; // !found -> Limit not hit.
4738 if (it
->second
== st
) found
= true;
4740 next_share
= it
->first
;
4742 if (flow
== 0) return;
4743 SharesMap new_shares
;
4744 new_shares
[flow
] = st
;
4745 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4746 if (it
->second
!= st
) {
4747 new_shares
[flow
+ it
->first
] = it
->second
;
4752 this->shares
.swap(new_shares
);
4753 assert(!this->shares
.empty());
4757 * Scale all shares from link graph's runtime to monthly values.
4758 * @param runtime Time the link graph has been running without compression.
4759 * @pre runtime must be greater than 0 as we don't want infinite flow values.
4761 void FlowStat::ScaleToMonthly(uint runtime
)
4763 assert(runtime
> 0);
4764 SharesMap new_shares
;
4766 for (SharesMap::iterator i
= this->shares
.begin(); i
!= this->shares
.end(); ++i
) {
4767 share
= max(share
+ 1, i
->first
* 30 / runtime
);
4768 new_shares
[share
] = i
->second
;
4769 if (this->unrestricted
== i
->first
) this->unrestricted
= share
;
4771 this->shares
.swap(new_shares
);
4775 * Add some flow from "origin", going via "via".
4776 * @param origin Origin of the flow.
4777 * @param via Next hop.
4778 * @param flow Amount of flow to be added.
4780 void FlowStatMap::AddFlow(StationID origin
, StationID via
, uint flow
)
4782 FlowStatMap::iterator origin_it
= this->find(origin
);
4783 if (origin_it
== this->end()) {
4784 this->insert(std::make_pair(origin
, FlowStat(via
, flow
)));
4786 origin_it
->second
.ChangeShare(via
, flow
);
4787 assert(!origin_it
->second
.GetShares()->empty());
4792 * Pass on some flow, remembering it as invalid, for later subtraction from
4793 * locally consumed flow. This is necessary because we can't have negative
4794 * flows and we don't want to sort the flows before adding them up.
4795 * @param origin Origin of the flow.
4796 * @param via Next hop.
4797 * @param flow Amount of flow to be passed.
4799 void FlowStatMap::PassOnFlow(StationID origin
, StationID via
, uint flow
)
4801 FlowStatMap::iterator prev_it
= this->find(origin
);
4802 if (prev_it
== this->end()) {
4803 FlowStat
fs(via
, flow
);
4804 fs
.AppendShare(INVALID_STATION
, flow
);
4805 this->insert(std::make_pair(origin
, fs
));
4807 prev_it
->second
.ChangeShare(via
, flow
);
4808 prev_it
->second
.ChangeShare(INVALID_STATION
, flow
);
4809 assert(!prev_it
->second
.GetShares()->empty());
4814 * Subtract invalid flows from locally consumed flow.
4815 * @param self ID of own station.
4817 void FlowStatMap::FinalizeLocalConsumption(StationID self
)
4819 for (FlowStatMap::iterator i
= this->begin(); i
!= this->end(); ++i
) {
4820 FlowStat
&fs
= i
->second
;
4821 uint local
= fs
.GetShare(INVALID_STATION
);
4822 if (local
> INT_MAX
) { // make sure it fits in an int
4823 fs
.ChangeShare(self
, -INT_MAX
);
4824 fs
.ChangeShare(INVALID_STATION
, -INT_MAX
);
4827 fs
.ChangeShare(self
, -(int)local
);
4828 fs
.ChangeShare(INVALID_STATION
, -(int)local
);
4830 /* If the local share is used up there must be a share for some
4831 * remote station. */
4832 assert(!fs
.GetShares()->empty());
4837 * Delete all flows at a station for specific cargo and destination.
4838 * @param via Remote station of flows to be deleted.
4839 * @return IDs of source stations for which the complete FlowStat, not only a
4840 * share, has been erased.
4842 StationIDStack
FlowStatMap::DeleteFlows(StationID via
)
4845 for (FlowStatMap::iterator f_it
= this->begin(); f_it
!= this->end();) {
4846 FlowStat
&s_flows
= f_it
->second
;
4847 s_flows
.ChangeShare(via
, INT_MIN
);
4848 if (s_flows
.GetShares()->empty()) {
4849 ret
.Push(f_it
->first
);
4850 this->erase(f_it
++);
4859 * Restrict all flows at a station for specific cargo and destination.
4860 * @param via Remote station of flows to be restricted.
4862 void FlowStatMap::RestrictFlows(StationID via
)
4864 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4865 it
->second
.RestrictShare(via
);
4870 * Release all flows at a station for specific cargo and destination.
4871 * @param via Remote station of flows to be released.
4873 void FlowStatMap::ReleaseFlows(StationID via
)
4875 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4876 it
->second
.ReleaseShare(via
);
4881 * Get the sum of all flows from this FlowStatMap.
4882 * @return sum of all flows.
4884 uint
FlowStatMap::GetFlow() const
4887 for (FlowStatMap::const_iterator i
= this->begin(); i
!= this->end(); ++i
) {
4888 ret
+= (--(i
->second
.GetShares()->end()))->first
;
4894 * Get the sum of flows via a specific station from this FlowStatMap.
4895 * @param via Remote station to look for.
4896 * @return all flows for 'via' added up.
4898 uint
FlowStatMap::GetFlowVia(StationID via
) const
4901 for (FlowStatMap::const_iterator i
= this->begin(); i
!= this->end(); ++i
) {
4902 ret
+= i
->second
.GetShare(via
);
4908 * Get the sum of flows from a specific station from this FlowStatMap.
4909 * @param from Origin station to look for.
4910 * @return all flows from 'from' added up.
4912 uint
FlowStatMap::GetFlowFrom(StationID from
) const
4914 FlowStatMap::const_iterator i
= this->find(from
);
4915 if (i
== this->end()) return 0;
4916 return (--(i
->second
.GetShares()->end()))->first
;
4920 * Get the flow from a specific station via a specific other station.
4921 * @param from Origin station to look for.
4922 * @param via Remote station to look for.
4923 * @return flow share originating at 'from' and going to 'via'.
4925 uint
FlowStatMap::GetFlowFromVia(StationID from
, StationID via
) const
4927 FlowStatMap::const_iterator i
= this->find(from
);
4928 if (i
== this->end()) return 0;
4929 return i
->second
.GetShare(via
);
4932 extern const TileTypeProcs _tile_type_station_procs
= {
4933 DrawTile_Station
, // draw_tile_proc
4934 GetSlopePixelZ_Station
, // get_slope_z_proc
4935 ClearTile_Station
, // clear_tile_proc
4936 NULL
, // add_accepted_cargo_proc
4937 GetTileDesc_Station
, // get_tile_desc_proc
4938 GetTileTrackStatus_Station
, // get_tile_track_status_proc
4939 ClickTile_Station
, // click_tile_proc
4940 AnimateTile_Station
, // animate_tile_proc
4941 TileLoop_Station
, // tile_loop_proc
4942 ChangeTileOwner_Station
, // change_tile_owner_proc
4943 NULL
, // add_produced_cargo_proc
4944 VehicleEnter_Station
, // vehicle_enter_tile_proc
4945 GetFoundation_Station
, // get_foundation_proc
4946 TerraformTile_Station
, // terraform_tile_proc