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();
457 void Station::UpdateCargoHistory()
460 FOR_ALL_CARGOSPECS(cs
) {
461 auto amount
= this->goods
[cs
->Index()].cargo
.AvailableCount();
463 std::rotate(std::begin(this->station_cargo_history
) + cs
->Index() * MAX_STATION_CARGO_HISTORY_DAYS
,
464 std::begin(this->station_cargo_history
) + cs
->Index() * MAX_STATION_CARGO_HISTORY_DAYS
+ 1,
465 std::begin(this->station_cargo_history
) + (cs
->Index() + 1) * MAX_STATION_CARGO_HISTORY_DAYS
);
467 this->station_cargo_history
[(cs
->Index() + 1) * MAX_STATION_CARGO_HISTORY_DAYS
- 1] = std::clamp(amount
/ STATION_CARGO_HISTORY_FACTOR
, (uint
)0, (uint
)UINT8_MAX
);
472 * Update the virtual coords needed to draw the station sign.
474 void Station::UpdateVirtCoord()
476 Point pt
= RemapCoords2(TileX(this->xy
) * TILE_SIZE
, TileY(this->xy
) * TILE_SIZE
);
478 pt
.y
-= 32 * ZOOM_LVL_BASE
;
479 if ((this->facilities
& FACIL_AIRPORT
) && this->airport
.type
== AT_OILRIG
) pt
.y
-= 16 * ZOOM_LVL_BASE
;
481 SetDParam(0, this->index
);
482 SetDParam(1, this->facilities
);
483 this->sign
.UpdatePosition(pt
.x
, pt
.y
, STR_VIEWPORT_STATION
);
485 SetWindowDirty(WC_STATION_VIEW
, this->index
);
488 /** Update the virtual coords needed to draw the station sign for all stations. */
489 void UpdateAllStationVirtCoords()
493 FOR_ALL_BASE_STATIONS(st
) {
494 st
->UpdateVirtCoord();
499 * Get a mask of the cargo types that the station accepts.
500 * @param st Station to query
501 * @return the expected mask
503 static uint
GetAcceptanceMask(const Station
*st
)
507 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
508 if (HasBit(st
->goods
[i
].status
, GoodsEntry::GES_ACCEPTANCE
)) mask
|= 1 << i
;
514 * Items contains the two cargo names that are to be accepted or rejected.
515 * msg is the string id of the message to display.
517 static void ShowRejectOrAcceptNews(const Station
*st
, uint num_items
, CargoID
*cargo
, StringID msg
)
519 for (uint i
= 0; i
< num_items
; i
++) {
520 SetDParam(i
+ 1, CargoSpec::Get(cargo
[i
])->name
);
523 SetDParam(0, st
->index
);
524 AddNewsItem(msg
, NT_ACCEPTANCE
, NF_INCOLOUR
| NF_SMALL
, NR_STATION
, st
->index
);
528 * Get the cargo types being produced around the tile (in a rectangle).
529 * @param tile Northtile of area
530 * @param w X extent of the area
531 * @param h Y extent of the area
532 * @param rad Search radius in addition to the given area
534 CargoArray
GetProductionAroundTiles(TileIndex tile
, int w
, int h
, int rad
)
541 /* expand the region by rad tiles on each side
542 * while making sure that we remain inside the board. */
543 int x2
= min(x
+ w
+ rad
, MapSizeX());
544 int x1
= max(x
- rad
, 0);
546 int y2
= min(y
+ h
+ rad
, MapSizeY());
547 int y1
= max(y
- rad
, 0);
554 TileArea
ta(TileXY(x1
, y1
), TileXY(x2
- 1, y2
- 1));
556 /* Loop over all tiles to get the produced cargo of
557 * everything except industries */
558 TILE_AREA_LOOP(tile
, ta
) AddProducedCargo(tile
, produced
);
560 /* Loop over the industries. They produce cargo for
561 * anything that is within 'rad' from their bounding
562 * box. As such if you have e.g. a oil well the tile
563 * area loop might not hit an industry tile while
564 * the industry would produce cargo for the station.
567 FOR_ALL_INDUSTRIES(i
) {
568 if (!ta
.Intersects(i
->location
)) continue;
570 for (uint j
= 0; j
< lengthof(i
->produced_cargo
); j
++) {
571 CargoID cargo
= i
->produced_cargo
[j
];
572 if (cargo
!= CT_INVALID
) produced
[cargo
]++;
580 * Get the acceptance of cargoes around the tile in 1/8.
581 * @param tile Center of the search area
582 * @param w X extent of area
583 * @param h Y extent of area
584 * @param rad Search radius in addition to given area
585 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be NULL
587 CargoArray
GetAcceptanceAroundTiles(TileIndex tile
, int w
, int h
, int rad
, uint32
*always_accepted
)
589 CargoArray acceptance
;
590 if (always_accepted
!= NULL
) *always_accepted
= 0;
595 /* expand the region by rad tiles on each side
596 * while making sure that we remain inside the board. */
597 int x2
= min(x
+ w
+ rad
, MapSizeX());
598 int y2
= min(y
+ h
+ rad
, MapSizeY());
599 int x1
= max(x
- rad
, 0);
600 int y1
= max(y
- rad
, 0);
607 for (int yc
= y1
; yc
!= y2
; yc
++) {
608 for (int xc
= x1
; xc
!= x2
; xc
++) {
609 TileIndex tile
= TileXY(xc
, yc
);
610 AddAcceptedCargo(tile
, acceptance
, always_accepted
);
618 * Update the acceptance for a station.
619 * @param st Station to update
620 * @param show_msg controls whether to display a message that acceptance was changed.
622 void UpdateStationAcceptance(Station
*st
, bool show_msg
)
624 /* old accepted goods types */
625 uint old_acc
= GetAcceptanceMask(st
);
627 /* And retrieve the acceptance. */
628 CargoArray acceptance
;
629 if (!st
->rect
.IsEmpty()) {
630 acceptance
= GetAcceptanceAroundTiles(
631 TileXY(st
->rect
.left
, st
->rect
.top
),
632 st
->rect
.right
- st
->rect
.left
+ 1,
633 st
->rect
.bottom
- st
->rect
.top
+ 1,
634 st
->GetCatchmentRadius(),
639 /* Adjust in case our station only accepts fewer kinds of goods */
640 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
641 uint amt
= acceptance
[i
];
643 /* Make sure the station can accept the goods type. */
644 bool is_passengers
= IsCargoInClass(i
, CC_PASSENGERS
);
645 if ((!is_passengers
&& !(st
->facilities
& ~FACIL_BUS_STOP
)) ||
646 (is_passengers
&& !(st
->facilities
& ~FACIL_TRUCK_STOP
))) {
650 GoodsEntry
&ge
= st
->goods
[i
];
651 SB(ge
.status
, GoodsEntry::GES_ACCEPTANCE
, 1, amt
>= 8);
652 if (LinkGraph::IsValidID(ge
.link_graph
)) {
653 (*LinkGraph::Get(ge
.link_graph
))[ge
.node
].SetDemand(amt
/ 8);
657 /* Only show a message in case the acceptance was actually changed. */
658 uint new_acc
= GetAcceptanceMask(st
);
659 if (old_acc
== new_acc
) return;
661 /* show a message to report that the acceptance was changed? */
662 if (show_msg
&& st
->owner
== _local_company
&& st
->IsInUse()) {
663 /* List of accept and reject strings for different number of
665 static const StringID accept_msg
[] = {
666 STR_NEWS_STATION_NOW_ACCEPTS_CARGO
,
667 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO
,
669 static const StringID reject_msg
[] = {
670 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO
,
671 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO
,
674 /* Array of accepted and rejected cargo types */
675 CargoID accepts
[2] = { CT_INVALID
, CT_INVALID
};
676 CargoID rejects
[2] = { CT_INVALID
, CT_INVALID
};
680 /* Test each cargo type to see if its acceptance has changed */
681 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
682 if (HasBit(new_acc
, i
)) {
683 if (!HasBit(old_acc
, i
) && num_acc
< lengthof(accepts
)) {
684 /* New cargo is accepted */
685 accepts
[num_acc
++] = i
;
688 if (HasBit(old_acc
, i
) && num_rej
< lengthof(rejects
)) {
689 /* Old cargo is no longer accepted */
690 rejects
[num_rej
++] = i
;
695 /* Show news message if there are any changes */
696 if (num_acc
> 0) ShowRejectOrAcceptNews(st
, num_acc
, accepts
, accept_msg
[num_acc
- 1]);
697 if (num_rej
> 0) ShowRejectOrAcceptNews(st
, num_rej
, rejects
, reject_msg
[num_rej
- 1]);
700 /* redraw the station view since acceptance changed */
701 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ACCEPT_RATING_LIST
);
702 if (Overlays::Instance()->HasStation(st
)) st
->MarkAcceptanceTilesDirty();
705 static void UpdateStationSignCoord(BaseStation
*st
)
707 const StationRect
*r
= &st
->rect
;
709 if (r
->IsEmpty()) return; // no tiles belong to this station
711 /* clamp sign coord to be inside the station rect */
712 st
->xy
= TileXY(ClampU(TileX(st
->xy
), r
->left
, r
->right
), ClampU(TileY(st
->xy
), r
->top
, r
->bottom
));
713 st
->UpdateVirtCoord();
715 if (!Station::IsExpected(st
)) return;
716 Station
*full_station
= Station::From(st
);
717 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
718 LinkGraphID lg
= full_station
->goods
[c
].link_graph
;
719 if (!LinkGraph::IsValidID(lg
)) continue;
720 (*LinkGraph::Get(lg
))[full_station
->goods
[c
].node
].UpdateLocation(st
->xy
);
725 * Common part of building various station parts and possibly attaching them to an existing one.
726 * @param [in,out] st Station to attach to
727 * @param flags Command flags
728 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
729 * @param area Area occupied by the new part
730 * @param name_class Station naming class to use to generate the new station's name
731 * @return Command error that occurred, if any
733 static CommandCost
BuildStationPart(Station
**st
, DoCommandFlag flags
, bool reuse
, TileArea area
, StationNaming name_class
)
735 /* Find a deleted station close to us */
736 if (*st
== NULL
&& reuse
) *st
= GetClosestDeletedStation(area
.tile
);
739 if ((*st
)->owner
!= _current_company
) {
740 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION
);
743 CommandCost ret
= (*st
)->rect
.BeforeAddRect(area
.tile
, area
.w
, area
.h
, StationRect::ADD_TEST
);
744 if (ret
.Failed()) return ret
;
746 /* allocate and initialize new station */
747 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING
);
749 if (flags
& DC_EXEC
) {
750 *st
= new Station(area
.tile
);
752 (*st
)->town
= ClosestTownFromTile(area
.tile
, UINT_MAX
);
753 (*st
)->string_id
= GenerateStationName(*st
, area
.tile
, area
.w
, area
.h
, name_class
);
755 if (Company::IsValidID(_current_company
)) {
756 SetBit((*st
)->town
->have_ratings
, _current_company
);
760 return CommandCost();
764 * This is called right after a station was deleted.
765 * It checks if the whole station is free of substations, and if so, the station will be
766 * deleted after a little while.
769 static void DeleteStationIfEmpty(BaseStation
*st
)
771 if (!st
->IsInUse()) {
772 if (Station::IsExpected(st
)) Overlays::Instance()->RemoveStation((Station
*)st
);
774 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
776 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
777 UpdateStationSignCoord(st
);
779 if (Station::IsExpected(st
)) {
780 MarkWholeScreenDirty();
784 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
);
787 * Checks if the given tile is buildable, flat and has a certain height.
788 * @param tile TileIndex to check.
789 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
790 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
791 * @param allow_steep Whether steep slopes are allowed.
792 * @param check_bridge Check for the existence of a bridge.
793 * @return The cost in case of success, or an error code if it failed.
795 CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
= true)
797 if (check_bridge
&& IsBridgeAbove(tile
)) {
798 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
801 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
802 if (ret
.Failed()) return ret
;
805 Slope tileh
= GetTileSlope(tile
, &z
);
807 /* Prohibit building if
808 * 1) The tile is "steep" (i.e. stretches two height levels).
809 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
811 if ((!allow_steep
&& IsSteepSlope(tileh
)) ||
812 ((!_settings_game
.construction
.build_on_slopes
) && tileh
!= SLOPE_FLAT
)) {
813 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
816 CommandCost
cost(EXPENSES_CONSTRUCTION
);
817 int flat_z
= z
+ GetSlopeMaxZ(tileh
);
818 if (tileh
!= SLOPE_FLAT
) {
819 /* Forbid building if the tile faces a slope in a invalid direction. */
820 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
!= DIAGDIR_END
; dir
++) {
821 if (HasBit(invalid_dirs
, dir
) && !CanBuildDepotByTileh(dir
, tileh
)) {
822 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
825 cost
.AddCost(_price
[PR_BUILD_FOUNDATION
]);
828 /* The level of this tile must be equal to allowed_z. */
832 } else if (allowed_z
!= flat_z
) {
833 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
840 * Tries to clear the given area.
841 * @param tile_area Area to check.
842 * @param flags Operation to perform.
843 * @return The cost in case of success, or an error code if it failed.
845 CommandCost
CheckFlatLand(TileArea tile_area
, DoCommandFlag flags
)
847 CommandCost
cost(EXPENSES_CONSTRUCTION
);
850 TILE_AREA_LOOP(tile_cur
, tile_area
) {
851 CommandCost ret
= CheckBuildableTile(tile_cur
, 0, allowed_z
, true);
852 if (ret
.Failed()) return ret
;
855 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
856 if (ret
.Failed()) return ret
;
864 * Checks given water area for obstacles.
865 * @param tile_area Area to check.
866 * @param flags Operation to perform.
867 * @return The cost in case of success, or an error code if it failed.
869 CommandCost
CheckClearWater(TileArea tile_area
, DoCommandFlag flags
)
871 CommandCost
cost(EXPENSES_CONSTRUCTION
);
873 TILE_AREA_LOOP(tile_cur
, tile_area
) {
874 if (!IsWaterTile(tile_cur
) || GetTileSlope(tile_cur
) != SLOPE_FLAT
) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
875 if (IsBridgeAbove(tile_cur
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
876 CommandCost ret
= EnsureNoVehicleOnGround(tile_cur
);
877 if (ret
.Failed()) return ret
;
884 * Checks if a rail station can be built at the given area.
885 * @param tile_area Area to check.
886 * @param flags Operation to perform.
887 * @param axis Rail station axis.
888 * @param station StationID to be queried and returned if available.
889 * @param rt The rail type to check for (overbuilding rail stations over rail).
890 * @param affected_vehicles List of trains with PBS reservations on the tiles
891 * @param spec_class Station class.
892 * @param spec_index Index into the station class.
893 * @param plat_len Platform length.
894 * @param numtracks Number of platforms.
895 * @return The cost in case of success, or an error code if it failed.
897 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
)
899 CommandCost
cost(EXPENSES_CONSTRUCTION
);
901 uint invalid_dirs
= 5 << axis
;
903 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
904 bool slope_cb
= statspec
!= NULL
&& HasBit(statspec
->callback_mask
, CBM_STATION_SLOPE_CHECK
);
906 TILE_AREA_LOOP(tile_cur
, tile_area
) {
907 CommandCost ret
= CheckBuildableTile(tile_cur
, invalid_dirs
, allowed_z
, false);
908 if (ret
.Failed()) return ret
;
912 /* Do slope check if requested. */
913 ret
= PerformStationTileSlopeCheck(tile_area
.tile
, tile_cur
, statspec
, axis
, plat_len
, numtracks
);
914 if (ret
.Failed()) return ret
;
917 /* if station is set, then we have special handling to allow building on top of already existing stations.
918 * so station points to INVALID_STATION if we can build on any station.
919 * Or it points to a station if we're only allowed to build on exactly that station. */
920 if (station
!= NULL
&& IsTileType(tile_cur
, MP_STATION
)) {
921 if (!IsRailStation(tile_cur
)) {
922 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
924 StationID st
= GetStationIndex(tile_cur
);
925 if (*station
== INVALID_STATION
) {
927 } else if (*station
!= st
) {
928 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
932 /* Rail type is only valid when building a railway station; if station to
933 * build isn't a rail station it's INVALID_RAILTYPE. */
934 if (rt
!= INVALID_RAILTYPE
&&
935 IsPlainRailTile(tile_cur
) && !HasSignals(tile_cur
) &&
936 HasPowerOnRail(GetRailType(tile_cur
), rt
)) {
937 /* Allow overbuilding if the tile:
938 * - has rail, but no signals
939 * - it has exactly one track
940 * - the track is in line with the station
941 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
943 TrackBits tracks
= GetTrackBits(tile_cur
);
944 Track track
= RemoveFirstTrack(&tracks
);
945 Track expected_track
= HasBit(invalid_dirs
, DIAGDIR_NE
) ? TRACK_X
: TRACK_Y
;
947 if (tracks
== TRACK_BIT_NONE
&& track
== expected_track
) {
948 /* Check for trains having a reservation for this tile. */
949 if (HasBit(GetRailReservationTrackBits(tile_cur
), track
)) {
950 Train
*v
= GetTrainForReservation(tile_cur
, track
);
952 *affected_vehicles
.Append() = v
;
955 CommandCost ret
= DoCommand(tile_cur
, 0, track
, flags
, CMD_REMOVE_SINGLE_RAIL
);
956 if (ret
.Failed()) return ret
;
958 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
962 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
963 if (ret
.Failed()) return ret
;
972 * Checks if a road stop can be built at the given tile.
973 * @param tile_area Area to check.
974 * @param flags Operation to perform.
975 * @param invalid_dirs Prohibited directions (set of DiagDirections).
976 * @param is_drive_through True if trying to build a drive-through station.
977 * @param is_truck_stop True when building a truck stop, false otherwise.
978 * @param axis Axis of a drive-through road stop.
979 * @param station StationID to be queried and returned if available.
980 * @param rts Road types to build.
981 * @return The cost in case of success, or an error code if it failed.
983 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
)
985 CommandCost
cost(EXPENSES_CONSTRUCTION
);
988 TILE_AREA_LOOP(cur_tile
, tile_area
) {
989 CommandCost ret
= CheckBuildableTile(cur_tile
, invalid_dirs
, allowed_z
, !is_drive_through
);
990 if (ret
.Failed()) return ret
;
993 /* If station is set, then we have special handling to allow building on top of already existing stations.
994 * Station points to INVALID_STATION if we can build on any station.
995 * Or it points to a station if we're only allowed to build on exactly that station. */
996 if (station
!= NULL
&& IsTileType(cur_tile
, MP_STATION
)) {
997 if (!IsRoadStop(cur_tile
)) {
998 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
1000 if (is_truck_stop
!= IsTruckStop(cur_tile
) ||
1001 is_drive_through
!= IsDriveThroughStopTile(cur_tile
)) {
1002 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
1004 /* Drive-through station in the wrong direction. */
1005 if (is_drive_through
&& IsDriveThroughStopTile(cur_tile
) && DiagDirToAxis(GetRoadStopDir(cur_tile
)) != axis
){
1006 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
1008 StationID st
= GetStationIndex(cur_tile
);
1009 if (*station
== INVALID_STATION
) {
1011 } else if (*station
!= st
) {
1012 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
1016 bool build_over_road
= is_drive_through
&& IsNormalRoadTile(cur_tile
);
1017 /* Road bits in the wrong direction. */
1018 RoadBits rb
= IsNormalRoadTile(cur_tile
) ? GetAllRoadBits(cur_tile
) : ROAD_NONE
;
1019 if (build_over_road
&& (rb
& (axis
== AXIS_X
? ROAD_Y
: ROAD_X
)) != 0) {
1020 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1021 switch (CountBits(rb
)) {
1023 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
1026 if (rb
== ROAD_X
|| rb
== ROAD_Y
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
1027 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER
);
1030 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION
);
1034 RoadTypes cur_rts
= IsNormalRoadTile(cur_tile
) ? GetRoadTypes(cur_tile
) : ROADTYPES_NONE
;
1035 uint num_roadbits
= 0;
1036 if (build_over_road
) {
1037 /* There is a road, check if we can build road+tram stop over it. */
1038 if (HasBit(cur_rts
, ROADTYPE_ROAD
)) {
1039 Owner road_owner
= GetRoadOwner(cur_tile
, ROADTYPE_ROAD
);
1040 if (road_owner
== OWNER_TOWN
) {
1041 if (!_settings_game
.construction
.road_stop_on_town_road
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD
);
1042 } else if (!_settings_game
.construction
.road_stop_on_competitor_road
&& road_owner
!= OWNER_NONE
) {
1043 CommandCost ret
= CheckOwnership(road_owner
);
1044 if (ret
.Failed()) return ret
;
1046 num_roadbits
+= CountBits(GetRoadBits(cur_tile
, ROADTYPE_ROAD
));
1049 /* There is a tram, check if we can build road+tram stop over it. */
1050 if (HasBit(cur_rts
, ROADTYPE_TRAM
)) {
1051 Owner tram_owner
= GetRoadOwner(cur_tile
, ROADTYPE_TRAM
);
1052 if (Company::IsValidID(tram_owner
) &&
1053 (!_settings_game
.construction
.road_stop_on_competitor_road
||
1054 /* Disallow breaking end-of-line of someone else
1055 * so trams can still reverse on this tile. */
1056 HasExactlyOneBit(GetRoadBits(cur_tile
, ROADTYPE_TRAM
)))) {
1057 CommandCost ret
= CheckOwnership(tram_owner
);
1058 if (ret
.Failed()) return ret
;
1060 num_roadbits
+= CountBits(GetRoadBits(cur_tile
, ROADTYPE_TRAM
));
1063 /* Take into account existing roadbits. */
1066 ret
= DoCommand(cur_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
1067 if (ret
.Failed()) return ret
;
1071 uint roadbits_to_build
= CountBits(rts
) * 2 - num_roadbits
;
1072 cost
.AddCost(_price
[PR_BUILD_ROAD
] * roadbits_to_build
);
1079 /** /// Checks if an airport can be built at the given area.
1080 * @param tile_area Area to check.
1081 * @param flags Operation to perform.
1082 * @param station StationID of airport allowed in search area.
1083 * @return The cost in case of success, or an error code if it failed.
1085 static CommandCost
CheckFlatLandAirport(TileArea tile_area
, DoCommandFlag flags
, StationID
*station
)
1087 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1090 TILE_AREA_LOOP(tile_cur
, tile_area
) {
1091 CommandCost ret
= CheckBuildableTile(tile_cur
, 0, allowed_z
, true);
1092 if (ret
.Failed()) return ret
;
1095 /* if station is set, then allow building on top of an already
1096 * existing airport, either the one in *station if it is not
1097 * INVALID_STATION, or anyone otherwise and store which one
1099 if (station
!= NULL
&& IsTileType(tile_cur
, MP_STATION
)) {
1100 if (!IsAirport(tile_cur
)) {
1101 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
1103 StationID st
= GetStationIndex(tile_cur
);
1104 if (*station
== INVALID_STATION
) {
1106 } else if (*station
!= st
) {
1107 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
1111 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
1112 if (ret
.Failed()) return ret
;
1121 * Check whether we can expand the rail part of the given station.
1122 * @param st the station to expand
1123 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1124 * @param axis the axis of the newly build rail
1125 * @return Succeeded or failed command.
1127 CommandCost
CanExpandRailStation(const BaseStation
*st
, TileArea
&new_ta
, Axis axis
)
1129 TileArea cur_ta
= st
->train_station
;
1131 /* determine new size of train station region.. */
1132 int x
= min(TileX(cur_ta
.tile
), TileX(new_ta
.tile
));
1133 int y
= min(TileY(cur_ta
.tile
), TileY(new_ta
.tile
));
1134 new_ta
.w
= max(TileX(cur_ta
.tile
) + cur_ta
.w
, TileX(new_ta
.tile
) + new_ta
.w
) - x
;
1135 new_ta
.h
= max(TileY(cur_ta
.tile
) + cur_ta
.h
, TileY(new_ta
.tile
) + new_ta
.h
) - y
;
1136 new_ta
.tile
= TileXY(x
, y
);
1138 /* make sure the final size is not too big. */
1139 if (new_ta
.w
> _settings_game
.station
.station_spread
|| new_ta
.h
> _settings_game
.station
.station_spread
) {
1140 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1143 return CommandCost();
1146 static inline byte
*CreateSingle(byte
*layout
, int n
)
1149 do *layout
++ = 0; while (--i
);
1150 layout
[((n
- 1) >> 1) - n
] = 2;
1154 static inline byte
*CreateMulti(byte
*layout
, int n
, byte b
)
1157 do *layout
++ = b
; while (--i
);
1160 layout
[n
- 1 - n
] = 0;
1166 * Create the station layout for the given number of tracks and platform length.
1167 * @param layout The layout to write to.
1168 * @param numtracks The number of tracks to write.
1169 * @param plat_len The length of the platforms.
1170 * @param statspec The specification of the station to (possibly) get the layout from.
1172 void GetStationLayout(byte
*layout
, int numtracks
, int plat_len
, const StationSpec
*statspec
)
1174 if (statspec
!= NULL
&& statspec
->lengths
>= plat_len
&&
1175 statspec
->platforms
[plat_len
- 1] >= numtracks
&&
1176 statspec
->layouts
[plat_len
- 1][numtracks
- 1]) {
1177 /* Custom layout defined, follow it. */
1178 memcpy(layout
, statspec
->layouts
[plat_len
- 1][numtracks
- 1],
1179 plat_len
* numtracks
);
1183 if (plat_len
== 1) {
1184 CreateSingle(layout
, numtracks
);
1186 if (numtracks
& 1) layout
= CreateSingle(layout
, plat_len
);
1189 while (--numtracks
>= 0) {
1190 layout
= CreateMulti(layout
, plat_len
, 4);
1191 layout
= CreateMulti(layout
, plat_len
, 6);
1197 * Find a nearby station that joins this station.
1198 * /// @tparam T the class to find a station for
1199 * @param existing_station an existing station we build over
1200 * @param station_to_join the station to join to
1201 * @param adjacent whether adjacent stations are allowed
1202 * @param ta the area of the newly build station
1203 * @param st 'return' pointer for the found station
1204 * @param error_message the error message when building a station on top of others
1205 * @return command cost with the error or 'okay'
1208 CommandCost
FindJoiningBaseStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, T
**st
, StringID error_message
)
1210 assert(*st
== NULL
);
1211 bool check_surrounding
= true;
1213 if (_settings_game
.station
.adjacent_stations
) {
1214 if (existing_station
!= INVALID_STATION
) {
1215 if (adjacent
&& existing_station
!= station_to_join
) {
1216 /* You can't build an adjacent station over the top of one that
1217 * already exists. */
1218 return_cmd_error(error_message
);
1220 /* Extend the current station, and don't check whether it will
1221 * be near any other stations. */
1222 *st
= T::GetIfValid(existing_station
);
1223 check_surrounding
= (*st
== NULL
);
1226 /* There's no station here. Don't check the tiles surrounding this
1227 * one if the company wanted to build an adjacent station. */
1228 if (adjacent
) check_surrounding
= false;
1232 if (check_surrounding
) {
1233 /* Make sure there are no similar stations around us. */
1234 CommandCost ret
= GetStationAround(ta
, existing_station
, st
);
1235 if (ret
.Failed()) return ret
;
1239 if (*st
== NULL
&& station_to_join
!= INVALID_STATION
) *st
= T::GetIfValid(station_to_join
);
1241 return CommandCost();
1245 * Find a nearby station that joins this station.
1246 * @param existing_station an existing station we build over
1247 * @param station_to_join the station to join to
1248 * @param adjacent whether adjacent stations are allowed
1249 * @param ta the area of the newly build station
1250 * @param st 'return' pointer for the found station
1251 * @param error_message the error message when building a station on top of others
1252 * @return command cost with the error or 'okay'
1254 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
)
1256 return FindJoiningBaseStation
<Station
>(existing_station
, station_to_join
, adjacent
, ta
, st
, error_message
);
1260 * Find a nearby waypoint that joins this waypoint.
1261 * @param existing_waypoint an existing waypoint we build over
1262 * @param waypoint_to_join the waypoint to join to
1263 * @param adjacent whether adjacent waypoints are allowed
1264 * @param ta the area of the newly build waypoint
1265 * @param wp 'return' pointer for the found waypoint
1266 * @return command cost with the error or 'okay'
1268 CommandCost
FindJoiningWaypoint(StationID existing_waypoint
, StationID waypoint_to_join
, bool adjacent
, TileArea ta
, Waypoint
**wp
)
1270 return FindJoiningBaseStation
<Waypoint
>(existing_waypoint
, waypoint_to_join
, adjacent
, ta
, wp
, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST
);
1274 * Clear platform reservation during station building/removing.
1275 * @param v vehicle which holds reservation
1277 static void FreeTrainReservation(Train
*v
)
1279 FreeTrainTrackReservation(v
);
1280 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(v
->GetVehicleTrackdir()), false);
1282 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(ReverseTrackdir(v
->GetVehicleTrackdir())), false);
1286 * Restore platform reservation during station building/removing.
1287 * @param v vehicle which held reservation
1289 static void RestoreTrainReservation(Train
*v
)
1291 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(v
->GetVehicleTrackdir()), true);
1292 TryPathReserve(v
, true, true);
1294 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(ReverseTrackdir(v
->GetVehicleTrackdir())), true);
1298 * Build rail station
1299 * @param tile_org northern most position of station dragging/placement
1300 * @param flags operation to perform
1301 * @param p1 various bitstuffed elements
1302 * - p1 = (bit 0- 4) - railtype
1303 * - p1 = (bit 5) - orientation (Axis)
1304 * - p1 = (bit 8-15) - number of tracks
1305 * - p1 = (bit 16-23) - platform length
1306 * - p1 = (bit 24) - allow stations directly adjacent to other stations.
1307 * @param p2 various bitstuffed elements
1308 * - p2 = (bit 0- 7) - custom station class
1309 * - p2 = (bit 8-15) - custom station id
1310 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
1311 * @param text unused
1312 * @return the cost of this operation or an error
1314 CommandCost
CmdBuildRailStation(TileIndex tile_org
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1316 /* Unpack parameters */
1317 RailType rt
= Extract
<RailType
, 0, 5>(p1
);
1318 Axis axis
= Extract
<Axis
, 5, 1>(p1
);
1319 byte numtracks
= GB(p1
, 8, 8);
1320 byte plat_len
= GB(p1
, 16, 8);
1321 bool adjacent
= HasBit(p1
, 24);
1323 StationClassID spec_class
= Extract
<StationClassID
, 0, 8>(p2
);
1324 byte spec_index
= GB(p2
, 8, 8);
1325 StationID station_to_join
= GB(p2
, 16, 16);
1327 /* Does the authority allow this? */
1328 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile_org
, flags
);
1329 if (ret
.Failed()) return ret
;
1331 if (!ValParamRailtype(rt
)) return CMD_ERROR
;
1333 /* Check if the given station class is valid */
1334 if ((uint
)spec_class
>= StationClass::GetClassCount() || spec_class
== STAT_CLASS_WAYP
) return CMD_ERROR
;
1335 if (spec_index
>= StationClass::Get(spec_class
)->GetSpecCount()) return CMD_ERROR
;
1336 if (plat_len
== 0 || numtracks
== 0) return CMD_ERROR
;
1339 if (axis
== AXIS_X
) {
1347 bool reuse
= (station_to_join
!= NEW_STATION
);
1348 if (!reuse
) station_to_join
= INVALID_STATION
;
1349 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1351 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1353 if (h_org
> _settings_game
.station
.station_spread
|| w_org
> _settings_game
.station
.station_spread
) return CMD_ERROR
;
1355 /* these values are those that will be stored in train_tile and station_platforms */
1356 TileArea
new_location(tile_org
, w_org
, h_org
);
1358 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1359 StationID est
= INVALID_STATION
;
1360 SmallVector
<Train
*, 4> affected_vehicles
;
1361 /* Clear the land below the station. */
1362 CommandCost cost
= CheckFlatLandRailStation(new_location
, flags
, axis
, &est
, rt
, affected_vehicles
, spec_class
, spec_index
, plat_len
, numtracks
);
1363 if (cost
.Failed()) return cost
;
1364 /* Add construction expenses. */
1365 cost
.AddCost((numtracks
* _price
[PR_BUILD_STATION_RAIL
] + _price
[PR_BUILD_STATION_RAIL_LENGTH
]) * plat_len
);
1366 cost
.AddCost(numtracks
* plat_len
* RailBuildCost(rt
));
1369 ret
= FindJoiningStation(est
, station_to_join
, adjacent
, new_location
, &st
);
1370 if (ret
.Failed()) return ret
;
1372 ret
= BuildStationPart(&st
, flags
, reuse
, new_location
, STATIONNAMING_RAIL
);
1373 if (ret
.Failed()) return ret
;
1375 if (st
!= NULL
&& st
->train_station
.tile
!= INVALID_TILE
) {
1376 CommandCost ret
= CanExpandRailStation(st
, new_location
, axis
);
1377 if (ret
.Failed()) return ret
;
1380 /* Check if we can allocate a custom stationspec to this station */
1381 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
1382 int specindex
= AllocateSpecToStation(statspec
, st
, (flags
& DC_EXEC
) != 0);
1383 if (specindex
== -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS
);
1385 if (statspec
!= NULL
) {
1386 /* Perform NewStation checks */
1388 /* Check if the station size is permitted */
1389 if (HasBit(statspec
->disallowed_platforms
, min(numtracks
- 1, 7)) || HasBit(statspec
->disallowed_lengths
, min(plat_len
- 1, 7))) {
1393 /* Check if the station is buildable */
1394 if (HasBit(statspec
->callback_mask
, CBM_STATION_AVAIL
)) {
1395 uint16 cb_res
= GetStationCallback(CBID_STATION_AVAILABILITY
, 0, 0, statspec
, NULL
, INVALID_TILE
);
1396 if (cb_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(statspec
->grf_prop
.grffile
, CBID_STATION_AVAILABILITY
, cb_res
)) return CMD_ERROR
;
1400 if (flags
& DC_EXEC
) {
1401 TileIndexDiff tile_delta
;
1403 byte numtracks_orig
;
1406 st
->train_station
= new_location
;
1407 st
->AddFacility(FACIL_TRAIN
, new_location
.tile
);
1409 st
->rect
.BeforeAddRect(tile_org
, w_org
, h_org
, StationRect::ADD_TRY
);
1410 st
->catchment
.BeforeAddRect(tile_org
, w_org
, h_org
, CA_TRAIN
);
1412 if (statspec
!= NULL
) {
1413 /* Include this station spec's animation trigger bitmask
1414 * in the station's cached copy. */
1415 st
->cached_anim_triggers
|= statspec
->animation
.triggers
;
1418 tile_delta
= (axis
== AXIS_X
? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1419 track
= AxisToTrack(axis
);
1421 layout_ptr
= AllocaM(byte
, numtracks
* plat_len
);
1422 GetStationLayout(layout_ptr
, numtracks
, plat_len
, statspec
);
1424 numtracks_orig
= numtracks
;
1426 Company
*c
= Company::Get(st
->owner
);
1427 TileIndex tile_track
= tile_org
;
1429 TileIndex tile
= tile_track
;
1432 byte layout
= *layout_ptr
++;
1433 if (IsRailStationTile(tile
) && HasStationReservation(tile
)) {
1434 /* Check for trains having a reservation for this tile. */
1435 Train
*v
= GetTrainForReservation(tile
, AxisToTrack(GetRailStationAxis(tile
)));
1437 *affected_vehicles
.Append() = v
;
1438 FreeTrainReservation(v
);
1442 /* Railtype can change when overbuilding. */
1443 if (IsRailStationTile(tile
)) {
1444 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[GetRailType(tile
)]--;
1445 c
->infrastructure
.station
--;
1448 /* Remove animation if overbuilding */
1449 DeleteAnimatedTile(tile
);
1450 byte old_specindex
= HasStationTileRail(tile
) ? GetCustomStationSpecIndex(tile
) : 0;
1451 MakeRailStation(tile
, st
->owner
, st
->index
, axis
, layout
& ~1, rt
);
1452 /* Free the spec if we overbuild something */
1453 DeallocateSpecFromStation(st
, old_specindex
);
1455 SetCustomStationSpecIndex(tile
, specindex
);
1456 SetStationTileRandomBits(tile
, GB(Random(), 0, 4));
1457 SetAnimationFrame(tile
, 0);
1459 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[rt
]++;
1460 c
->infrastructure
.station
++;
1462 if (statspec
!= NULL
) {
1463 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1464 uint32 platinfo
= GetPlatformInfo(AXIS_X
, GetStationGfx(tile
), plat_len
, numtracks_orig
, plat_len
- w
, numtracks_orig
- numtracks
, false);
1466 /* As the station is not yet completely finished, the station does not yet exist. */
1467 uint16 callback
= GetStationCallback(CBID_STATION_TILE_LAYOUT
, platinfo
, 0, statspec
, NULL
, tile
);
1468 if (callback
!= CALLBACK_FAILED
) {
1470 SetStationGfx(tile
, (callback
& ~1) + axis
);
1472 ErrorUnknownCallbackResult(statspec
->grf_prop
.grffile
->grfid
, CBID_STATION_TILE_LAYOUT
, callback
);
1476 /* Trigger station animation -- after building? */
1477 TriggerStationAnimation(st
, tile
, SAT_BUILT
);
1482 AddTrackToSignalBuffer(tile_track
, track
, _current_company
);
1483 YapfNotifyTrackLayoutChange(tile_track
, track
);
1484 tile_track
+= tile_delta
^ TileDiffXY(1, 1); // perpendicular to tile_delta
1485 } while (--numtracks
);
1487 for (uint i
= 0; i
< affected_vehicles
.Length(); ++i
) {
1488 /* Restore reservations of trains. */
1489 RestoreTrainReservation(affected_vehicles
[i
]);
1492 /* Check whether we need to expand the reservation of trains already on the station. */
1493 TileArea update_reservation_area
;
1494 if (axis
== AXIS_X
) {
1495 update_reservation_area
= TileArea(tile_org
, 1, numtracks_orig
);
1497 update_reservation_area
= TileArea(tile_org
, numtracks_orig
, 1);
1500 TILE_AREA_LOOP(tile
, update_reservation_area
) {
1501 /* Don't even try to make eye candy parts reserved. */
1502 if (IsStationTileBlocked(tile
)) continue;
1504 DiagDirection dir
= AxisToDiagDir(axis
);
1505 TileIndexDiff tile_offset
= TileOffsByDiagDir(dir
);
1506 TileIndex platform_begin
= tile
;
1507 TileIndex platform_end
= tile
;
1509 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1510 for (TileIndex next_tile
= platform_begin
- tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_begin
); next_tile
-= tile_offset
) {
1511 platform_begin
= next_tile
;
1513 for (TileIndex next_tile
= platform_end
+ tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_end
); next_tile
+= tile_offset
) {
1514 platform_end
= next_tile
;
1517 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1518 bool reservation
= false;
1519 for (TileIndex t
= platform_begin
; !reservation
&& t
<= platform_end
; t
+= tile_offset
) {
1520 reservation
= HasStationReservation(t
);
1524 SetRailStationPlatformReservation(platform_begin
, dir
, true);
1528 st
->MarkTilesDirty(false);
1529 st
->UpdateVirtCoord();
1530 UpdateStationAcceptance(st
, false);
1531 st
->RecomputeIndustriesNear();
1532 ZoningMarkDirtyStationCoverageArea(st
);
1533 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
1534 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
1535 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1536 DirtyCompanyInfrastructureWindows(st
->owner
);
1542 static void MakeRailStationAreaSmaller(BaseStation
*st
)
1544 TileArea ta
= st
->train_station
;
1549 if (ta
.w
!= 0 && ta
.h
!= 0) {
1550 /* check the left side, x = constant, y changes */
1551 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(0, i
));) {
1552 /* the left side is unused? */
1554 ta
.tile
+= TileDiffXY(1, 0);
1560 /* check the right side, x = constant, y changes */
1561 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(ta
.w
- 1, i
));) {
1562 /* the right side is unused? */
1569 /* check the upper side, y = constant, x changes */
1570 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(i
, 0));) {
1571 /* the left side is unused? */
1573 ta
.tile
+= TileDiffXY(0, 1);
1579 /* check the lower side, y = constant, x changes */
1580 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(i
, ta
.h
- 1));) {
1581 /* the left side is unused? */
1591 st
->train_station
= ta
;
1595 * Remove a number of tiles from any rail station within the area.
1596 * @param ta the area to clear station tile from.
1597 * @param affected_stations the stations affected.
1598 * @param flags the command flags.
1599 * @param removal_cost the cost for removing the tile, including the rail.
1600 * @param keep_rail whether to keep the rail of the station.
1601 * @tparam T the type of station to remove.
1602 * @return the number of cleared tiles or an error.
1605 CommandCost
RemoveFromRailBaseStation(TileArea ta
, SmallVector
<T
*, 4> &affected_stations
, DoCommandFlag flags
, Money removal_cost
, bool keep_rail
)
1607 /* Count of the number of tiles removed */
1609 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
1610 /* Accumulator for the errors seen during clearing. If no errors happen,
1611 * and the quantity is 0 there is no station. Otherwise it will be one
1612 * of the other error that got accumulated. */
1615 /* Do the action for every tile into the area */
1616 TILE_AREA_LOOP(tile
, ta
) {
1617 /* Make sure the specified tile is a rail station */
1618 if (!HasStationTileRail(tile
)) continue;
1620 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1621 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1623 if (ret
.Failed()) continue;
1625 /* Check ownership of station */
1626 T
*st
= T::GetByTile(tile
);
1627 if (st
== NULL
) continue;
1629 if (_current_company
!= OWNER_WATER
) {
1630 CommandCost ret
= CheckOwnership(st
->owner
);
1632 if (ret
.Failed()) continue;
1635 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1638 if (keep_rail
|| IsStationTileBlocked(tile
)) {
1639 /* Don't refund the 'steel' of the track when we keep the
1640 * rail, or when the tile didn't have any rail at all. */
1641 total_cost
.AddCost(-_price
[PR_CLEAR_RAIL
]);
1644 if (flags
& DC_EXEC
) {
1645 bool already_affected
= affected_stations
.Include(st
);
1646 if (!already_affected
) ZoningMarkDirtyStationCoverageArea(st
);
1648 /* read variables before the station tile is removed */
1649 uint specindex
= GetCustomStationSpecIndex(tile
);
1650 Track track
= GetRailStationTrack(tile
);
1651 Owner owner
= GetTileOwner(tile
);
1652 RailType rt
= GetRailType(tile
);
1653 if (Station::IsExpected(st
)) ((Station
*)st
)->catchment
.AfterRemoveTile(tile
, CA_TRAIN
);
1656 if (HasStationReservation(tile
)) {
1657 v
= GetTrainForReservation(tile
, track
);
1658 if (v
!= NULL
) FreeTrainReservation(v
);
1661 bool build_rail
= keep_rail
&& !IsStationTileBlocked(tile
);
1662 if (!build_rail
&& !IsStationTileBlocked(tile
)) Company::Get(owner
)->infrastructure
.rail
[rt
]--;
1664 DoClearSquare(tile
);
1665 DeleteNewGRFInspectWindow(GSF_STATIONS
, tile
);
1666 if (Station::IsExpected(st
) && Overlays::Instance()->HasStation((Station
*)st
)) ((Station
*)st
)->MarkAcceptanceTilesDirty();
1667 if (build_rail
) MakeRailNormal(tile
, owner
, TrackToTrackBits(track
), rt
);
1668 if (Station::IsExpected(st
) && Overlays::Instance()->HasStation((Station
*)st
)) ((Station
*)st
)->MarkAcceptanceTilesDirty();
1669 Company::Get(owner
)->infrastructure
.station
--;
1670 DirtyCompanyInfrastructureWindows(owner
);
1672 st
->rect
.AfterRemoveTile(st
, tile
);
1673 AddTrackToSignalBuffer(tile
, track
, owner
);
1674 YapfNotifyTrackLayoutChange(tile
, track
);
1676 DeallocateSpecFromStation(st
, specindex
);
1678 if (v
!= NULL
) RestoreTrainReservation(v
);
1682 if (quantity
== 0) return error
.Failed() ? error
: CommandCost(STR_ERROR_THERE_IS_NO_STATION
);
1684 for (T
**stp
= affected_stations
.Begin(); stp
!= affected_stations
.End(); stp
++) {
1687 /* now we need to make the "spanned" area of the railway station smaller
1688 * if we deleted something at the edges.
1689 * we also need to adjust train_tile. */
1690 MakeRailStationAreaSmaller(st
);
1691 UpdateStationSignCoord(st
);
1693 /* if we deleted the whole station, delete the train facility. */
1694 if (st
->train_station
.tile
== INVALID_TILE
) {
1695 st
->facilities
&= ~FACIL_TRAIN
;
1696 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1697 st
->UpdateVirtCoord();
1698 DeleteStationIfEmpty(st
);
1702 total_cost
.AddCost(quantity
* removal_cost
);
1707 * Remove a single tile from a rail station.
1708 * This allows for custom-built station with holes and weird layouts
1709 * @param start tile of station piece to remove
1710 * @param flags operation to perform
1711 * @param p1 start_tile
1712 * @param p2 various bitstuffed elements
1713 * - p2 = bit 0 - if set keep the rail
1714 * @param text unused
1715 * @return the cost of this operation or an error
1717 CommandCost
CmdRemoveFromRailStation(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1719 TileIndex end
= p1
== 0 ? start
: p1
;
1720 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1722 TileArea
ta(start
, end
);
1723 SmallVector
<Station
*, 4> affected_stations
;
1725 CommandCost ret
= RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_STATION_RAIL
], HasBit(p2
, 0));
1726 if (ret
.Failed()) return ret
;
1728 /* Do all station specific functions here. */
1729 for (Station
**stp
= affected_stations
.Begin(); stp
!= affected_stations
.End(); stp
++) {
1732 if (st
->train_station
.tile
== INVALID_TILE
) SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1733 if (Overlays::Instance()->HasStation(st
)) st
->MarkAcceptanceTilesDirty();
1734 st
->MarkTilesDirty(false);
1735 st
->RecomputeIndustriesNear();
1738 /* Now apply the rail cost to the number that we deleted */
1743 * Remove a single tile from a waypoint.
1744 * This allows for custom-built waypoint with holes and weird layouts
1745 * @param start tile of waypoint piece to remove
1746 * @param flags operation to perform
1747 * @param p1 start_tile
1748 * @param p2 various bitstuffed elements
1749 * - p2 = bit 0 - if set keep the rail
1750 * @param text unused
1751 * @return the cost of this operation or an error
1753 CommandCost
CmdRemoveFromRailWaypoint(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1755 TileIndex end
= p1
== 0 ? start
: p1
;
1756 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1758 TileArea
ta(start
, end
);
1759 SmallVector
<Waypoint
*, 4> affected_stations
;
1761 return RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
], HasBit(p2
, 0));
1766 * Remove a rail station/waypoint
1767 * @param st The station/waypoint to remove the rail part from
1768 * @param flags operation to perform
1769 * @param removal_cost the cost for removing a tile
1770 * @tparam T the type of station to remove
1771 * @return cost or failure of operation
1774 CommandCost
RemoveRailStation(T
*st
, DoCommandFlag flags
, Money removal_cost
)
1776 /* Current company owns the station? */
1777 if (_current_company
!= OWNER_WATER
) {
1778 CommandCost ret
= CheckOwnership(st
->owner
);
1779 if (ret
.Failed()) return ret
;
1782 /* determine width and height of platforms */
1783 TileArea ta
= st
->train_station
;
1785 assert(ta
.w
!= 0 && ta
.h
!= 0);
1787 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1788 /* clear all areas of the station */
1789 TILE_AREA_LOOP(tile
, ta
) {
1790 /* only remove tiles that are actually train station tiles */
1791 if (st
->TileBelongsToRailStation(tile
)) {
1792 SmallVector
<T
*, 4> affected_stations
; // dummy
1793 CommandCost ret
= RemoveFromRailBaseStation(TileArea(tile
, 1, 1), affected_stations
, flags
, removal_cost
, false);
1794 if (ret
.Failed()) return ret
;
1803 * Remove a rail station
1804 * @param tile Tile of the station.
1805 * @param flags operation to perform
1806 * @return cost or failure of operation
1808 static CommandCost
RemoveRailStation(TileIndex tile
, DoCommandFlag flags
)
1810 /* if there is flooding, remove platforms tile by tile */
1811 if (_current_company
== OWNER_WATER
) {
1812 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_STATION
);
1815 Station
*st
= Station::GetByTile(tile
);
1817 if (flags
& DC_EXEC
) ZoningMarkDirtyStationCoverageArea(st
);
1819 CommandCost cost
= RemoveRailStation(st
, flags
, _price
[PR_CLEAR_STATION_RAIL
]);
1821 if (flags
& DC_EXEC
) st
->RecomputeIndustriesNear();
1827 * Remove a rail waypoint
1828 * @param tile Tile of the waypoint.
1829 * @param flags operation to perform
1830 * @return cost or failure of operation
1832 static CommandCost
RemoveRailWaypoint(TileIndex tile
, DoCommandFlag flags
)
1834 /* if there is flooding, remove waypoints tile by tile */
1835 if (_current_company
== OWNER_WATER
) {
1836 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_WAYPOINT
);
1839 return RemoveRailStation(Waypoint::GetByTile(tile
), flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
]);
1844 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1845 * @param st The Station to do the whole procedure for
1846 * @return a pointer to where to link a new RoadStop*
1848 static RoadStop
**FindRoadStopSpot(bool truck_station
, Station
*st
)
1850 RoadStop
**primary_stop
= (truck_station
) ? &st
->truck_stops
: &st
->bus_stops
;
1852 if (*primary_stop
== NULL
) {
1853 /* we have no roadstop of the type yet, so write a "primary stop" */
1854 return primary_stop
;
1856 /* there are stops already, so append to the end of the list */
1857 RoadStop
*stop
= *primary_stop
;
1858 while (stop
->next
!= NULL
) stop
= stop
->next
;
1863 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
);
1866 * Find a nearby station that joins this road stop.
1867 * @param existing_stop an existing road stop we build over
1868 * @param station_to_join the station to join to
1869 * @param adjacent whether adjacent stations are allowed
1870 * @param ta the area of the newly build station
1871 * @param st 'return' pointer for the found station
1872 * @return command cost with the error or 'okay'
1874 static CommandCost
FindJoiningRoadStop(StationID existing_stop
, StationID station_to_join
, bool adjacent
, TileArea ta
, Station
**st
)
1876 return FindJoiningBaseStation
<Station
>(existing_stop
, station_to_join
, adjacent
, ta
, st
, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST
);
1880 * Build a bus or truck stop.
1881 * @param tile Northernmost tile of the stop.
1882 * @param flags Operation to perform.
1883 * @param p1 bit 0..7: Width of the road stop.
1884 * bit 8..15: Length of the road stop.
1885 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1886 * bit 1: 0 For normal stops, 1 for drive-through.
1887 * bit 2..3: The roadtypes.
1888 * bit 5: Allow stations directly adjacent to other stations.
1889 * bit 6..7: Entrance direction (#DiagDirection) for normal stops.
1890 * bit 6: #Axis of the road for drive-through stops.
1891 * bit 16..31: Station ID to join (NEW_STATION if build new one).
1892 * @param text Unused.
1893 * @return The cost of this operation or an error.
1895 CommandCost
CmdBuildRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1897 bool type
= HasBit(p2
, 0);
1898 bool is_drive_through
= HasBit(p2
, 1);
1899 RoadTypes rts
= Extract
<RoadTypes
, 2, 2>(p2
);
1900 StationID station_to_join
= GB(p2
, 16, 16);
1901 bool reuse
= (station_to_join
!= NEW_STATION
);
1902 if (!reuse
) station_to_join
= INVALID_STATION
;
1903 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1905 uint8 width
= (uint8
)GB(p1
, 0, 8);
1906 uint8 lenght
= (uint8
)GB(p1
, 8, 8);
1908 /* Check if the requested road stop is too big */
1909 if (width
> _settings_game
.station
.station_spread
|| lenght
> _settings_game
.station
.station_spread
) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1910 /* Check for incorrect width / length. */
1911 if (width
== 0 || lenght
== 0) return CMD_ERROR
;
1912 /* Check if the first tile and the last tile are valid */
1913 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, lenght
- 1) == INVALID_TILE
) return CMD_ERROR
;
1915 TileArea
roadstop_area(tile
, width
, lenght
);
1917 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1919 if (!HasExactlyOneBit(rts
) || !HasRoadTypesAvail(_current_company
, rts
)) return CMD_ERROR
;
1921 /* Trams only have drive through stops */
1922 if (!is_drive_through
&& HasBit(rts
, ROADTYPE_TRAM
)) return CMD_ERROR
;
1926 if (is_drive_through
) {
1927 /* By definition axis is valid, due to there being 2 axes and reading 1 bit. */
1928 axis
= Extract
<Axis
, 6, 1>(p2
);
1929 ddir
= AxisToDiagDir(axis
);
1931 /* By definition ddir is valid, due to there being 4 diagonal directions and reading 2 bits. */
1932 ddir
= Extract
<DiagDirection
, 6, 2>(p2
);
1933 axis
= DiagDirToAxis(ddir
);
1936 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
1937 if (ret
.Failed()) return ret
;
1939 /* Total road stop cost. */
1940 CommandCost
cost(EXPENSES_CONSTRUCTION
, roadstop_area
.w
* roadstop_area
.h
* _price
[type
? PR_BUILD_STATION_TRUCK
: PR_BUILD_STATION_BUS
]);
1941 StationID est
= INVALID_STATION
;
1942 ret
= CheckFlatLandRoadStop(roadstop_area
, flags
, is_drive_through
? 5 << axis
: 1 << ddir
, is_drive_through
, type
, axis
, &est
, rts
);
1943 if (ret
.Failed()) return ret
;
1947 ret
= FindJoiningRoadStop(est
, station_to_join
, HasBit(p2
, 5), roadstop_area
, &st
);
1948 if (ret
.Failed()) return ret
;
1950 /* Check if this number of road stops can be allocated. */
1951 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
);
1953 ret
= BuildStationPart(&st
, flags
, reuse
, roadstop_area
, STATIONNAMING_ROAD
);
1954 if (ret
.Failed()) return ret
;
1956 if (flags
& DC_EXEC
) {
1957 /* Check every tile in the area. */
1958 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
1959 RoadTypes cur_rts
= GetRoadTypes(cur_tile
);
1960 Owner road_owner
= HasBit(cur_rts
, ROADTYPE_ROAD
) ? GetRoadOwner(cur_tile
, ROADTYPE_ROAD
) : _current_company
;
1961 Owner tram_owner
= HasBit(cur_rts
, ROADTYPE_TRAM
) ? GetRoadOwner(cur_tile
, ROADTYPE_TRAM
) : _current_company
;
1963 if (IsTileType(cur_tile
, MP_STATION
) && IsRoadStop(cur_tile
)) {
1964 RemoveRoadStop(cur_tile
, flags
);
1967 RoadStop
*road_stop
= new RoadStop(cur_tile
);
1968 /* Insert into linked list of RoadStops. */
1969 RoadStop
**currstop
= FindRoadStopSpot(type
, st
);
1970 *currstop
= road_stop
;
1973 st
->truck_station
.Add(cur_tile
);
1975 st
->bus_station
.Add(cur_tile
);
1978 /* Initialize an empty station. */
1979 st
->AddFacility((type
) ? FACIL_TRUCK_STOP
: FACIL_BUS_STOP
, cur_tile
);
1981 st
->rect
.BeforeAddTile(cur_tile
, StationRect::ADD_TRY
);
1982 st
->catchment
.BeforeAddTile(cur_tile
, type
? CA_TRUCK
: CA_BUS
);
1984 RoadStopType rs_type
= type
? ROADSTOP_TRUCK
: ROADSTOP_BUS
;
1985 if (is_drive_through
) {
1986 /* Update company infrastructure counts. If the current tile is a normal
1987 * road tile, count only the new road bits needed to get a full diagonal road. */
1989 FOR_EACH_SET_ROADTYPE(rt
, cur_rts
| rts
) {
1990 Company
*c
= Company::GetIfValid(rt
== ROADTYPE_ROAD
? road_owner
: tram_owner
);
1992 c
->infrastructure
.road
[rt
] += 2 - (IsNormalRoadTile(cur_tile
) && HasBit(cur_rts
, rt
) ? CountBits(GetRoadBits(cur_tile
, rt
)) : 0);
1993 DirtyCompanyInfrastructureWindows(c
->index
);
1997 MakeDriveThroughRoadStop(cur_tile
, st
->owner
, road_owner
, tram_owner
, st
->index
, rs_type
, rts
| cur_rts
, axis
);
1998 road_stop
->MakeDriveThrough();
2000 /* Non-drive-through stop never overbuild and always count as two road bits. */
2001 Company::Get(st
->owner
)->infrastructure
.road
[FIND_FIRST_BIT(rts
)] += 2;
2002 MakeRoadStop(cur_tile
, st
->owner
, st
->index
, rs_type
, rts
, ddir
);
2004 Company::Get(st
->owner
)->infrastructure
.station
++;
2005 DirtyCompanyInfrastructureWindows(st
->owner
);
2007 MarkTileDirtyByTile(cur_tile
);
2009 ZoningMarkDirtyStationCoverageArea(st
);
2013 st
->UpdateVirtCoord();
2014 UpdateStationAcceptance(st
, false);
2015 st
->RecomputeIndustriesNear();
2016 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2017 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2018 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ROADVEHS
);
2024 static Vehicle
*ClearRoadStopStatusEnum(Vehicle
*v
, void *)
2026 if (v
->type
== VEH_ROAD
) {
2027 /* Okay... we are a road vehicle on a drive through road stop.
2028 * But that road stop has just been removed, so we need to make
2029 * sure we are in a valid state... however, vehicles can also
2030 * turn on road stop tiles, so only clear the 'road stop' state
2031 * bits and only when the state was 'in road stop', otherwise
2032 * we'll end up clearing the turn around bits. */
2033 RoadVehicle
*rv
= RoadVehicle::From(v
);
2034 if (HasBit(rv
->state
, RVS_IN_DT_ROAD_STOP
)) rv
->state
&= RVSB_ROAD_STOP_TRACKDIR_MASK
;
2042 * Remove a bus station/truck stop
2043 * @param tile TileIndex been queried
2044 * @param flags operation to perform
2045 * @return cost or failure of operation
2047 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
)
2049 Station
*st
= Station::GetByTile(tile
);
2051 if (_current_company
!= OWNER_WATER
) {
2052 CommandCost ret
= CheckOwnership(st
->owner
);
2053 if (ret
.Failed()) return ret
;
2056 bool is_truck
= IsTruckStop(tile
);
2058 RoadStop
**primary_stop
;
2060 if (is_truck
) { // truck stop
2061 primary_stop
= &st
->truck_stops
;
2062 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_TRUCK
);
2064 primary_stop
= &st
->bus_stops
;
2065 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_BUS
);
2068 assert(cur_stop
!= NULL
);
2070 /* don't do the check for drive-through road stops when company bankrupts */
2071 if (IsDriveThroughStopTile(tile
) && (flags
& DC_BANKRUPT
)) {
2072 /* remove the 'going through road stop' status from all vehicles on that tile */
2073 if (flags
& DC_EXEC
) FindVehicleOnPos(tile
, NULL
, &ClearRoadStopStatusEnum
);
2075 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
2076 if (ret
.Failed()) return ret
;
2079 if (flags
& DC_EXEC
) {
2080 ZoningMarkDirtyStationCoverageArea(st
);
2081 if (*primary_stop
== cur_stop
) {
2082 /* removed the first stop in the list */
2083 *primary_stop
= cur_stop
->next
;
2084 /* removed the only stop? */
2085 if (*primary_stop
== NULL
) {
2086 st
->facilities
&= (is_truck
? ~FACIL_TRUCK_STOP
: ~FACIL_BUS_STOP
);
2089 /* tell the predecessor in the list to skip this stop */
2090 RoadStop
*pred
= *primary_stop
;
2091 while (pred
->next
!= cur_stop
) pred
= pred
->next
;
2092 pred
->next
= cur_stop
->next
;
2095 /* Update company infrastructure counts. */
2097 FOR_EACH_SET_ROADTYPE(rt
, GetRoadTypes(tile
)) {
2098 Company
*c
= Company::GetIfValid(GetRoadOwner(tile
, rt
));
2100 c
->infrastructure
.road
[rt
] -= 2;
2101 DirtyCompanyInfrastructureWindows(c
->index
);
2104 Company::Get(st
->owner
)->infrastructure
.station
--;
2105 DirtyCompanyInfrastructureWindows(st
->owner
);
2107 if (IsDriveThroughStopTile(tile
)) {
2108 /* Clears the tile for us */
2109 cur_stop
->ClearDriveThrough();
2111 DoClearSquare(tile
);
2114 if (Overlays::Instance()->HasStation(st
)) st
->MarkAcceptanceTilesDirty();
2115 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ROADVEHS
);
2118 /* Make sure no vehicle is going to the old roadstop */
2120 FOR_ALL_ROADVEHICLES(v
) {
2121 if (v
->First() == v
&& v
->current_order
.IsType(OT_GOTO_STATION
) &&
2122 v
->dest_tile
== tile
) {
2123 v
->dest_tile
= v
->GetOrderStationLocation(st
->index
);
2127 st
->rect
.AfterRemoveTile(st
, tile
);
2128 st
->catchment
.AfterRemoveTile(tile
, is_truck
? CA_TRUCK
: CA_BUS
);
2130 st
->UpdateVirtCoord();
2131 st
->RecomputeIndustriesNear();
2132 DeleteStationIfEmpty(st
);
2134 /* Update the tile area of the truck/bus stop */
2136 st
->truck_station
.Clear();
2137 for (const RoadStop
*rs
= st
->truck_stops
; rs
!= NULL
; rs
= rs
->next
) st
->truck_station
.Add(rs
->xy
);
2139 st
->bus_station
.Clear();
2140 for (const RoadStop
*rs
= st
->bus_stops
; rs
!= NULL
; rs
= rs
->next
) st
->bus_station
.Add(rs
->xy
);
2144 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[is_truck
? PR_CLEAR_STATION_TRUCK
: PR_CLEAR_STATION_BUS
]);
2148 * Remove bus or truck stops.
2149 * @param tile Northernmost tile of the removal area.
2150 * @param flags Operation to perform.
2151 * @param p1 bit 0..7: Width of the removal area.
2152 * bit 8..15: Height of the removal area.
2153 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
2154 * @param p2 bit 1: 0 to keep roads of all drive-through stops, 1 to remove them.
2155 * @param text Unused.
2156 * @return The cost of this operation or an error.
2158 CommandCost
CmdRemoveRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2160 uint8 width
= (uint8
)GB(p1
, 0, 8);
2161 uint8 height
= (uint8
)GB(p1
, 8, 8);
2162 bool keep_drive_through_roads
= !HasBit(p2
, 1);
2164 /* Check for incorrect width / height. */
2165 if (width
== 0 || height
== 0) return CMD_ERROR
;
2166 /* Check if the first tile and the last tile are valid */
2167 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, height
- 1) == INVALID_TILE
) return CMD_ERROR
;
2168 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2169 if (!keep_drive_through_roads
&& (flags
& DC_BANKRUPT
)) return CMD_ERROR
;
2171 TileArea
roadstop_area(tile
, width
, height
);
2173 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2174 CommandCost
last_error(STR_ERROR_THERE_IS_NO_STATION
);
2175 bool had_success
= false;
2177 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
2178 /* Make sure the specified tile is a road stop of the correct type */
2179 if (!IsTileType(cur_tile
, MP_STATION
) || !IsRoadStop(cur_tile
) || (uint32
)GetRoadStopType(cur_tile
) != GB(p2
, 0, 1)) continue;
2181 /* Save information on to-be-restored roads before the stop is removed. */
2182 RoadTypes rts
= ROADTYPES_NONE
;
2183 RoadBits road_bits
= ROAD_NONE
;
2184 Owner road_owner
[] = { OWNER_NONE
, OWNER_NONE
};
2185 assert_compile(lengthof(road_owner
) == ROADTYPE_END
);
2186 if (IsDriveThroughStopTile(cur_tile
)) {
2188 FOR_EACH_SET_ROADTYPE(rt
, GetRoadTypes(cur_tile
)) {
2189 road_owner
[rt
] = GetRoadOwner(cur_tile
, rt
);
2190 /* If we don't want to preserve our roads then restore only roads of others. */
2191 if (keep_drive_through_roads
|| road_owner
[rt
] != _current_company
) SetBit(rts
, rt
);
2193 road_bits
= AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile
)));
2196 CommandCost ret
= RemoveRoadStop(cur_tile
, flags
);
2204 /* Restore roads. */
2205 if ((flags
& DC_EXEC
) && rts
!= ROADTYPES_NONE
) {
2206 MakeRoadNormal(cur_tile
, road_bits
, rts
, ClosestTownFromTile(cur_tile
, UINT_MAX
)->index
,
2207 road_owner
[ROADTYPE_ROAD
], road_owner
[ROADTYPE_TRAM
]);
2209 /* Update company infrastructure counts. */
2211 FOR_EACH_SET_ROADTYPE(rt
, rts
) {
2212 Company
*c
= Company::GetIfValid(GetRoadOwner(cur_tile
, rt
));
2214 c
->infrastructure
.road
[rt
] += CountBits(road_bits
);
2215 DirtyCompanyInfrastructureWindows(c
->index
);
2221 return had_success
? cost
: last_error
;
2225 * Computes the minimal distance from town's xy to any airport's tile.
2226 * @param it An iterator over all airport tiles.
2227 * @param town_tile town's tile (t->xy)
2228 * @return minimal manhattan distance from town_tile to any airport's tile
2230 static uint
GetMinimalAirportDistanceToTile(TileIterator
&it
, TileIndex town_tile
)
2232 uint mindist
= UINT_MAX
;
2234 for (TileIndex cur_tile
= it
; cur_tile
!= INVALID_TILE
; cur_tile
= ++it
) {
2235 mindist
= min(mindist
, DistanceManhattan(town_tile
, cur_tile
));
2242 * Get a possible noise reduction factor based on distance from town center.
2243 * The further you get, the less noise you generate.
2244 * So all those folks at city council can now happily slee... work in their offices
2245 * @param as airport information
2246 * @param it An iterator over all airport tiles.
2247 * @param town_tile TileIndex of town's center, the one who will receive the airport's candidature
2248 * @return the noise that will be generated, according to distance
2250 uint8
GetAirportNoiseLevelForTown(const AirportSpec
*as
, TileIterator
&it
, TileIndex town_tile
)
2252 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2253 * So no need to go any further*/
2254 if (as
->noise_level
< 2) return as
->noise_level
;
2256 uint distance
= GetMinimalAirportDistanceToTile(it
, town_tile
);
2258 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2259 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2260 * Basically, it says that the less tolerant a town is, the bigger the distance before
2261 * an actual decrease can be granted */
2262 uint8 town_tolerance_distance
= 8 + (_settings_game
.difficulty
.town_council_tolerance
* 4);
2264 /* now, we want to have the distance segmented using the distance judged bareable by town
2265 * This will give us the coefficient of reduction the distance provides. */
2266 uint noise_reduction
= distance
/ town_tolerance_distance
;
2268 /* If the noise reduction equals the airport noise itself, don't give it for free.
2269 * Otherwise, simply reduce the airport's level. */
2270 return noise_reduction
>= as
->noise_level
? 1 : as
->noise_level
- noise_reduction
;
2274 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2275 * If two towns have the same distance, town with lower index is returned.
2276 * @param as airport's description
2277 * @param it An iterator over all airport tiles
2278 * @return nearest town to airport
2280 Town
*AirportGetNearestTown(const AirportSpec
*as
, const TileIterator
&it
)
2282 Town
*t
, *nearest
= NULL
;
2283 uint add
= as
->size_x
+ as
->size_y
- 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2284 uint mindist
= UINT_MAX
- add
; // prevent overflow
2286 if (DistanceManhattan(t
->xy
, it
) < mindist
+ add
) { // avoid calling GetMinimalAirportDistanceToTile too often
2287 TileIterator
*copy
= it
.Clone();
2288 uint dist
= GetMinimalAirportDistanceToTile(*copy
, t
->xy
);
2290 if (dist
< mindist
) {
2301 /** Recalculate the noise generated by the airports of each town */
2302 void UpdateAirportsNoise()
2307 FOR_ALL_TOWNS(t
) t
->noise_reached
= 0;
2309 FOR_ALL_STATIONS(st
) {
2310 if (st
->airport
.tile
!= INVALID_TILE
&& st
->airport
.type
!= AT_OILRIG
) {
2311 const AirportSpec
*as
= st
->airport
.GetSpec();
2312 AirportTileIterator
it(st
);
2313 Town
*nearest
= AirportGetNearestTown(as
, it
);
2314 nearest
->noise_reached
+= GetAirportNoiseLevelForTown(as
, it
, nearest
->xy
);
2321 * /// Checks if an airport can be removed (no aircraft on it or landing)
2322 * @param st Station whose airport is to be removed
2323 * @param flags Operation to perform
2324 * @return Cost or failure of operation
2326 static CommandCost
CanRemoveAirport(Station
*st
, DoCommandFlag flags
)
2329 FOR_ALL_AIRCRAFT(a
) {
2330 if (!a
->IsNormalAircraft()) continue;
2331 if (a
->targetairport
== st
->index
&& a
->state
!= FLYING
)
2332 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY
);
2335 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2337 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2338 if (!st
->TileBelongsToAirport(tile_cur
)) continue;
2340 CommandCost ret
= EnsureNoVehicleOnGround(tile_cur
);
2341 if (ret
.Failed()) return ret
;
2343 cost
.AddCost(_price
[PR_CLEAR_STATION_AIRPORT
]);
2352 * @param tile tile where airport will be built
2353 * @param flags operation to perform
2355 * - p1 = (bit 0- 7) - airport type, @see airport.h
2356 * - p1 = (bit 8-15) - airport layout
2357 * @param p2 various bitstuffed elements
2358 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2359 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2360 * @param text unused
2361 * @return the cost of this operation or an error
2363 CommandCost
CmdBuildAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2365 StationID station_to_join
= GB(p2
, 16, 16);
2366 bool reuse
= (station_to_join
!= NEW_STATION
);
2367 if (!reuse
) station_to_join
= INVALID_STATION
;
2368 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2369 byte airport_type
= GB(p1
, 0, 8);
2370 byte layout
= GB(p1
, 8, 8);
2372 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2374 if (airport_type
>= NUM_AIRPORTS
) return CMD_ERROR
;
2376 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2377 if (ret
.Failed()) return ret
;
2379 /* Check if a valid, buildable airport was chosen for construction */
2380 const AirportSpec
*as
= AirportSpec::Get(airport_type
);
2381 if (!as
->IsAvailable() || layout
>= as
->num_table
) return CMD_ERROR
;
2383 Direction rotation
= as
->rotation
[layout
];
2386 if (rotation
== DIR_E
|| rotation
== DIR_W
) Swap(w
, h
);
2387 TileArea airport_area
= TileArea(tile
, w
, h
);
2389 if (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
) {
2390 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
2393 StationID est
= INVALID_STATION
;
2394 CommandCost cost
= CheckFlatLandAirport(airport_area
, flags
, &est
);
2395 if (cost
.Failed()) return cost
;
2398 ret
= FindJoiningStation(est
, station_to_join
, HasBit(p2
, 0), airport_area
, &st
, STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
2399 if (ret
.Failed()) return ret
;
2402 if (st
== NULL
&& distant_join
) st
= Station::GetIfValid(station_to_join
);
2404 ret
= BuildStationPart(&st
, flags
, reuse
, airport_area
, (GetAirport(airport_type
)->flags
& AirportFTAClass::AIRPLANES
) ? STATIONNAMING_AIRPORT
: STATIONNAMING_HELIPORT
);
2405 if (ret
.Failed()) return ret
;
2407 /* action to be performed */
2409 AIRPORT_NEW
, // airport is a new station
2410 AIRPORT_ADD
, // add an airport to an existing station
2411 AIRPORT_UPGRADE
, // upgrade the airport in a station
2413 (est
!= INVALID_STATION
) ? AIRPORT_UPGRADE
:
2414 (st
!= NULL
) ? AIRPORT_ADD
: AIRPORT_NEW
;
2416 if (action
== AIRPORT_ADD
&& st
->airport
.tile
!= INVALID_TILE
) {
2417 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT
);
2420 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2421 AirportTileTableIterator
iter(as
->table
[layout
], tile
);
2422 Town
*nearest
= AirportGetNearestTown(as
, iter
);
2423 uint newnoise_level
= nearest
->noise_reached
+ GetAirportNoiseLevelForTown(as
, iter
, nearest
->xy
);
2425 if (action
== AIRPORT_UPGRADE
) {
2426 const AirportSpec
*old_as
= st
->airport
.GetSpec();
2427 AirportTileTableIterator
old_iter(old_as
->table
[st
->airport
.layout
], st
->airport
.tile
);
2428 Town
*old_nearest
= AirportGetNearestTown(old_as
, old_iter
);
2429 if (old_nearest
== nearest
) {
2430 newnoise_level
-= GetAirportNoiseLevelForTown(old_as
, old_iter
, nearest
->xy
);
2434 /* Check if local auth would allow a new airport */
2435 StringID authority_refuse_message
= STR_NULL
;
2436 Town
*authority_refuse_town
= NULL
;
2438 if (_settings_game
.economy
.station_noise_level
) {
2439 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2440 if (newnoise_level
> nearest
->MaxTownNoise()) {
2441 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE
;
2442 authority_refuse_town
= nearest
;
2444 } else if (action
!= AIRPORT_UPGRADE
) {
2445 Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
2448 FOR_ALL_STATIONS(st
) {
2449 if (st
->town
== t
&& (st
->facilities
& FACIL_AIRPORT
) && st
->airport
.type
!= AT_OILRIG
) num
++;
2452 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT
;
2453 authority_refuse_town
= t
;
2457 if (authority_refuse_message
!= STR_NULL
) {
2458 SetDParam(0, authority_refuse_town
->index
);
2459 return_cmd_error(authority_refuse_message
);
2462 if (action
== AIRPORT_UPGRADE
) {
2463 /* check that the old airport can be removed */
2464 CommandCost r
= CanRemoveAirport(st
, flags
);
2465 if (r
.Failed()) return r
;
2469 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2470 cost
.AddCost(_price
[PR_BUILD_STATION_AIRPORT
]);
2473 if (flags
& DC_EXEC
) {
2474 if (action
== AIRPORT_UPGRADE
) {
2475 /* delete old airport if upgrading */
2476 const AirportSpec
*old_as
= st
->airport
.GetSpec();
2477 AirportTileTableIterator
old_iter(old_as
->table
[st
->airport
.layout
], st
->airport
.tile
);
2478 Town
*old_nearest
= AirportGetNearestTown(old_as
, old_iter
);
2480 if (old_nearest
!= nearest
) {
2481 old_nearest
->noise_reached
-= GetAirportNoiseLevelForTown(old_as
, old_iter
, old_nearest
->xy
);
2482 if (_settings_game
.economy
.station_noise_level
) {
2483 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2487 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2488 if (IsHangarTile(tile_cur
)) OrderBackup::Reset(tile_cur
, false);
2489 DeleteAnimatedTile(tile_cur
);
2490 DoClearSquare(tile_cur
);
2491 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
);
2494 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2496 WC_VEHICLE_DEPOT
, st
->airport
.GetHangarTile(i
)
2500 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2501 st
->airport
.Clear();
2504 /* Always add the noise, so there will be no need to recalculate when option toggles */
2505 nearest
->noise_reached
= newnoise_level
;
2507 st
->AddFacility(FACIL_AIRPORT
, tile
);
2508 st
->airport
.type
= airport_type
;
2509 st
->airport
.layout
= layout
;
2510 st
->airport
.flags
= 0;
2511 st
->airport
.rotation
= rotation
;
2513 st
->rect
.BeforeAddRect(tile
, w
, h
, StationRect::ADD_TRY
);
2515 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2516 MakeAirport(iter
, st
->owner
, st
->index
, iter
.GetStationGfx(), WATER_CLASS_INVALID
);
2517 SetStationTileRandomBits(iter
, GB(Random(), 0, 4));
2518 st
->airport
.Add(iter
);
2519 st
->catchment
.BeforeAddTile(iter
, as
->catchment
);
2521 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter
.GetStationGfx()))->animation
.status
!= ANIM_STATUS_NO_ANIMATION
) AddAnimatedTile(iter
);
2524 /* Only call the animation trigger after all tiles have been built */
2525 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2526 AirportTileAnimationTrigger(st
, iter
, AAT_BUILT
);
2529 if (action
!= AIRPORT_NEW
) UpdateAirplanesOnNewStation(st
);
2531 if (action
== AIRPORT_UPGRADE
) {
2532 UpdateStationSignCoord(st
);
2534 Company::Get(st
->owner
)->infrastructure
.airport
++;
2535 DirtyCompanyInfrastructureWindows(st
->owner
);
2536 st
->UpdateVirtCoord();
2539 UpdateStationAcceptance(st
, false);
2540 st
->RecomputeIndustriesNear();
2541 ZoningMarkDirtyStationCoverageArea(st
);
2542 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2543 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2544 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2546 if (_settings_game
.economy
.station_noise_level
) {
2547 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2555 * Place a Seaplane Airport.
2556 * @param tile tile where airport will be built
2557 * @param flags operation to perform
2559 * - p1 = (bit 0- 7) - airport type, @see airport.h
2560 * - p1 = (bit 8-15) - airport layout
2561 * @param p2 various bitstuffed elements
2562 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2563 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2564 * @param text unused
2565 * @return the cost of this operation or an error
2567 CommandCost
CmdBuildSeaplaneAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2570 StationID station_to_join
= GB(p2
, 16, 16);
2571 bool reuse
= (station_to_join
!= NEW_STATION
);
2572 if (!reuse
) station_to_join
= INVALID_STATION
;
2573 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2574 byte airport_type
= GB(p1
, 0, 8);
2575 byte layout
= GB(p1
, 8, 8);
2577 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2579 if (airport_type
>= NUM_AIRPORTS
) return CMD_ERROR
;
2582 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2583 if (ret
.Failed()) return ret
;
2585 /* Check if a valid, buildable airport was chosen for construction */
2586 const AirportSpec
*as
= AirportSpec::Get(airport_type
);
2587 if (!as
->IsAvailable() || layout
>= as
->num_table
) return CMD_ERROR
;
2589 Direction rotation
= as
->rotation
[layout
];
2592 if (rotation
== DIR_E
|| rotation
== DIR_W
) Swap(w
, h
);
2593 TileArea airport_area
= TileArea(tile
, w
, h
);
2595 if (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
) {
2596 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
2599 CommandCost cost
= CheckClearWater(airport_area
, flags
);
2600 if (cost
.Failed()) return cost
;
2602 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2603 AirportTileTableIterator
iter(as
->table
[layout
], tile
);
2604 Town
*nearest
= AirportGetNearestTown(as
, iter
);
2605 uint newnoise_level
= GetAirportNoiseLevelForTown(as
, iter
, nearest
->xy
);
2607 /* Check if local auth would allow a new airport */
2608 StringID authority_refuse_message
= STR_NULL
;
2609 Town
*authority_refuse_town
= NULL
;
2611 if (_settings_game
.economy
.station_noise_level
) {
2612 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2613 if ((nearest
->noise_reached
+ newnoise_level
) > nearest
->MaxTownNoise()) {
2614 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE
;
2615 authority_refuse_town
= nearest
;
2618 Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
2621 FOR_ALL_STATIONS(st
) {
2622 if (st
->town
== t
&& (st
->facilities
& FACIL_AIRPORT
) && st
->airport
.type
!= AT_OILRIG
) num
++;
2625 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT
;
2626 authority_refuse_town
= t
;
2630 if (authority_refuse_message
!= STR_NULL
) {
2631 SetDParam(0, authority_refuse_town
->index
);
2632 return_cmd_error(authority_refuse_message
);
2636 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, HasBit(p2
, 0), airport_area
, &st
);
2637 if (ret
.Failed()) return ret
;
2640 if (st
== NULL
&& distant_join
) st
= Station::GetIfValid(station_to_join
);
2642 ret
= BuildStationPart(&st
, flags
, reuse
, airport_area
, STATIONNAMING_AIRPORT
);
2643 if (ret
.Failed()) return ret
;
2645 if (st
!= NULL
&& st
->airport
.tile
!= INVALID_TILE
) {
2646 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT
);
2649 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2650 cost
.AddCost(_price
[PR_BUILD_STATION_AIRPORT
]);
2653 if (flags
& DC_EXEC
) {
2654 /* Always add the noise, so there will be no need to recalculate when option toggles */
2655 nearest
->noise_reached
+= newnoise_level
;
2657 st
->AddFacility(FACIL_AIRPORT
, tile
);
2658 st
->airport
.type
= airport_type
;
2659 st
->airport
.layout
= layout
;
2660 st
->airport
.flags
= 0;
2661 st
->airport
.rotation
= rotation
;
2663 st
->rect
.BeforeAddRect(tile
, w
, h
, StationRect::ADD_TRY
);
2665 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2666 MakeAirport(iter
, st
->owner
, st
->index
, iter
.GetStationGfx(), GetWaterClass(iter
));
2667 SetStationTileRandomBits(iter
, GB(Random(), 0, 4));
2668 st
->airport
.Add(iter
);
2669 st
->catchment
.BeforeAddTile(iter
, as
->catchment
);
2671 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter
.GetStationGfx()))->animation
.status
!= ANIM_STATUS_NO_ANIMATION
) AddAnimatedTile(iter
);
2674 /* Only call the animation trigger after all tiles have been built */
2675 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2676 AirportTileAnimationTrigger(st
, iter
, AAT_BUILT
);
2679 UpdateAirplanesOnNewStation(st
);
2681 Company::Get(st
->owner
)->infrastructure
.airport
++;
2682 DirtyCompanyInfrastructureWindows(st
->owner
);
2684 st
->UpdateVirtCoord();
2685 UpdateStationAcceptance(st
, false);
2686 st
->RecomputeIndustriesNear();
2687 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2688 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2689 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2691 if (_settings_game
.economy
.station_noise_level
) {
2692 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2701 * @param tile TileIndex been queried
2702 * @param flags operation to perform
2703 * @return cost or failure of operation
2705 static CommandCost
RemoveAirport(TileIndex tile
, DoCommandFlag flags
)
2707 Station
*st
= Station::GetByTile(tile
);
2709 if (_current_company
!= OWNER_WATER
) {
2710 CommandCost ret
= CheckOwnership(st
->owner
);
2711 if (ret
.Failed()) return ret
;
2714 CommandCost cost
= CanRemoveAirport(st
, flags
);
2715 if (cost
.Failed()) return cost
;
2717 if (flags
& DC_EXEC
) {
2718 const AirportSpec
*as
= st
->airport
.GetSpec();
2719 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2720 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2721 * need of recalculation */
2722 AirportTileIterator
it(st
);
2723 Town
*nearest
= AirportGetNearestTown(as
, it
);
2724 nearest
->noise_reached
-= GetAirportNoiseLevelForTown(as
, it
, nearest
->xy
);
2726 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2727 ZoningMarkDirtyStationCoverageArea(st
);
2728 const AirportSpec
*as
= st
->airport
.GetSpec();
2729 if (IsHangarTile(tile_cur
)) OrderBackup::Reset(tile_cur
, false);
2730 DeleteAnimatedTile(tile_cur
);
2731 st
->catchment
.AfterRemoveTile(tile_cur
, as
->catchment
);
2732 WaterClass wc
= GetWaterClass(tile_cur
);
2733 DoClearSquare(tile_cur
);
2735 if (wc
!= WATER_CLASS_INVALID
){
2736 SetTileType(tile_cur
, MP_WATER
);
2737 SetWaterClass(tile_cur
, wc
);
2738 if (wc
== WATER_CLASS_CANAL
) {
2739 SetTileOwner(tile_cur
, st
->owner
);
2743 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
);
2746 /* Clear the persistent storage. */
2747 delete st
->airport
.psa
;
2749 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2751 WC_VEHICLE_DEPOT
, st
->airport
.GetHangarTile(i
)
2755 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2757 st
->airport
.Clear();
2758 st
->facilities
&= ~FACIL_AIRPORT
;
2760 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2762 if (_settings_game
.economy
.station_noise_level
) {
2763 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2766 Company::Get(st
->owner
)->infrastructure
.airport
--;
2767 DirtyCompanyInfrastructureWindows(st
->owner
);
2769 st
->UpdateVirtCoord();
2770 st
->RecomputeIndustriesNear();
2771 DeleteStationIfEmpty(st
);
2772 DeleteNewGRFInspectWindow(GSF_AIRPORTS
, st
->index
);
2779 * Open/close an airport to incoming aircraft.
2780 * @param tile Unused.
2781 * @param flags Operation to perform.
2782 * @param p1 Station ID of the airport.
2784 * @param text unused
2785 * @return the cost of this operation or an error
2787 CommandCost
CmdOpenCloseAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2789 if (!Station::IsValidID(p1
)) return CMD_ERROR
;
2790 Station
*st
= Station::Get(p1
);
2792 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->owner
== OWNER_NONE
) return CMD_ERROR
;
2794 CommandCost ret
= CheckOwnership(st
->owner
);
2795 if (ret
.Failed()) return ret
;
2797 if (flags
& DC_EXEC
) {
2798 st
->airport
.flags
^= AIRPORT_CLOSED_block
;
2799 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_CLOSE_AIRPORT
);
2801 return CommandCost();
2805 * Tests whether the company's vehicles have this station in orders
2806 * @param station station ID
2807 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2808 * @param company company ID
2810 bool HasStationInUse(StationID station
, bool include_company
, CompanyID company
)
2813 FOR_ALL_VEHICLES(v
) {
2814 if ((v
->owner
== company
) == include_company
) {
2816 FOR_VEHICLE_ORDERS(v
, order
) {
2817 if ((order
->IsType(OT_GOTO_STATION
) || order
->IsType(OT_GOTO_WAYPOINT
)) && order
->GetDestination() == station
) {
2826 static const TileIndexDiffC _dock_tileoffs_chkaround
[] = {
2832 static const byte _dock_w_chk
[4] = { 2, 1, 2, 1 };
2833 static const byte _dock_h_chk
[4] = { 1, 2, 1, 2 };
2836 * Build a dock/haven.
2837 * @param tile tile where dock will be built
2838 * @param flags operation to perform
2839 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
2840 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
2841 * @param text unused
2842 * @return the cost of this operation or an error
2844 CommandCost
CmdBuildDock(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2846 StationID station_to_join
= GB(p2
, 16, 16);
2847 bool reuse
= (station_to_join
!= NEW_STATION
);
2848 if (!reuse
) station_to_join
= INVALID_STATION
;
2849 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2851 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2853 TileIndex slope_tile
= tile
;
2855 DiagDirection direction
= GetInclinedSlopeDirection(GetTileSlope(slope_tile
));
2856 if (direction
== INVALID_DIAGDIR
) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2857 direction
= ReverseDiagDir(direction
);
2859 TileIndex flat_tile
= slope_tile
+ TileOffsByDiagDir(direction
);
2861 /* Docks cannot be placed on rapids */
2862 if (HasTileWaterGround(slope_tile
)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2864 CommandCost ret
= CheckIfAuthorityAllowsNewStation(slope_tile
, flags
);
2865 if (ret
.Failed()) return ret
;
2867 if (IsBridgeAbove(slope_tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2869 ret
= DoCommand(slope_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2870 if (ret
.Failed()) return ret
;
2872 if (!IsTileType(flat_tile
, MP_WATER
) || !IsTileFlat(flat_tile
)) {
2873 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2876 if (IsBridgeAbove(flat_tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2878 /* Get the water class of the water tile before it is cleared.*/
2879 WaterClass wc
= GetWaterClass(flat_tile
);
2881 ret
= DoCommand(flat_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2882 if (ret
.Failed()) return ret
;
2884 TileIndex adjacent_tile
= flat_tile
+ TileOffsByDiagDir(direction
);
2885 if (!IsTileType(adjacent_tile
, MP_WATER
) || !IsTileFlat(adjacent_tile
)) {
2886 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2889 TileArea dock_area
= TileArea(slope_tile
+ ToTileIndexDiff(_dock_tileoffs_chkaround
[direction
]),
2890 _dock_w_chk
[direction
], _dock_h_chk
[direction
]);
2894 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, HasBit(p1
, 0), dock_area
, &st
);
2895 if (ret
.Failed()) return ret
;
2898 if (st
== NULL
&& distant_join
) st
= Station::GetIfValid(station_to_join
);
2900 if (!Dock::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_DOCKS
);
2902 ret
= BuildStationPart(&st
, flags
, reuse
, dock_area
, STATIONNAMING_DOCK
);
2903 if (ret
.Failed()) return ret
;
2905 if (flags
& DC_EXEC
) {
2906 /* Create the dock and insert it into the list of docks. */
2907 Dock
*dock
= new Dock(slope_tile
, flat_tile
);
2908 dock
->next
= st
->docks
;
2911 st
->dock_station
.Add(slope_tile
);
2912 st
->dock_station
.Add(flat_tile
);
2913 st
->AddFacility(FACIL_DOCK
, slope_tile
);
2915 st
->rect
.BeforeAddRect(dock_area
.tile
, dock_area
.w
, dock_area
.h
, StationRect::ADD_TRY
);
2916 st
->catchment
.BeforeAddRect(dock_area
.tile
, dock_area
.w
, dock_area
.h
, CA_DOCK
);
2918 /* If the water part of the dock is on a canal, update infrastructure counts.
2919 * This is needed as we've unconditionally cleared that tile before. */
2920 if (wc
== WATER_CLASS_CANAL
) {
2921 Company::Get(st
->owner
)->infrastructure
.water
++;
2923 Company::Get(st
->owner
)->infrastructure
.station
+= 2;
2924 DirtyCompanyInfrastructureWindows(st
->owner
);
2926 MakeDock(slope_tile
, st
->owner
, st
->index
, direction
, wc
);
2928 st
->UpdateVirtCoord();
2929 UpdateStationAcceptance(st
, false);
2930 st
->RecomputeIndustriesNear();
2931 ZoningMarkDirtyStationCoverageArea(st
);
2932 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2933 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2934 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_SHIPS
);
2937 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_STATION_DOCK
]);
2942 * @param tile TileIndex been queried
2943 * @param flags operation to perform
2944 * @return cost or failure of operation
2946 static CommandCost
RemoveDock(TileIndex tile
, DoCommandFlag flags
)
2948 Station
*st
= Station::GetByTile(tile
);
2949 CommandCost ret
= CheckOwnership(st
->owner
);
2950 if (ret
.Failed()) return ret
;
2952 Dock
*removing_dock
= Dock::GetByTile(tile
);
2953 assert(removing_dock
!= NULL
);
2955 TileIndex tile1
= removing_dock
->sloped
;
2956 TileIndex tile2
= removing_dock
->flat
;
2958 DiagDirection direction
= DiagdirBetweenTiles(removing_dock
->sloped
, removing_dock
->flat
);
2959 TileIndex docking_location
= removing_dock
->flat
+ TileOffsByDiagDir(direction
);
2961 ret
= EnsureNoVehicleOnGround(tile1
);
2962 if (ret
.Succeeded()) ret
= EnsureNoVehicleOnGround(tile2
);
2963 if (ret
.Failed()) return ret
;
2965 if (flags
& DC_EXEC
) {
2966 st
->catchment
.AfterRemoveTile(tile1
, CA_DOCK
);
2967 st
->catchment
.AfterRemoveTile(tile2
, CA_DOCK
);
2968 ZoningMarkDirtyStationCoverageArea(st
);
2970 if (st
->docks
== removing_dock
) {
2971 /* The first dock in the list is removed. */
2972 st
->docks
= removing_dock
->next
;
2973 /* Last dock is removed. */
2974 if (st
->docks
== NULL
) {
2975 st
->facilities
&= ~FACIL_DOCK
;
2978 /* Tell the predecessor in the list to skip this dock. */
2979 Dock
*pred
= st
->docks
;
2980 while (pred
->next
!= removing_dock
) pred
= pred
->next
;
2981 pred
->next
= removing_dock
->next
;
2984 delete removing_dock
;
2986 DoClearSquare(tile1
);
2987 MarkTileDirtyByTile(tile1
);
2988 MakeWaterKeepingClass(tile2
, st
->owner
);
2990 if (Overlays::Instance()->HasStation(st
)) st
->MarkAcceptanceTilesDirty();
2991 st
->rect
.AfterRemoveTile(st
, tile1
);
2992 st
->rect
.AfterRemoveTile(st
, tile2
);
2994 st
->dock_station
.Clear();
2995 for (Dock
*dock
= st
->docks
; dock
!= NULL
; dock
= dock
->next
) {
2996 st
->dock_station
.Add(dock
->flat
);
2997 st
->dock_station
.Add(dock
->sloped
);
3000 Company::Get(st
->owner
)->infrastructure
.station
-= 2;
3001 DirtyCompanyInfrastructureWindows(st
->owner
);
3003 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_SHIPS
);
3004 st
->UpdateVirtCoord();
3005 st
->RecomputeIndustriesNear();
3006 DeleteStationIfEmpty(st
);
3008 /* All ships that were going to our station, can't go to it anymore.
3009 * Just clear the order, then automatically the next appropriate order
3010 * will be selected and in case of no appropriate order it will just
3011 * wander around the world. */
3014 if (s
->current_order
.IsType(OT_LOADING
) && s
->tile
== docking_location
) {
3018 if (s
->dest_tile
== docking_location
) {
3020 s
->current_order
.Free();
3025 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_STATION_DOCK
]);
3028 #include "table/station_land.h"
3030 const DrawTileSprites
*GetStationTileLayout(StationType st
, byte gfx
)
3032 return &_station_display_datas
[st
][gfx
];
3036 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
3037 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
3038 * is set to the overlay to draw.
3039 * @param ti Positional info for the tile to decide snowyness etc. May be NULL.
3040 * @param [in,out] ground Groundsprite to draw.
3041 * @param [out] overlay_offset Overlay to draw.
3042 * @return true if overlay can be drawn.
3044 bool SplitGroundSpriteForOverlay(const TileInfo
*ti
, SpriteID
*ground
, RailTrackOffset
*overlay_offset
)
3048 case SPR_RAIL_TRACK_X
:
3049 snow_desert
= false;
3050 *overlay_offset
= RTO_X
;
3053 case SPR_RAIL_TRACK_Y
:
3054 snow_desert
= false;
3055 *overlay_offset
= RTO_Y
;
3058 case SPR_RAIL_TRACK_X_SNOW
:
3060 *overlay_offset
= RTO_X
;
3063 case SPR_RAIL_TRACK_Y_SNOW
:
3065 *overlay_offset
= RTO_Y
;
3073 /* Decide snow/desert from tile */
3074 switch (_settings_game
.game_creation
.landscape
) {
3076 snow_desert
= (uint
)ti
->z
> GetSnowLine() * TILE_HEIGHT
;
3080 snow_desert
= GetTropicZone(ti
->tile
) == TROPICZONE_DESERT
;
3088 *ground
= snow_desert
? SPR_FLAT_SNOW_DESERT_TILE
: SPR_FLAT_GRASS_TILE
;
3092 static void DrawTile_Station(TileInfo
*ti
)
3094 const NewGRFSpriteLayout
*layout
= NULL
;
3095 DrawTileSprites tmp_rail_layout
;
3096 const DrawTileSprites
*t
= NULL
;
3097 RoadTypes roadtypes
;
3099 const RailtypeInfo
*rti
= NULL
;
3100 uint32 relocation
= 0;
3101 uint32 ground_relocation
= 0;
3102 BaseStation
*st
= NULL
;
3103 const StationSpec
*statspec
= NULL
;
3104 uint tile_layout
= 0;
3106 if (HasStationRail(ti
->tile
)) {
3107 rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
3108 roadtypes
= ROADTYPES_NONE
;
3109 total_offset
= rti
->GetRailtypeSpriteOffset();
3111 if (IsCustomStationSpecIndex(ti
->tile
)) {
3112 /* look for customization */
3113 st
= BaseStation::GetByTile(ti
->tile
);
3114 statspec
= st
->speclist
[GetCustomStationSpecIndex(ti
->tile
)].spec
;
3116 if (statspec
!= NULL
) {
3117 tile_layout
= GetStationGfx(ti
->tile
);
3119 if (HasBit(statspec
->callback_mask
, CBM_STATION_SPRITE_LAYOUT
)) {
3120 uint16 callback
= GetStationCallback(CBID_STATION_SPRITE_LAYOUT
, 0, 0, statspec
, st
, ti
->tile
);
3121 if (callback
!= CALLBACK_FAILED
) tile_layout
= (callback
& ~1) + GetRailStationAxis(ti
->tile
);
3124 /* Ensure the chosen tile layout is valid for this custom station */
3125 if (statspec
->renderdata
!= NULL
) {
3126 layout
= &statspec
->renderdata
[tile_layout
< statspec
->tiles
? tile_layout
: (uint
)GetRailStationAxis(ti
->tile
)];
3127 if (!layout
->NeedsPreprocessing()) {
3135 roadtypes
= IsRoadStop(ti
->tile
) ? GetRoadTypes(ti
->tile
) : ROADTYPES_NONE
;
3139 StationGfx gfx
= GetStationGfx(ti
->tile
);
3140 if (IsAirport(ti
->tile
)) {
3141 gfx
= GetAirportGfx(ti
->tile
);
3142 if (gfx
>= NEW_AIRPORTTILE_OFFSET
) {
3143 const AirportTileSpec
*ats
= AirportTileSpec::Get(gfx
);
3144 if (ats
->grf_prop
.spritegroup
[0] != NULL
&& DrawNewAirportTile(ti
, Station::GetByTile(ti
->tile
), gfx
, ats
)) {
3147 /* No sprite group (or no valid one) found, meaning no graphics associated.
3148 * Use the substitute one instead */
3149 assert(ats
->grf_prop
.subst_id
!= INVALID_AIRPORTTILE
);
3150 gfx
= ats
->grf_prop
.subst_id
;
3153 case APT_RADAR_GRASS_FENCE_SW
:
3154 t
= &_station_display_datas_airport_radar_grass_fence_sw
[GetAnimationFrame(ti
->tile
)];
3156 case APT_GRASS_FENCE_NE_FLAG
:
3157 t
= &_station_display_datas_airport_flag_grass_fence_ne
[GetAnimationFrame(ti
->tile
)];
3159 case APT_RADAR_FENCE_SW
:
3160 t
= &_station_display_datas_airport_radar_fence_sw
[GetAnimationFrame(ti
->tile
)];
3162 case APT_RADAR_FENCE_NE
:
3163 t
= &_station_display_datas_airport_radar_fence_ne
[GetAnimationFrame(ti
->tile
)];
3165 case APT_GRASS_FENCE_NE_FLAG_2
:
3166 t
= &_station_display_datas_airport_flag_grass_fence_ne_2
[GetAnimationFrame(ti
->tile
)];
3171 Owner owner
= GetTileOwner(ti
->tile
);
3174 if (Company::IsValidID(owner
)) {
3175 palette
= COMPANY_SPRITE_COLOUR(owner
);
3177 /* Some stations are not owner by a company, namely oil rigs */
3178 palette
= PALETTE_TO_GREY
;
3181 if (layout
== NULL
&& (t
== NULL
|| t
->seq
== NULL
)) t
= GetStationTileLayout(GetStationType(ti
->tile
), gfx
);
3183 /* don't show foundation for docks */
3184 if (ti
->tileh
!= SLOPE_FLAT
&& !IsDock(ti
->tile
)) {
3185 if (statspec
!= NULL
&& HasBit(statspec
->flags
, SSF_CUSTOM_FOUNDATIONS
)) {
3186 /* Station has custom foundations.
3187 * Check whether the foundation continues beyond the tile's upper sides. */
3190 Slope slope
= GetFoundationPixelSlope(ti
->tile
, &z
);
3191 if (!HasFoundationNW(ti
->tile
, slope
, z
)) SetBit(edge_info
, 0);
3192 if (!HasFoundationNE(ti
->tile
, slope
, z
)) SetBit(edge_info
, 1);
3193 SpriteID image
= GetCustomStationFoundationRelocation(statspec
, st
, ti
->tile
, tile_layout
, edge_info
);
3194 if (image
== 0) goto draw_default_foundation
;
3196 if (HasBit(statspec
->flags
, SSF_EXTENDED_FOUNDATIONS
)) {
3197 /* Station provides extended foundations. */
3199 static const uint8 foundation_parts
[] = {
3200 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3201 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3202 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3203 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3206 AddSortableSpriteToDraw(image
+ foundation_parts
[ti
->tileh
], PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
3208 /* Draw simple foundations, built up from 8 possible foundation sprites. */
3210 /* Each set bit represents one of the eight composite sprites to be drawn.
3211 * 'Invalid' entries will not drawn but are included for completeness. */
3212 static const uint8 composite_foundation_parts
[] = {
3213 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
3214 0x00, 0xD1, 0xE4, 0xE0,
3215 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
3216 0xCA, 0xC9, 0xC4, 0xC0,
3217 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
3218 0xD2, 0x91, 0xE4, 0xA0,
3219 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
3223 uint8 parts
= composite_foundation_parts
[ti
->tileh
];
3225 /* If foundations continue beyond the tile's upper sides then
3226 * mask out the last two pieces. */
3227 if (HasBit(edge_info
, 0)) ClrBit(parts
, 6);
3228 if (HasBit(edge_info
, 1)) ClrBit(parts
, 7);
3231 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
3232 * correct offset for the childsprites.
3233 * So, draw the (completely empty) sprite of the default foundations. */
3234 goto draw_default_foundation
;
3237 StartSpriteCombine();
3238 for (int i
= 0; i
< 8; i
++) {
3239 if (HasBit(parts
, i
)) {
3240 AddSortableSpriteToDraw(image
+ i
, PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
3246 OffsetGroundSprite(31, 1);
3247 ti
->z
+= ApplyPixelFoundationToSlope(FOUNDATION_LEVELED
, &ti
->tileh
);
3249 draw_default_foundation
:
3250 DrawFoundation(ti
, FOUNDATION_LEVELED
);
3254 if (IsBuoy(ti
->tile
)) {
3255 DrawWaterClassGround(ti
);
3256 SpriteID sprite
= GetCanalSprite(CF_BUOY
, ti
->tile
);
3257 if (sprite
!= 0) total_offset
= sprite
- SPR_IMG_BUOY
;
3258 } else if (IsDock(ti
->tile
) || (IsOilRig(ti
->tile
) && IsTileOnWater(ti
->tile
))) {
3259 if (ti
->tileh
== SLOPE_FLAT
) {
3260 DrawWaterClassGround(ti
);
3262 assert(IsDock(ti
->tile
));
3263 TileIndex water_tile
= ti
->tile
+ TileOffsByDiagDir(GetDockDirection(ti
->tile
));
3264 WaterClass wc
= GetWaterClass(water_tile
);
3265 if (wc
== WATER_CLASS_SEA
) {
3266 DrawShoreTile(ti
->tileh
);
3268 DrawClearLandTile(ti
, 3);
3272 if (layout
!= NULL
) {
3273 /* Sprite layout which needs preprocessing */
3274 bool separate_ground
= HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
);
3275 uint32 var10_values
= layout
->PrepareLayout(total_offset
, rti
->fallback_railtype
, 0, 0, separate_ground
);
3277 FOR_EACH_SET_BIT(var10
, var10_values
) {
3278 uint32 var10_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, var10
);
3279 layout
->ProcessRegisters(var10
, var10_relocation
, separate_ground
);
3281 tmp_rail_layout
.seq
= layout
->GetLayout(&tmp_rail_layout
.ground
);
3282 t
= &tmp_rail_layout
;
3284 } else if (statspec
!= NULL
) {
3285 /* Simple sprite layout */
3286 ground_relocation
= relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 0);
3287 if (HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
)) {
3288 ground_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 1);
3290 ground_relocation
+= rti
->fallback_railtype
;
3293 SpriteID image
= t
->ground
.sprite
;
3294 PaletteID pal
= t
->ground
.pal
;
3295 RailTrackOffset overlay_offset
;
3296 if (rti
!= NULL
&& rti
->UsesOverlay() && SplitGroundSpriteForOverlay(ti
, &image
, &overlay_offset
)) {
3297 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
);
3298 DrawGroundSprite(image
, PAL_NONE
);
3299 DrawGroundSprite(ground
+ overlay_offset
, PAL_NONE
);
3301 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationReservation(ti
->tile
)) {
3302 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
3303 DrawGroundSprite(overlay
+ overlay_offset
, PALETTE_CRASH
);
3306 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
3307 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
3308 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
));
3310 /* PBS debugging, draw reserved tracks darker */
3311 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationRail(ti
->tile
) && HasStationReservation(ti
->tile
)) {
3312 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
3313 DrawGroundSprite(GetRailStationAxis(ti
->tile
) == AXIS_X
? rti
->base_sprites
.single_x
: rti
->base_sprites
.single_y
, PALETTE_CRASH
);
3318 DrawOverlay(ti
, MP_STATION
);
3320 if (HasStationRail(ti
->tile
) && HasRailCatenaryDrawn(GetRailType(ti
->tile
))) DrawRailCatenary(ti
);
3323 if (HasBit(roadtypes
, ROADTYPE_TRAM
)) {
3324 Axis axis
= GetRoadStopDir(ti
->tile
) == DIAGDIR_NE
? AXIS_X
: AXIS_Y
;
3325 DrawGroundSprite((HasBit(roadtypes
, ROADTYPE_ROAD
) ? SPR_TRAMWAY_OVERLAY
: SPR_TRAMWAY_TRAM
) + (axis
^ 1), PAL_NONE
);
3326 DrawRoadCatenary(ti
, axis
== AXIS_X
? ROAD_X
: ROAD_Y
);
3329 if (IsRailWaypoint(ti
->tile
)) {
3330 /* Don't offset the waypoint graphics; they're always the same. */
3334 DrawRailTileSeq(ti
, t
, TO_BUILDINGS
, total_offset
, relocation
, palette
);
3337 void StationPickerDrawSprite(int x
, int y
, StationType st
, RailType railtype
, RoadType roadtype
, int image
)
3339 int32 total_offset
= 0;
3340 PaletteID pal
= COMPANY_SPRITE_COLOUR(_local_company
);
3341 const DrawTileSprites
*t
= GetStationTileLayout(st
, image
);
3342 const RailtypeInfo
*rti
= NULL
;
3344 if (railtype
!= INVALID_RAILTYPE
) {
3345 rti
= GetRailTypeInfo(railtype
);
3346 total_offset
= rti
->GetRailtypeSpriteOffset();
3349 SpriteID img
= t
->ground
.sprite
;
3350 RailTrackOffset overlay_offset
;
3351 if (rti
!= NULL
&& rti
->UsesOverlay() && SplitGroundSpriteForOverlay(NULL
, &img
, &overlay_offset
)) {
3352 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
3353 DrawSprite(img
, PAL_NONE
, x
, y
);
3354 DrawSprite(ground
+ overlay_offset
, PAL_NONE
, x
, y
);
3356 DrawSprite(img
+ total_offset
, HasBit(img
, PALETTE_MODIFIER_COLOUR
) ? pal
: PAL_NONE
, x
, y
);
3359 if (roadtype
== ROADTYPE_TRAM
) {
3360 DrawSprite(SPR_TRAMWAY_TRAM
+ (t
->ground
.sprite
== SPR_ROAD_PAVED_STRAIGHT_X
? 1 : 0), PAL_NONE
, x
, y
);
3363 /* Default waypoint has no railtype specific sprites */
3364 DrawRailTileSeqInGUI(x
, y
, t
, st
== STATION_WAYPOINT
? 0 : total_offset
, 0, pal
);
3367 static int GetSlopePixelZ_Station(TileIndex tile
, uint x
, uint y
)
3369 return GetTileMaxPixelZ(tile
);
3372 static Foundation
GetFoundation_Station(TileIndex tile
, Slope tileh
)
3374 return FlatteningFoundation(tileh
);
3377 static void GetTileDesc_Station(TileIndex tile
, TileDesc
*td
)
3379 td
->owner
[0] = GetTileOwner(tile
);
3380 if (IsDriveThroughStopTile(tile
)) {
3381 Owner road_owner
= INVALID_OWNER
;
3382 Owner tram_owner
= INVALID_OWNER
;
3383 RoadTypes rts
= GetRoadTypes(tile
);
3384 if (HasBit(rts
, ROADTYPE_ROAD
)) road_owner
= GetRoadOwner(tile
, ROADTYPE_ROAD
);
3385 if (HasBit(rts
, ROADTYPE_TRAM
)) tram_owner
= GetRoadOwner(tile
, ROADTYPE_TRAM
);
3387 /* Is there a mix of owners? */
3388 if ((tram_owner
!= INVALID_OWNER
&& tram_owner
!= td
->owner
[0]) ||
3389 (road_owner
!= INVALID_OWNER
&& road_owner
!= td
->owner
[0])) {
3391 if (road_owner
!= INVALID_OWNER
) {
3392 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_ROAD_OWNER
;
3393 td
->owner
[i
] = road_owner
;
3396 if (tram_owner
!= INVALID_OWNER
) {
3397 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_TRAM_OWNER
;
3398 td
->owner
[i
] = tram_owner
;
3402 td
->build_date
= BaseStation::GetByTile(tile
)->build_date
;
3404 if (HasStationTileRail(tile
)) {
3405 const StationSpec
*spec
= GetStationSpec(tile
);
3408 td
->station_class
= StationClass::Get(spec
->cls_id
)->name
;
3409 td
->station_name
= spec
->name
;
3411 if (spec
->grf_prop
.grffile
!= NULL
) {
3412 const GRFConfig
*gc
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
);
3413 td
->grf
= gc
->GetName();
3417 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(tile
));
3418 td
->rail_speed
= rti
->max_speed
;
3419 td
->railtype
= rti
->strings
.name
;
3422 if (IsAirport(tile
)) {
3423 const AirportSpec
*as
= Station::GetByTile(tile
)->airport
.GetSpec();
3424 td
->airport_class
= AirportClass::Get(as
->cls_id
)->name
;
3425 td
->airport_name
= as
->name
;
3427 const AirportTileSpec
*ats
= AirportTileSpec::GetByTile(tile
);
3428 td
->airport_tile_name
= ats
->name
;
3430 if (as
->grf_prop
.grffile
!= NULL
) {
3431 const GRFConfig
*gc
= GetGRFConfig(as
->grf_prop
.grffile
->grfid
);
3432 td
->grf
= gc
->GetName();
3433 } else if (ats
->grf_prop
.grffile
!= NULL
) {
3434 const GRFConfig
*gc
= GetGRFConfig(ats
->grf_prop
.grffile
->grfid
);
3435 td
->grf
= gc
->GetName();
3440 switch (GetStationType(tile
)) {
3441 default: NOT_REACHED();
3442 case STATION_RAIL
: str
= STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION
; break;
3443 case STATION_AIRPORT
:
3444 str
= (IsHangar(tile
) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR
: STR_LAI_STATION_DESCRIPTION_AIRPORT
);
3446 case STATION_TRUCK
: str
= STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA
; break;
3447 case STATION_BUS
: str
= STR_LAI_STATION_DESCRIPTION_BUS_STATION
; break;
3448 case STATION_OILRIG
: str
= STR_INDUSTRY_NAME_OIL_RIG
; break;
3449 case STATION_DOCK
: str
= STR_LAI_STATION_DESCRIPTION_SHIP_DOCK
; break;
3450 case STATION_BUOY
: str
= STR_LAI_STATION_DESCRIPTION_BUOY
; break;
3451 case STATION_WAYPOINT
: str
= STR_LAI_STATION_DESCRIPTION_WAYPOINT
; break;
3457 static TrackStatus
GetTileTrackStatus_Station(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
3459 TrackBits trackbits
= TRACK_BIT_NONE
;
3462 case TRANSPORT_RAIL
:
3463 if (HasStationRail(tile
) && !IsStationTileBlocked(tile
)) {
3464 trackbits
= TrackToTrackBits(GetRailStationTrack(tile
));
3468 case TRANSPORT_WATER
:
3469 /* buoy is coded as a station, it is always on open water */
3471 trackbits
= TRACK_BIT_ALL
;
3472 /* remove tracks that connect NE map edge */
3473 if (TileX(tile
) == 0) trackbits
&= ~(TRACK_BIT_X
| TRACK_BIT_UPPER
| TRACK_BIT_RIGHT
);
3474 /* remove tracks that connect NW map edge */
3475 if (TileY(tile
) == 0) trackbits
&= ~(TRACK_BIT_Y
| TRACK_BIT_LEFT
| TRACK_BIT_UPPER
);
3479 case TRANSPORT_ROAD
:
3480 if ((GetRoadTypes(tile
) & sub_mode
) != 0 && IsRoadStop(tile
)) {
3481 DiagDirection dir
= GetRoadStopDir(tile
);
3482 Axis axis
= DiagDirToAxis(dir
);
3484 if (side
!= INVALID_DIAGDIR
) {
3485 if (axis
!= DiagDirToAxis(side
) || (IsStandardRoadStopTile(tile
) && dir
!= side
)) break;
3488 trackbits
= AxisToTrackBits(axis
);
3496 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits
), TRACKDIR_BIT_NONE
);
3500 static void TileLoop_Station(TileIndex tile
)
3502 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3503 * hardcoded.....not good */
3504 switch (GetStationType(tile
)) {
3505 case STATION_AIRPORT
:
3506 AirportTileAnimationTrigger(Station::GetByTile(tile
), tile
, AAT_TILELOOP
);
3510 if (!IsTileFlat(tile
)) break; // only handle water part
3513 case STATION_OILRIG
: //(station part)
3515 TileLoop_Water(tile
);
3523 static void AnimateTile_Station(TileIndex tile
)
3525 if (HasStationRail(tile
)) {
3526 AnimateStationTile(tile
);
3530 if (IsAirport(tile
)) {
3531 AnimateAirportTile(tile
);
3536 static bool ClickTile_Station(TileIndex tile
)
3538 const BaseStation
*bst
= BaseStation::GetByTile(tile
);
3540 if (bst
->facilities
& FACIL_WAYPOINT
) {
3541 ShowWaypointWindow(Waypoint::From(bst
));
3542 } else if (IsHangar(tile
)) {
3543 const Station
*st
= Station::From(bst
);
3544 ShowDepotWindow(st
->airport
.GetHangarTile(st
->airport
.GetHangarNum(tile
)), VEH_AIRCRAFT
);
3546 ShowStationViewWindow(bst
->index
);
3551 static VehicleEnterTileStatus
VehicleEnter_Station(Vehicle
*v
, TileIndex tile
, int x
, int y
)
3553 if (v
->type
== VEH_TRAIN
) {
3554 StationID station_id
= GetStationIndex(tile
);
3555 if (v
->current_order
.IsType(OT_GOTO_WAYPOINT
) && v
->current_order
.GetDestination() == station_id
&& v
->current_order
.GetWaypointFlags() & OWF_REVERSE
) {
3556 Train
*t
= Train::From(v
);
3557 // reverse at waypoint
3558 if (t
->reverse_distance
== 0) t
->reverse_distance
= t
->gcache
.cached_total_length
;
3560 if (!v
->current_order
.ShouldStopAtStation(v
, station_id
)) return VETSB_CONTINUE
;
3561 if (!IsRailStation(tile
) || !v
->IsFrontEngine()) return VETSB_CONTINUE
;
3565 int stop
= GetTrainStopLocation(station_id
, tile
, Train::From(v
), &station_ahead
, &station_length
);
3567 /* Stop whenever that amount of station ahead + the distance from the
3568 * begin of the platform to the stop location is longer than the length
3569 * of the platform. Station ahead 'includes' the current tile where the
3570 * vehicle is on, so we need to subtract that. */
3571 if (stop
+ station_ahead
- (int)TILE_SIZE
>= station_length
) return VETSB_CONTINUE
;
3573 DiagDirection dir
= DirToDiagDir(v
->direction
);
3578 if (DiagDirToAxis(dir
) != AXIS_X
) Swap(x
, y
);
3579 if (y
== TILE_SIZE
/ 2) {
3580 if (dir
!= DIAGDIR_SE
&& dir
!= DIAGDIR_SW
) x
= TILE_SIZE
- 1 - x
;
3581 stop
&= TILE_SIZE
- 1;
3584 return VETSB_ENTERED_STATION
| (VehicleEnterTileStatus
)(station_id
<< VETS_STATION_ID_OFFSET
); // enter station
3585 } else if (x
< stop
) {
3586 v
->vehstatus
|= VS_TRAIN_SLOWING
;
3587 uint16 spd
= max(0, (stop
- x
) * 20 - 15);
3588 if (spd
< v
->cur_speed
) v
->cur_speed
= spd
;
3591 } else if (v
->type
== VEH_ROAD
) {
3592 RoadVehicle
*rv
= RoadVehicle::From(v
);
3593 if (rv
->state
< RVSB_IN_ROAD_STOP
&& !IsReversingRoadTrackdir((Trackdir
)rv
->state
) && rv
->frame
== 0) {
3594 if (IsRoadStop(tile
) && rv
->IsFrontEngine()) {
3595 /* Attempt to allocate a parking bay in a road stop */
3596 return RoadStop::GetByTile(tile
, GetRoadStopType(tile
))->Enter(rv
) ? VETSB_CONTINUE
: VETSB_CANNOT_ENTER
;
3601 return VETSB_CONTINUE
;
3605 * Run the watched cargo callback for all houses in the catchment area.
3606 * @param st Station.
3608 void TriggerWatchedCargoCallbacks(Station
*st
)
3610 /* Collect cargoes accepted since the last big tick. */
3612 for (CargoID cid
= 0; cid
< NUM_CARGO
; cid
++) {
3613 if (HasBit(st
->goods
[cid
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
)) SetBit(cargoes
, cid
);
3616 /* Anything to do? */
3617 if (cargoes
== 0) return;
3619 /* Loop over all houses in the catchment. */
3620 Rect r
= st
->GetCatchmentRect();
3621 TileArea
ta(TileXY(r
.left
, r
.top
), TileXY(r
.right
, r
.bottom
));
3622 TILE_AREA_LOOP(tile
, ta
) {
3623 if (IsTileType(tile
, MP_HOUSE
)) {
3624 WatchedCargoCallback(tile
, cargoes
);
3630 * This function is called for each station once every 250 ticks.
3631 * Not all stations will get the tick at the same time.
3632 * @param st the station receiving the tick.
3633 * @return true if the station is still valid (wasn't deleted)
3635 static bool StationHandleBigTick(BaseStation
*st
)
3637 if (!st
->IsInUse()) {
3638 if (++st
->delete_ctr
>= 8) delete st
;
3642 if (Station::IsExpected(st
)) {
3643 TriggerWatchedCargoCallbacks(Station::From(st
));
3645 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3646 ClrBit(Station::From(st
)->goods
[i
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
);
3651 if ((st
->facilities
& FACIL_WAYPOINT
) == 0) UpdateStationAcceptance(Station::From(st
), true);
3656 static inline void byte_inc_sat(byte
*p
)
3663 * Truncate the cargo by a specific amount.
3664 * @param cs The type of cargo to perform the truncation for.
3665 * @param ge The goods entry, of the station, to truncate.
3666 * @param amount The amount to truncate the cargo by.
3668 static void TruncateCargo(const CargoSpec
*cs
, GoodsEntry
*ge
, uint amount
= UINT_MAX
)
3670 /* If truncating also punish the source stations' ratings to
3671 * decrease the flow of incoming cargo. */
3673 StationCargoAmountMap waiting_per_source
;
3674 ge
->cargo
.Truncate(amount
, &waiting_per_source
);
3675 for (StationCargoAmountMap::iterator
i(waiting_per_source
.begin()); i
!= waiting_per_source
.end(); ++i
) {
3676 Station
*source_station
= Station::GetIfValid(i
->first
);
3677 if (source_station
== NULL
) continue;
3679 GoodsEntry
&source_ge
= source_station
->goods
[cs
->Index()];
3680 uint source_avg_waiting
= source_ge
.cargo
.AvailableCount() / max(1u, (uint
)source_ge
.cargo
.Packets()->MapSize());
3682 if (i
->second
> source_avg_waiting
) {
3683 source_ge
.max_waiting_cargo
= i
->second
;
3684 source_ge
.punishment_triggered
= true;
3689 static void UpdateStationRating(Station
*st
)
3691 bool waiting_changed
= false;
3693 byte_inc_sat(&st
->time_since_load
);
3694 byte_inc_sat(&st
->time_since_unload
);
3696 const CargoSpec
*cs
;
3697 FOR_ALL_CARGOSPECS(cs
) {
3698 GoodsEntry
*ge
= &st
->goods
[cs
->Index()];
3699 /* Slowly increase the rating back to his original level in the case we
3700 * didn't deliver cargo yet to this station. This happens when a bribe
3701 * failed while you didn't moved that cargo yet to a station. */
3702 if (!ge
->HasRating() && ge
->rating
< INITIAL_STATION_RATING
) {
3706 /* Only change the rating if we are moving this cargo */
3707 if (ge
->HasRating()) {
3708 byte_inc_sat(&ge
->time_since_pickup
);
3709 if (ge
->time_since_pickup
== 255 && _settings_game
.order
.selectgoods
) {
3710 ClrBit(ge
->status
, GoodsEntry::GES_RATING
);
3712 TruncateCargo(cs
, ge
);
3713 waiting_changed
= true;
3719 uint waiting
= ge
->cargo
.AvailableCount();
3721 /* num_dests is at least 1 if there is any cargo as
3722 * INVALID_STATION is also a destination.
3724 uint num_dests
= max(1u, (uint
)ge
->cargo
.Packets()->MapSize());
3726 /* Average amount of cargo per next hop, but prefer solitary stations
3727 * with only one or two next hops. They are allowed to have more
3728 * cargo waiting per next hop.
3729 * With manual cargo distribution waiting_avg = waiting / 1 as then
3730 * INVALID_STATION is the only destination.
3732 uint waiting_avg
= waiting
/ num_dests
;
3734 if (HasBit(cs
->callback_mask
, CBM_CARGO_STATION_RATING_CALC
)) {
3735 /* Perform custom station rating. If it succeeds the speed, days in transit and
3736 * waiting cargo ratings must not be executed. */
3738 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3739 uint last_speed
= ge
->HasVehicleEverTriedLoading() ? ge
->last_speed
: 0xFF;
3741 uint32 var18
= min(ge
->time_since_pickup
, 0xFF) | (min(ge
->max_waiting_cargo
, 0xFFFF) << 8) | (min(last_speed
, 0xFF) << 24);
3742 /* Convert to the 'old' vehicle types */
3743 uint32 var10
= (st
->last_vehicle_type
== VEH_INVALID
) ? 0x0 : (st
->last_vehicle_type
+ 0x10);
3744 uint16 callback
= GetCargoCallback(CBID_CARGO_STATION_RATING_CALC
, var10
, var18
, cs
);
3745 if (callback
!= CALLBACK_FAILED
) {
3747 rating
= GB(callback
, 0, 14);
3749 /* Simulate a 15 bit signed value */
3750 if (HasBit(callback
, 14)) rating
-= 0x4000;
3755 int b
= ge
->last_speed
- 15;
3756 if (b
>= 0) rating
+= b
>> 2;
3758 (rating
-= 90, ge
->max_waiting_cargo
> 2000) ||
3759 (rating
+= 52, ge
->max_waiting_cargo
> 1000) ||
3760 (rating
+= 52, ge
->max_waiting_cargo
> 500) ||
3761 (rating
+= 52, ge
->max_waiting_cargo
> 250) ||
3762 (rating
+= 52, ge
->max_waiting_cargo
> 125) ||
3763 (rating
+= 52, true);
3766 if (Company::IsValidID(st
->owner
) && HasBit(st
->town
->statues
, st
->owner
)) rating
+= 26;
3768 byte age
= ge
->last_age
;
3770 (rating
+= 10, age
>= 20) ||
3771 (rating
+= 10, age
>= 10) ||
3772 (rating
+= 13, true);
3775 int or_
= ge
->rating
; // old rating
3777 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3778 ge
->rating
= rating
= or_
+ Clamp(Clamp(rating
, 0, 255) - or_
, -2, 2);
3780 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3781 * remove some random amount of goods from the station */
3782 if (rating
<= 64 && waiting_avg
>= 100) {
3783 int dec
= Random() & 0x1F;
3784 if (waiting_avg
< 200) dec
&= 7;
3785 waiting
-= (dec
+ 1) * num_dests
;
3786 waiting_changed
= true;
3789 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3790 if (rating
<= 127 && waiting
!= 0) {
3791 uint32 r
= Random();
3792 if (rating
<= (int)GB(r
, 0, 7)) {
3793 /* Need to have int, otherwise it will just overflow etc. */
3794 waiting
= max((int)waiting
- (int)((GB(r
, 8, 2) - 1) * num_dests
), 0);
3795 waiting_changed
= true;
3799 /* At some point we really must cap the cargo. Previously this
3800 * was a strict 4095, but now we'll have a less strict, but
3801 * increasingly aggressive truncation of the amount of cargo. */
3802 static const uint WAITING_CARGO_THRESHOLD
= 1 << 12;
3803 static const uint WAITING_CARGO_CUT_FACTOR
= 1 << 6;
3804 static const uint MAX_WAITING_CARGO
= 1 << 15;
3806 if (waiting
> WAITING_CARGO_THRESHOLD
) {
3807 uint difference
= waiting
- WAITING_CARGO_THRESHOLD
;
3808 waiting
-= (difference
/ WAITING_CARGO_CUT_FACTOR
);
3810 waiting
= min(waiting
, MAX_WAITING_CARGO
);
3811 waiting_changed
= true;
3814 /* We can't truncate cargo that's already reserved for loading.
3815 * Thus StoredCount() here. */
3816 if (waiting_changed
&& waiting
< ge
->cargo
.AvailableCount()) {
3817 /* Feed back the exact own waiting cargo at this station for the
3818 * next rating calculation. */
3819 TruncateCargo(cs
, ge
, ge
->cargo
.AvailableCount() - waiting
);
3822 if (ge
->punishment_triggered
) {
3823 // We were punished by another station. Delay the update of waiting cargo until next rating.
3824 ge
->punishment_in_effect
= true;
3825 ge
->punishment_triggered
= false;
3829 ge
->punishment_in_effect
= false;
3830 ge
->max_waiting_cargo
= waiting_avg
;
3836 StationID index
= st
->index
;
3837 if (waiting_changed
) {
3838 SetWindowDirty(WC_STATION_VIEW
, index
); // update whole window
3840 SetWindowWidgetDirty(WC_STATION_VIEW
, index
, WID_SV_ACCEPT_RATING_LIST
); // update only ratings list
3845 * Reroute cargo of type c at station st or in any vehicles unloading there.
3846 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3847 * @param st Station to be rerouted at.
3848 * @param c Type of cargo.
3849 * @param avoid Original next hop of cargo, avoid this.
3850 * @param avoid2 Another station to be avoided when rerouting.
3852 void RerouteCargo(Station
*st
, CargoID c
, StationID avoid
, StationID avoid2
)
3854 GoodsEntry
&ge
= st
->goods
[c
];
3856 /* Reroute cargo in station. */
3857 ge
.cargo
.Reroute(UINT_MAX
, &ge
.cargo
, avoid
, avoid2
, &ge
);
3859 /* Reroute cargo staged to be transfered. */
3860 for (Vehicle
*v
: st
->loading_vehicles
) {
3861 for (; v
!= NULL
; v
= v
->Next()) {
3862 if (v
->cargo_type
!= c
) continue;
3863 v
->cargo
.Reroute(UINT_MAX
, &v
->cargo
, avoid
, avoid2
, &ge
);
3869 * Check all next hops of cargo packets in this station for existance of a
3870 * a valid link they may use to travel on. Reroute any cargo not having a valid
3871 * link and remove timed out links found like this from the linkgraph. We're
3872 * not all links here as that is expensive and useless. A link no one is using
3873 * doesn't hurt either.
3874 * @param from Station to check.
3876 void DeleteStaleLinks(Station
*from
)
3878 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
3879 const bool auto_distributed
= (_settings_game
.linkgraph
.GetDistributionType(c
) != DT_MANUAL
);
3880 GoodsEntry
&ge
= from
->goods
[c
];
3881 LinkGraph
*lg
= LinkGraph::GetIfValid(ge
.link_graph
);
3882 if (lg
== NULL
) continue;
3883 Node node
= (*lg
)[ge
.node
];
3884 for (EdgeIterator
it(node
.Begin()); it
!= node
.End();) {
3885 Edge edge
= it
->second
;
3886 Station
*to
= Station::Get((*lg
)[it
->first
].Station());
3887 assert(to
->goods
[c
].node
== it
->first
);
3888 ++it
; // Do that before removing the edge. Anything else may crash.
3889 assert(_date
>= edge
.LastUpdate());
3890 uint timeout
= max
<uint
>((LinkGraph::MIN_TIMEOUT_DISTANCE
+ (DistanceManhattan(from
->xy
, to
->xy
) >> 3)) / _settings_game
.economy
.daylength
, 1);
3891 if ((uint
)(_date
- edge
.LastUpdate()) > timeout
) {
3892 bool updated
= false;
3894 if (auto_distributed
) {
3895 /* Have all vehicles refresh their next hops before deciding to
3896 * remove the node. */
3898 SmallVector
<Vehicle
*, 32> vehicles
;
3899 FOR_ALL_ORDER_LISTS(l
) {
3900 bool found_from
= false;
3901 bool found_to
= false;
3902 for (Order
*order
= l
->GetFirstOrder(); order
!= NULL
; order
= order
->next
) {
3903 if (!order
->IsType(OT_GOTO_STATION
) && !order
->IsType(OT_IMPLICIT
)) continue;
3904 if (order
->GetDestination() == from
->index
) {
3906 if (found_to
) break;
3907 } else if (order
->GetDestination() == to
->index
) {
3909 if (found_from
) break;
3912 if (!found_to
|| !found_from
) continue;
3913 *(vehicles
.Append()) = l
->GetFirstSharedVehicle();
3916 Vehicle
**iter
= vehicles
.Begin();
3917 while (iter
!= vehicles
.End()) {
3920 LinkRefresher::Run(v
, false); // Don't allow merging. Otherwise lg might get deleted.
3921 if (edge
.LastUpdate() == _date
) {
3926 Vehicle
*next_shared
= v
->NextShared();
3928 *iter
= next_shared
;
3931 vehicles
.Erase(iter
);
3934 if (iter
== vehicles
.End()) iter
= vehicles
.Begin();
3939 /* If it's still considered dead remove it. */
3940 node
.RemoveEdge(to
->goods
[c
].node
);
3941 ge
.flows
.DeleteFlows(to
->index
);
3942 RerouteCargo(from
, c
, to
->index
, from
->index
);
3944 } else if (edge
.LastUnrestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastUnrestrictedUpdate()) > timeout
) {
3946 ge
.flows
.RestrictFlows(to
->index
);
3947 RerouteCargo(from
, c
, to
->index
, from
->index
);
3948 } else if (edge
.LastRestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastRestrictedUpdate()) > timeout
) {
3952 assert(_date
>= lg
->LastCompression());
3953 if ((uint
)(_date
- lg
->LastCompression()) > max
<uint
>(LinkGraph::COMPRESSION_INTERVAL
/ _settings_game
.economy
.daylength
, 1)) {
3960 * Increase capacity for a link stat given by station cargo and next hop.
3961 * @param st Station to get the link stats from.
3962 * @param cargo Cargo to increase stat for.
3963 * @param next_station_id Station the consist will be travelling to next.
3964 * @param capacity Capacity to add to link stat.
3965 * @param usage Usage to add to link stat.
3966 * @param mode Update mode to be applied.
3968 void IncreaseStats(Station
*st
, CargoID cargo
, StationID next_station_id
, uint capacity
, uint usage
, EdgeUpdateMode mode
)
3970 GoodsEntry
&ge1
= st
->goods
[cargo
];
3971 Station
*st2
= Station::Get(next_station_id
);
3972 GoodsEntry
&ge2
= st2
->goods
[cargo
];
3973 LinkGraph
*lg
= NULL
;
3974 if (ge1
.link_graph
== INVALID_LINK_GRAPH
) {
3975 if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3976 if (LinkGraph::CanAllocateItem()) {
3977 lg
= new LinkGraph(cargo
);
3978 LinkGraphSchedule::instance
.Queue(lg
);
3979 ge2
.link_graph
= lg
->index
;
3980 ge2
.node
= lg
->AddNode(st2
);
3982 DEBUG(misc
, 0, "Can't allocate link graph");
3985 lg
= LinkGraph::Get(ge2
.link_graph
);
3988 ge1
.link_graph
= lg
->index
;
3989 ge1
.node
= lg
->AddNode(st
);
3991 } else if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3992 lg
= LinkGraph::Get(ge1
.link_graph
);
3993 ge2
.link_graph
= lg
->index
;
3994 ge2
.node
= lg
->AddNode(st2
);
3996 lg
= LinkGraph::Get(ge1
.link_graph
);
3997 if (ge1
.link_graph
!= ge2
.link_graph
) {
3998 LinkGraph
*lg2
= LinkGraph::Get(ge2
.link_graph
);
3999 if (lg
->Size() < lg2
->Size()) {
4000 LinkGraphSchedule::instance
.Unqueue(lg
);
4001 lg2
->Merge(lg
); // Updates GoodsEntries of lg
4004 LinkGraphSchedule::instance
.Unqueue(lg2
);
4005 lg
->Merge(lg2
); // Updates GoodsEntries of lg2
4010 (*lg
)[ge1
.node
].UpdateEdge(ge2
.node
, capacity
, usage
, mode
);
4014 /* called for every station each tick */
4015 static void StationHandleSmallTick(BaseStation
*st
)
4017 if ((st
->facilities
& FACIL_WAYPOINT
) != 0 || !st
->IsInUse()) return;
4019 byte b
= st
->delete_ctr
+ 1;
4020 if (b
>= STATION_RATING_TICKS
) b
= 0;
4023 if (b
== 0) UpdateStationRating(Station::From(st
));
4026 void OnTick_Station()
4028 if (_game_mode
== GM_EDITOR
) return;
4031 FOR_ALL_BASE_STATIONS(st
) {
4032 StationHandleSmallTick(st
);
4034 /* Clean up the link graph about once a week. */
4035 if (Station::IsExpected(st
) && (_tick_counter
+ st
->index
) % STATION_LINKGRAPH_TICKS
== 0) {
4036 DeleteStaleLinks(Station::From(st
));
4039 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
4040 * Station index is included so that triggers are not all done
4041 * at the same time. */
4042 if ((_tick_counter
+ st
->index
) % STATION_ACCEPTANCE_TICKS
== 0) {
4043 /* Stop processing this station if it was deleted */
4044 if (!StationHandleBigTick(st
)) continue;
4045 TriggerStationAnimation(st
, st
->xy
, SAT_250_TICKS
);
4046 if (Station::IsExpected(st
)) AirportAnimationTrigger(Station::From(st
), AAT_STATION_250_TICKS
);
4051 /** Daily loop for stations. */
4052 void StationDailyLoop()
4054 // Only record cargo history every second day.
4055 if (_date
% 2 != 0) {
4058 FOR_ALL_STATIONS(st
) {
4059 st
->UpdateCargoHistory();
4064 /** Monthly loop for stations. */
4065 void StationMonthlyLoop()
4069 FOR_ALL_STATIONS(st
) {
4070 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
4071 GoodsEntry
*ge
= &st
->goods
[i
];
4072 SB(ge
->status
, GoodsEntry::GES_LAST_MONTH
, 1, GB(ge
->status
, GoodsEntry::GES_CURRENT_MONTH
, 1));
4073 ClrBit(ge
->status
, GoodsEntry::GES_CURRENT_MONTH
);
4079 void ModifyStationRatingAround(TileIndex tile
, Owner owner
, int amount
, uint radius
)
4083 FOR_ALL_STATIONS(st
) {
4084 if (st
->owner
== owner
&&
4085 DistanceManhattan(tile
, st
->xy
) <= radius
) {
4086 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
4087 GoodsEntry
*ge
= &st
->goods
[i
];
4089 if (ge
->status
!= 0) {
4090 ge
->rating
= Clamp(ge
->rating
+ amount
, 0, 255);
4097 static uint
UpdateStationWaiting(Station
*st
, CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
)
4099 /* We can't allocate a CargoPacket? Then don't do anything
4100 * at all; i.e. just discard the incoming cargo. */
4101 if (!CargoPacket::CanAllocateItem()) return 0;
4103 GoodsEntry
&ge
= st
->goods
[type
];
4104 amount
+= ge
.amount_fract
;
4105 ge
.amount_fract
= GB(amount
, 0, 8);
4108 /* No new "real" cargo item yet. */
4109 if (amount
== 0) return 0;
4111 StationID next
= ge
.GetVia(st
->index
);
4112 ge
.cargo
.Append(new CargoPacket(st
->index
, st
->xy
, amount
, source_type
, source_id
), next
);
4113 LinkGraph
*lg
= NULL
;
4114 if (ge
.link_graph
== INVALID_LINK_GRAPH
) {
4115 if (LinkGraph::CanAllocateItem()) {
4116 lg
= new LinkGraph(type
);
4117 LinkGraphSchedule::instance
.Queue(lg
);
4118 ge
.link_graph
= lg
->index
;
4119 ge
.node
= lg
->AddNode(st
);
4121 DEBUG(misc
, 0, "Can't allocate link graph");
4124 lg
= LinkGraph::Get(ge
.link_graph
);
4126 if (lg
!= NULL
) (*lg
)[ge
.node
].UpdateSupply(amount
);
4128 if (!ge
.HasRating()) {
4129 InvalidateWindowData(WC_STATION_LIST
, st
->index
);
4130 SetBit(ge
.status
, GoodsEntry::GES_RATING
);
4133 TriggerStationRandomisation(st
, st
->xy
, SRT_NEW_CARGO
, type
);
4134 TriggerStationAnimation(st
, st
->xy
, SAT_NEW_CARGO
, type
);
4135 AirportAnimationTrigger(st
, AAT_STATION_NEW_CARGO
, type
);
4137 SetWindowDirty(WC_STATION_VIEW
, st
->index
);
4138 st
->MarkTilesDirty(true);
4142 static bool IsUniqueStationName(const char *name
)
4146 FOR_ALL_STATIONS(st
) {
4147 if (st
->name
!= NULL
&& strcmp(st
->name
, name
) == 0) return false;
4155 * @param tile unused
4156 * @param flags operation to perform
4157 * @param p1 station ID that is to be renamed
4159 * @param text the new name or an empty string when resetting to the default
4160 * @return the cost of this operation or an error
4162 CommandCost
CmdRenameStation(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
4164 Station
*st
= Station::GetIfValid(p1
);
4165 if (st
== NULL
) return CMD_ERROR
;
4167 CommandCost ret
= CheckOwnership(st
->owner
);
4168 if (ret
.Failed()) return ret
;
4170 bool reset
= StrEmpty(text
);
4173 if (Utf8StringLength(text
) >= MAX_LENGTH_STATION_NAME_CHARS
) return CMD_ERROR
;
4174 if (!IsUniqueStationName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
4177 if (flags
& DC_EXEC
) {
4179 st
->name
= reset
? NULL
: stredup(text
);
4181 st
->UpdateVirtCoord();
4182 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 1);
4185 return CommandCost();
4189 * Find all stations around a rectangular producer (industry, house, headquarter, ...)
4191 * @param location The location/area of the producer
4192 * @param stations The list to store the stations in
4194 void FindStationsAroundTiles(const TileArea
&location
, StationList
*stations
)
4196 /* area to search = producer plus station catchment radius */
4197 uint max_rad
= (_settings_game
.station
.modified_catchment
? MAX_CATCHMENT
: CA_UNMODIFIED
);
4199 uint x
= TileX(location
.tile
);
4200 uint y
= TileY(location
.tile
);
4202 uint min_x
= (x
> max_rad
) ? x
- max_rad
: 0;
4203 uint max_x
= x
+ location
.w
+ max_rad
;
4204 uint min_y
= (y
> max_rad
) ? y
- max_rad
: 0;
4205 uint max_y
= y
+ location
.h
+ max_rad
;
4207 if (min_x
== 0 && _settings_game
.construction
.freeform_edges
) min_x
= 1;
4208 if (min_y
== 0 && _settings_game
.construction
.freeform_edges
) min_y
= 1;
4209 if (max_x
>= MapSizeX()) max_x
= MapSizeX() - 1;
4210 if (max_y
>= MapSizeY()) max_y
= MapSizeY() - 1;
4212 for (uint cy
= min_y
; cy
< max_y
; cy
++) {
4213 for (uint cx
= min_x
; cx
< max_x
; cx
++) {
4214 TileIndex cur_tile
= TileXY(cx
, cy
);
4215 if (!IsTileType(cur_tile
, MP_STATION
)) continue;
4217 Station
*st
= Station::GetByTile(cur_tile
);
4218 /* st can be NULL in case of waypoints */
4219 if (st
== NULL
) continue;
4221 if (_settings_game
.station
.modified_catchment
) {
4222 int rad
= st
->GetCatchmentRadius();
4226 if (rad_x
< -rad
|| rad_x
>= rad
+ location
.w
) continue;
4227 if (rad_y
< -rad
|| rad_y
>= rad
+ location
.h
) continue;
4230 /* Insert the station in the set. This will fail if it has
4231 * already been added.
4233 stations
->Include(st
);
4239 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
4240 * @return pointer to a StationList containing all stations found
4242 const StationList
*StationFinder::GetStations()
4244 if (this->tile
!= INVALID_TILE
) {
4245 FindStationsAroundTiles(*this, &this->stations
);
4246 this->tile
= INVALID_TILE
;
4248 return &this->stations
;
4251 uint
MoveGoodsToStation(CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
, const StationList
*all_stations
)
4253 /* Return if nothing to do. Also the rounding below fails for 0. */
4254 if (amount
== 0) return 0;
4256 Station
*st1
= NULL
; // Station with best rating
4257 Station
*st2
= NULL
; // Second best station
4258 uint best_rating1
= 0; // rating of st1
4259 uint best_rating2
= 0; // rating of st2
4261 for (Station
* const *st_iter
= all_stations
->Begin(); st_iter
!= all_stations
->End(); ++st_iter
) {
4262 Station
*st
= *st_iter
;
4264 /* Is the station reserved exclusively for somebody else? */
4265 if (st
->town
->exclusive_counter
> 0 && st
->town
->exclusivity
!= st
->owner
) continue;
4267 if (st
->goods
[type
].rating
== 0) continue; // Lowest possible rating, better not to give cargo anymore
4269 if (_settings_game
.order
.selectgoods
&& !st
->goods
[type
].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
4271 if (IsCargoInClass(type
, CC_PASSENGERS
)) {
4272 if (st
->facilities
== FACIL_TRUCK_STOP
) continue; // passengers are never served by just a truck stop
4274 if (st
->facilities
== FACIL_BUS_STOP
) continue; // non-passengers are never served by just a bus stop
4277 /* This station can be used, add it to st1/st2 */
4278 if (st1
== NULL
|| st
->goods
[type
].rating
>= best_rating1
) {
4279 st2
= st1
; best_rating2
= best_rating1
; st1
= st
; best_rating1
= st
->goods
[type
].rating
;
4280 } else if (st2
== NULL
|| st
->goods
[type
].rating
>= best_rating2
) {
4281 st2
= st
; best_rating2
= st
->goods
[type
].rating
;
4285 /* no stations around at all? */
4286 if (st1
== NULL
) return 0;
4288 /* From now we'll calculate with fractal cargo amounts.
4289 * First determine how much cargo we really have. */
4290 amount
*= best_rating1
+ 1;
4293 /* only one station around */
4294 return UpdateStationWaiting(st1
, type
, amount
, source_type
, source_id
);
4297 /* several stations around, the best two (highest rating) are in st1 and st2 */
4298 assert(st1
!= NULL
);
4299 assert(st2
!= NULL
);
4300 assert(best_rating1
!= 0 || best_rating2
!= 0);
4302 /* Then determine the amount the worst station gets. We do it this way as the
4303 * best should get a bonus, which in this case is the rounding difference from
4304 * this calculation. In reality that will mean the bonus will be pretty low.
4305 * Nevertheless, the best station should always get the most cargo regardless
4306 * of rounding issues. */
4307 uint worst_cargo
= amount
* best_rating2
/ (best_rating1
+ best_rating2
);
4308 assert(worst_cargo
<= (amount
- worst_cargo
));
4310 /* And then send the cargo to the stations! */
4311 uint moved
= UpdateStationWaiting(st1
, type
, amount
- worst_cargo
, source_type
, source_id
);
4312 /* These two UpdateStationWaiting's can't be in the statement as then the order
4313 * of execution would be undefined and that could cause desyncs with callbacks. */
4314 return moved
+ UpdateStationWaiting(st2
, type
, worst_cargo
, source_type
, source_id
);
4317 void BuildOilRig(TileIndex tile
)
4319 if (!Station::CanAllocateItem()) {
4320 DEBUG(misc
, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile
);
4324 Station
*st
= new Station(tile
);
4325 st
->town
= ClosestTownFromTile(tile
, UINT_MAX
);
4327 st
->string_id
= GenerateStationName(st
, tile
, 1, 1, STATIONNAMING_OILRIG
);
4329 assert(IsTileType(tile
, MP_INDUSTRY
));
4330 DeleteAnimatedTile(tile
);
4331 MakeOilrig(tile
, st
->index
, GetWaterClass(tile
));
4333 st
->owner
= OWNER_NONE
;
4334 st
->airport
.type
= AT_OILRIG
;
4335 st
->airport
.Add(tile
);
4336 st
->dock_station
.tile
= tile
;
4337 st
->facilities
= FACIL_AIRPORT
;
4339 if (!Dock::CanAllocateItem()) {
4340 DEBUG(misc
, 0, "Can't allocate dock for oilrig at 0x%X, reverting to oilrig with airport only", tile
);
4342 st
->docks
= new Dock(tile
, tile
+ ToTileIndexDiff({1, 0}));
4343 st
->dock_station
.tile
= tile
;
4344 st
->facilities
|= FACIL_DOCK
;
4347 st
->build_date
= _date
;
4349 st
->rect
.BeforeAddTile(tile
, StationRect::ADD_FORCE
);
4350 st
->catchment
.BeforeAddTile(tile
, st
->GetCatchmentRadius());
4352 st
->UpdateVirtCoord();
4353 UpdateStationAcceptance(st
, false);
4354 st
->RecomputeIndustriesNear();
4355 ZoningMarkDirtyStationCoverageArea(st
);
4358 void DeleteOilRig(TileIndex tile
)
4360 Station
*st
= Station::GetByTile(tile
);
4361 ZoningMarkDirtyStationCoverageArea(st
);
4363 st
->catchment
.AfterRemoveTile(tile
, st
->GetCatchmentRadius());
4364 MakeWaterKeepingClass(tile
, OWNER_NONE
);
4366 st
->dock_station
.tile
= INVALID_TILE
;
4367 if (st
->docks
!= NULL
) {
4371 st
->airport
.Clear();
4372 st
->facilities
&= ~(FACIL_AIRPORT
| FACIL_DOCK
);
4373 st
->airport
.flags
= 0;
4375 if (Overlays::Instance()->HasStation(st
)) st
->MarkAcceptanceTilesDirty();
4376 st
->rect
.AfterRemoveTile(st
, tile
);
4378 st
->UpdateVirtCoord();
4379 st
->RecomputeIndustriesNear();
4380 if (!st
->IsInUse()) delete st
;
4383 static void ChangeTileOwner_Station(TileIndex tile
, Owner old_owner
, Owner new_owner
)
4385 if (IsRoadStopTile(tile
)) {
4386 for (RoadType rt
= ROADTYPE_ROAD
; rt
< ROADTYPE_END
; rt
++) {
4387 /* Update all roadtypes, no matter if they are present */
4388 if (GetRoadOwner(tile
, rt
) == old_owner
) {
4389 if (HasTileRoadType(tile
, rt
)) {
4390 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4391 Company::Get(old_owner
)->infrastructure
.road
[rt
] -= 2;
4392 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.road
[rt
] += 2;
4394 SetRoadOwner(tile
, rt
, new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
);
4399 if (!IsTileOwner(tile
, old_owner
)) return;
4401 if (new_owner
!= INVALID_OWNER
) {
4402 /* Update company infrastructure counts. Only do it here
4403 * if the new owner is valid as otherwise the clear
4404 * command will do it for us. No need to dirty windows
4405 * here, we'll redraw the whole screen anyway.*/
4406 Company
*old_company
= Company::Get(old_owner
);
4407 Company
*new_company
= Company::Get(new_owner
);
4409 /* Update counts for underlying infrastructure. */
4410 switch (GetStationType(tile
)) {
4412 case STATION_WAYPOINT
:
4413 if (!IsStationTileBlocked(tile
)) {
4414 old_company
->infrastructure
.rail
[GetRailType(tile
)]--;
4415 new_company
->infrastructure
.rail
[GetRailType(tile
)]++;
4421 /* Road stops were already handled above. */
4426 if (GetWaterClass(tile
) == WATER_CLASS_CANAL
) {
4427 old_company
->infrastructure
.water
--;
4428 new_company
->infrastructure
.water
++;
4436 /* Update station tile count. */
4437 if (!IsBuoy(tile
) && !IsAirport(tile
)) {
4438 old_company
->infrastructure
.station
--;
4439 new_company
->infrastructure
.station
++;
4442 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4443 SetTileOwner(tile
, new_owner
);
4444 InvalidateWindowClassesData(WC_STATION_LIST
, 0);
4446 if (IsDriveThroughStopTile(tile
)) {
4447 /* Remove the drive-through road stop */
4448 DoCommand(tile
, 1 | 1 << 8, (GetStationType(tile
) == STATION_TRUCK
) ? ROADSTOP_TRUCK
: ROADSTOP_BUS
, DC_EXEC
| DC_BANKRUPT
, CMD_REMOVE_ROAD_STOP
);
4449 assert(IsTileType(tile
, MP_ROAD
));
4450 /* Change owner of tile and all roadtypes */
4451 ChangeTileOwner(tile
, old_owner
, new_owner
);
4453 DoCommand(tile
, 0, 0, DC_EXEC
| DC_BANKRUPT
, CMD_LANDSCAPE_CLEAR
);
4454 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4455 * Update owner of buoy if it was not removed (was in orders).
4456 * Do not update when owned by OWNER_WATER (sea and rivers). */
4457 if ((IsTileType(tile
, MP_WATER
) || IsBuoyTile(tile
)) && IsTileOwner(tile
, old_owner
)) SetTileOwner(tile
, OWNER_NONE
);
4463 * Check if a drive-through road stop tile can be cleared.
4464 * Road stops built on town-owned roads check the conditions
4465 * that would allow clearing of the original road.
4466 * @param tile road stop tile to check
4467 * @param flags command flags
4468 * @return true if the road can be cleared
4470 static bool CanRemoveRoadWithStop(TileIndex tile
, DoCommandFlag flags
)
4472 /* Yeah... water can always remove stops, right? */
4473 if (_current_company
== OWNER_WATER
) return true;
4475 RoadTypes rts
= GetRoadTypes(tile
);
4476 if (HasBit(rts
, ROADTYPE_TRAM
)) {
4477 Owner tram_owner
= GetRoadOwner(tile
, ROADTYPE_TRAM
);
4478 if (tram_owner
!= OWNER_NONE
&& CheckOwnership(tram_owner
).Failed()) return false;
4480 if (HasBit(rts
, ROADTYPE_ROAD
)) {
4481 Owner road_owner
= GetRoadOwner(tile
, ROADTYPE_ROAD
);
4482 if (road_owner
!= OWNER_TOWN
) {
4483 if (road_owner
!= OWNER_NONE
&& CheckOwnership(road_owner
).Failed()) return false;
4485 if (CheckAllowRemoveRoad(tile
, GetAnyRoadBits(tile
, ROADTYPE_ROAD
), OWNER_TOWN
, ROADTYPE_ROAD
, flags
).Failed()) return false;
4493 * Clear a single tile of a station.
4494 * @param tile The tile to clear.
4495 * @param flags The DoCommand flags related to the "command".
4496 * @return The cost, or error of clearing.
4498 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
)
4500 if (flags
& DC_AUTO
) {
4501 switch (GetStationType(tile
)) {
4503 case STATION_RAIL
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD
);
4504 case STATION_WAYPOINT
: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
4505 case STATION_AIRPORT
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
4506 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
);
4507 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
);
4508 case STATION_BUOY
: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY
);
4509 case STATION_DOCK
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST
);
4510 case STATION_OILRIG
:
4511 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG
);
4512 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY
);
4516 switch (GetStationType(tile
)) {
4517 case STATION_RAIL
: return RemoveRailStation(tile
, flags
);
4518 case STATION_WAYPOINT
: return RemoveRailWaypoint(tile
, flags
);
4519 case STATION_AIRPORT
: return RemoveAirport(tile
, flags
);
4521 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4522 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST
);
4524 return RemoveRoadStop(tile
, flags
);
4526 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4527 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST
);
4529 return RemoveRoadStop(tile
, flags
);
4530 case STATION_BUOY
: return RemoveBuoy(tile
, flags
);
4531 case STATION_DOCK
: return RemoveDock(tile
, flags
);
4538 static CommandCost
TerraformTile_Station(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
4540 if (_settings_game
.construction
.build_on_slopes
&& AutoslopeEnabled()) {
4541 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4542 * TTDP does not call it.
4544 if (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
)) {
4545 switch (GetStationType(tile
)) {
4546 case STATION_WAYPOINT
:
4547 case STATION_RAIL
: {
4548 DiagDirection direction
= AxisToDiagDir(GetRailStationAxis(tile
));
4549 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4550 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4551 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4554 case STATION_AIRPORT
:
4555 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4559 DiagDirection direction
= GetRoadStopDir(tile
);
4560 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4561 if (IsDriveThroughStopTile(tile
)) {
4562 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4564 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4571 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
4575 * Get flow for a station.
4576 * @param st Station to get flow for.
4577 * @return Flow for st.
4579 uint
FlowStat::GetShare(StationID st
) const
4582 for (SharesMap::const_iterator it
= this->shares
.begin(); it
!= this->shares
.end(); ++it
) {
4583 if (it
->second
== st
) {
4584 return it
->first
- prev
;
4593 * Get a station a package can be routed to, but exclude the given ones.
4594 * @param excluded StationID not to be selected.
4595 * @param excluded2 Another StationID not to be selected.
4596 * @return A station ID from the shares map.
4598 StationID
FlowStat::GetVia(StationID excluded
, StationID excluded2
) const
4600 if (this->unrestricted
== 0) return INVALID_STATION
;
4601 assert(!this->shares
.empty());
4602 SharesMap::const_iterator it
= this->shares
.upper_bound(RandomRange(this->unrestricted
));
4603 assert(it
!= this->shares
.end() && it
->first
<= this->unrestricted
);
4604 if (it
->second
!= excluded
&& it
->second
!= excluded2
) return it
->second
;
4606 /* We've hit one of the excluded stations.
4607 * Draw another share, from outside its range. */
4609 uint end
= it
->first
;
4610 uint begin
= (it
== this->shares
.begin() ? 0 : (--it
)->first
);
4611 uint interval
= end
- begin
;
4612 if (interval
>= this->unrestricted
) return INVALID_STATION
; // Only one station in the map.
4613 uint new_max
= this->unrestricted
- interval
;
4614 uint rand
= RandomRange(new_max
);
4615 SharesMap::const_iterator it2
= (rand
< begin
) ? this->shares
.upper_bound(rand
) :
4616 this->shares
.upper_bound(rand
+ interval
);
4617 assert(it2
!= this->shares
.end() && it2
->first
<= this->unrestricted
);
4618 if (it2
->second
!= excluded
&& it2
->second
!= excluded2
) return it2
->second
;
4620 /* We've hit the second excluded station.
4621 * Same as before, only a bit more complicated. */
4623 uint end2
= it2
->first
;
4624 uint begin2
= (it2
== this->shares
.begin() ? 0 : (--it2
)->first
);
4625 uint interval2
= end2
- begin2
;
4626 if (interval2
>= new_max
) return INVALID_STATION
; // Only the two excluded stations in the map.
4627 new_max
-= interval2
;
4628 if (begin
> begin2
) {
4629 Swap(begin
, begin2
);
4631 Swap(interval
, interval2
);
4633 rand
= RandomRange(new_max
);
4634 SharesMap::const_iterator it3
= this->shares
.upper_bound(this->unrestricted
);
4636 it3
= this->shares
.upper_bound(rand
);
4637 } else if (rand
< begin2
- interval
) {
4638 it3
= this->shares
.upper_bound(rand
+ interval
);
4640 it3
= this->shares
.upper_bound(rand
+ interval
+ interval2
);
4642 assert(it3
!= this->shares
.end() && it3
->first
<= this->unrestricted
);
4647 * Reduce all flows to minimum capacity so that they don't get in the way of
4648 * link usage statistics too much. Keep them around, though, to continue
4649 * routing any remaining cargo.
4651 void FlowStat::Invalidate()
4653 assert(!this->shares
.empty());
4654 SharesMap new_shares
;
4656 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4657 new_shares
[++i
] = it
->second
;
4658 if (it
->first
== this->unrestricted
) this->unrestricted
= i
;
4660 this->shares
.swap(new_shares
);
4661 assert(!this->shares
.empty() && this->unrestricted
<= (--this->shares
.end())->first
);
4665 * Change share for specified station. By specifing INT_MIN as parameter you
4666 * can erase a share. Newly added flows will be unrestricted.
4667 * @param st Next Hop to be removed.
4668 * @param flow Share to be added or removed.
4670 void FlowStat::ChangeShare(StationID st
, int flow
)
4672 /* We assert only before changing as afterwards the shares can actually
4673 * be empty. In that case the whole flow stat must be deleted then. */
4674 assert(!this->shares
.empty());
4676 uint removed_shares
= 0;
4677 uint added_shares
= 0;
4678 uint last_share
= 0;
4679 SharesMap new_shares
;
4680 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4681 if (it
->second
== st
) {
4683 uint share
= it
->first
- last_share
;
4684 if (flow
== INT_MIN
|| (uint
)(-flow
) >= share
) {
4685 removed_shares
+= share
;
4686 if (it
->first
<= this->unrestricted
) this->unrestricted
-= share
;
4687 if (flow
!= INT_MIN
) flow
+= share
;
4688 last_share
= it
->first
;
4689 continue; // remove the whole share
4691 removed_shares
+= (uint
)(-flow
);
4693 added_shares
+= (uint
)(flow
);
4695 if (it
->first
<= this->unrestricted
) this->unrestricted
+= flow
;
4697 /* If we don't continue above the whole flow has been added or
4701 new_shares
[it
->first
+ added_shares
- removed_shares
] = it
->second
;
4702 last_share
= it
->first
;
4705 new_shares
[last_share
+ (uint
)flow
] = st
;
4706 if (this->unrestricted
< last_share
) {
4707 this->ReleaseShare(st
);
4709 this->unrestricted
+= flow
;
4712 this->shares
.swap(new_shares
);
4716 * Restrict a flow by moving it to the end of the map and decreasing the amount
4717 * of unrestricted flow.
4718 * @param st Station of flow to be restricted.
4720 void FlowStat::RestrictShare(StationID st
)
4722 assert(!this->shares
.empty());
4724 uint last_share
= 0;
4725 SharesMap new_shares
;
4726 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4728 if (it
->first
> this->unrestricted
) return; // Not present or already restricted.
4729 if (it
->second
== st
) {
4730 flow
= it
->first
- last_share
;
4731 this->unrestricted
-= flow
;
4733 new_shares
[it
->first
] = it
->second
;
4736 new_shares
[it
->first
- flow
] = it
->second
;
4738 last_share
= it
->first
;
4740 if (flow
== 0) return;
4741 new_shares
[last_share
+ flow
] = st
;
4742 this->shares
.swap(new_shares
);
4743 assert(!this->shares
.empty());
4747 * Release ("unrestrict") a flow by moving it to the begin of the map and
4748 * increasing the amount of unrestricted flow.
4749 * @param st Station of flow to be released.
4751 void FlowStat::ReleaseShare(StationID st
)
4753 assert(!this->shares
.empty());
4755 uint next_share
= 0;
4757 for (SharesMap::reverse_iterator
it(this->shares
.rbegin()); it
!= this->shares
.rend(); ++it
) {
4758 if (it
->first
< this->unrestricted
) return; // Note: not <= as the share may hit the limit.
4760 flow
= next_share
- it
->first
;
4761 this->unrestricted
+= flow
;
4764 if (it
->first
== this->unrestricted
) return; // !found -> Limit not hit.
4765 if (it
->second
== st
) found
= true;
4767 next_share
= it
->first
;
4769 if (flow
== 0) return;
4770 SharesMap new_shares
;
4771 new_shares
[flow
] = st
;
4772 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4773 if (it
->second
!= st
) {
4774 new_shares
[flow
+ it
->first
] = it
->second
;
4779 this->shares
.swap(new_shares
);
4780 assert(!this->shares
.empty());
4784 * Scale all shares from link graph's runtime to monthly values.
4785 * @param runtime Time the link graph has been running without compression.
4786 * @pre runtime must be greater than 0 as we don't want infinite flow values.
4788 void FlowStat::ScaleToMonthly(uint runtime
)
4790 assert(runtime
> 0);
4791 SharesMap new_shares
;
4793 for (SharesMap::iterator i
= this->shares
.begin(); i
!= this->shares
.end(); ++i
) {
4794 share
= max(share
+ 1, i
->first
* 30 / runtime
);
4795 new_shares
[share
] = i
->second
;
4796 if (this->unrestricted
== i
->first
) this->unrestricted
= share
;
4798 this->shares
.swap(new_shares
);
4802 * Add some flow from "origin", going via "via".
4803 * @param origin Origin of the flow.
4804 * @param via Next hop.
4805 * @param flow Amount of flow to be added.
4807 void FlowStatMap::AddFlow(StationID origin
, StationID via
, uint flow
)
4809 FlowStatMap::iterator origin_it
= this->find(origin
);
4810 if (origin_it
== this->end()) {
4811 this->insert(std::make_pair(origin
, FlowStat(via
, flow
)));
4813 origin_it
->second
.ChangeShare(via
, flow
);
4814 assert(!origin_it
->second
.GetShares()->empty());
4819 * Pass on some flow, remembering it as invalid, for later subtraction from
4820 * locally consumed flow. This is necessary because we can't have negative
4821 * flows and we don't want to sort the flows before adding them up.
4822 * @param origin Origin of the flow.
4823 * @param via Next hop.
4824 * @param flow Amount of flow to be passed.
4826 void FlowStatMap::PassOnFlow(StationID origin
, StationID via
, uint flow
)
4828 FlowStatMap::iterator prev_it
= this->find(origin
);
4829 if (prev_it
== this->end()) {
4830 FlowStat
fs(via
, flow
);
4831 fs
.AppendShare(INVALID_STATION
, flow
);
4832 this->insert(std::make_pair(origin
, fs
));
4834 prev_it
->second
.ChangeShare(via
, flow
);
4835 prev_it
->second
.ChangeShare(INVALID_STATION
, flow
);
4836 assert(!prev_it
->second
.GetShares()->empty());
4841 * Subtract invalid flows from locally consumed flow.
4842 * @param self ID of own station.
4844 void FlowStatMap::FinalizeLocalConsumption(StationID self
)
4846 for (FlowStatMap::iterator i
= this->begin(); i
!= this->end(); ++i
) {
4847 FlowStat
&fs
= i
->second
;
4848 uint local
= fs
.GetShare(INVALID_STATION
);
4849 if (local
> INT_MAX
) { // make sure it fits in an int
4850 fs
.ChangeShare(self
, -INT_MAX
);
4851 fs
.ChangeShare(INVALID_STATION
, -INT_MAX
);
4854 fs
.ChangeShare(self
, -(int)local
);
4855 fs
.ChangeShare(INVALID_STATION
, -(int)local
);
4857 /* If the local share is used up there must be a share for some
4858 * remote station. */
4859 assert(!fs
.GetShares()->empty());
4864 * Delete all flows at a station for specific cargo and destination.
4865 * @param via Remote station of flows to be deleted.
4866 * @return IDs of source stations for which the complete FlowStat, not only a
4867 * share, has been erased.
4869 StationIDStack
FlowStatMap::DeleteFlows(StationID via
)
4872 for (FlowStatMap::iterator f_it
= this->begin(); f_it
!= this->end();) {
4873 FlowStat
&s_flows
= f_it
->second
;
4874 s_flows
.ChangeShare(via
, INT_MIN
);
4875 if (s_flows
.GetShares()->empty()) {
4876 ret
.Push(f_it
->first
);
4877 this->erase(f_it
++);
4886 * Restrict all flows at a station for specific cargo and destination.
4887 * @param via Remote station of flows to be restricted.
4889 void FlowStatMap::RestrictFlows(StationID via
)
4891 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4892 it
->second
.RestrictShare(via
);
4897 * Release all flows at a station for specific cargo and destination.
4898 * @param via Remote station of flows to be released.
4900 void FlowStatMap::ReleaseFlows(StationID via
)
4902 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4903 it
->second
.ReleaseShare(via
);
4908 * Get the sum of all flows from this FlowStatMap.
4909 * @return sum of all flows.
4911 uint
FlowStatMap::GetFlow() const
4914 for (FlowStatMap::const_iterator i
= this->begin(); i
!= this->end(); ++i
) {
4915 ret
+= (--(i
->second
.GetShares()->end()))->first
;
4921 * Get the sum of flows via a specific station from this FlowStatMap.
4922 * @param via Remote station to look for.
4923 * @return all flows for 'via' added up.
4925 uint
FlowStatMap::GetFlowVia(StationID via
) const
4928 for (FlowStatMap::const_iterator i
= this->begin(); i
!= this->end(); ++i
) {
4929 ret
+= i
->second
.GetShare(via
);
4935 * Get the sum of flows from a specific station from this FlowStatMap.
4936 * @param from Origin station to look for.
4937 * @return all flows from 'from' added up.
4939 uint
FlowStatMap::GetFlowFrom(StationID from
) const
4941 FlowStatMap::const_iterator i
= this->find(from
);
4942 if (i
== this->end()) return 0;
4943 return (--(i
->second
.GetShares()->end()))->first
;
4947 * Get the flow from a specific station via a specific other station.
4948 * @param from Origin station to look for.
4949 * @param via Remote station to look for.
4950 * @return flow share originating at 'from' and going to 'via'.
4952 uint
FlowStatMap::GetFlowFromVia(StationID from
, StationID via
) const
4954 FlowStatMap::const_iterator i
= this->find(from
);
4955 if (i
== this->end()) return 0;
4956 return i
->second
.GetShare(via
);
4959 extern const TileTypeProcs _tile_type_station_procs
= {
4960 DrawTile_Station
, // draw_tile_proc
4961 GetSlopePixelZ_Station
, // get_slope_z_proc
4962 ClearTile_Station
, // clear_tile_proc
4963 NULL
, // add_accepted_cargo_proc
4964 GetTileDesc_Station
, // get_tile_desc_proc
4965 GetTileTrackStatus_Station
, // get_tile_track_status_proc
4966 ClickTile_Station
, // click_tile_proc
4967 AnimateTile_Station
, // animate_tile_proc
4968 TileLoop_Station
, // tile_loop_proc
4969 ChangeTileOwner_Station
, // change_tile_owner_proc
4970 NULL
, // add_produced_cargo_proc
4971 VehicleEnter_Station
, // vehicle_enter_tile_proc
4972 GetFoundation_Station
, // get_foundation_proc
4973 TerraformTile_Station
, // terraform_tile_proc