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 "cmd_helper.h"
15 #include "viewport_func.h"
16 #include "command_func.h"
18 #include "news_func.h"
23 #include "newgrf_cargo.h"
24 #include "newgrf_debug.h"
25 #include "newgrf_station.h"
26 #include "newgrf_canal.h" /* For the buoy */
27 #include "pathfinder/yapf/yapf_cache.h"
28 #include "road_internal.h" /* For drawing catenary/checking road removal */
29 #include "autoslope.h"
31 #include "strings_func.h"
32 #include "clear_func.h"
33 #include "date_func.h"
34 #include "vehicle_func.h"
35 #include "string_func.h"
36 #include "animated_tile_func.h"
37 #include "elrail_func.h"
38 #include "station_base.h"
39 #include "roadstop_base.h"
40 #include "newgrf_railtype.h"
41 #include "waypoint_base.h"
42 #include "waypoint_func.h"
45 #include "core/random_func.hpp"
46 #include "company_base.h"
47 #include "table/airporttile_ids.h"
48 #include "newgrf_airporttiles.h"
49 #include "order_backup.h"
50 #include "newgrf_house.h"
51 #include "company_gui.h"
52 #include "linkgraph/linkgraph_base.h"
53 #include "linkgraph/refresh.h"
54 #include "widgets/station_widget.h"
55 #include "signal_func.h"
56 #include "map/zoneheight.h"
59 #include "table/strings.h"
62 * Check whether the given tile is a hangar.
63 * @param t the tile to of whether it is a hangar.
64 * @pre IsStationTile(t)
65 * @return true if and only if the tile is a hangar.
67 bool IsHangar(TileIndex t
)
69 assert(IsStationTile(t
));
71 /* If the tile isn't an airport there's no chance it's a hangar. */
72 if (!IsAirport(t
)) return false;
74 const Station
*st
= Station::GetByTile(t
);
75 const AirportSpec
*as
= st
->airport
.GetSpec();
77 for (uint i
= 0; i
< as
->nof_depots
; i
++) {
78 if (st
->airport
.GetHangarTile(i
) == t
) return true;
85 * Function to check whether the given tile matches some criterion.
86 * @param tile the tile to check
87 * @return true if it matches, false otherwise
89 typedef bool (*CMSAMatcher
)(TileIndex tile
);
92 * Counts the numbers of tiles matching a specific type in the area around
93 * @param tile the center tile of the 'count area'
94 * @param cmp the comparator/matcher (@see CMSAMatcher)
95 * @return the number of matching tiles around
97 static int CountMapSquareAround(TileIndex tile
, CMSAMatcher cmp
)
101 for (int dx
= -3; dx
<= 3; dx
++) {
102 for (int dy
= -3; dy
<= 3; dy
++) {
103 TileIndex t
= TileAddWrap(tile
, dx
, dy
);
104 if (t
!= INVALID_TILE
&& cmp(t
)) num
++;
112 * Check whether the tile is a mine.
113 * @param tile the tile to investigate.
114 * @return true if and only if the tile is a mine
116 static bool CMSAMine(TileIndex tile
)
119 if (!IsIndustryTile(tile
)) return false;
121 const Industry
*ind
= Industry::GetByTile(tile
);
123 /* No extractive industry */
124 if ((GetIndustrySpec(ind
->type
)->life_type
& INDUSTRYLIFE_EXTRACTIVE
) == 0) return false;
126 for (uint i
= 0; i
< lengthof(ind
->produced_cargo
); i
++) {
127 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
128 * Also the production of passengers and mail is ignored. */
129 if (ind
->produced_cargo
[i
] != CT_INVALID
&&
130 (CargoSpec::Get(ind
->produced_cargo
[i
])->classes
& (CC_LIQUID
| CC_PASSENGERS
| CC_MAIL
)) == 0) {
139 * Check whether the tile is water.
140 * @param tile the tile to investigate.
141 * @return true if and only if the tile is a water tile
143 static bool CMSAWater(TileIndex tile
)
145 return IsPlainWaterTile(tile
);
149 * Check whether the tile is a tree.
150 * @param tile the tile to investigate.
151 * @return true if and only if the tile is a tree tile
153 static bool CMSATree(TileIndex tile
)
155 return IsTreeTile(tile
);
158 #define M(x) ((x) - STR_SV_STNAME)
163 STATIONNAMING_AIRPORT
,
164 STATIONNAMING_OILRIG
,
166 STATIONNAMING_HELIPORT
,
169 /** Information to handle station action 0 property 24 correctly */
170 struct StationNameInformation
{
171 uint32 free_names
; ///< Current bitset of free names (we can remove names).
172 bool *indtypes
; ///< Array of bools telling whether an industry type has been found.
176 * Find a station action 0 property 24 station name, or reduce the
177 * free_names if needed.
178 * @param tile the tile to search
179 * @param user_data the StationNameInformation to base the search on
180 * @return true if the tile contains an industry that has not given
181 * its name to one of the other stations in town.
183 static bool FindNearIndustryName(TileIndex tile
, void *user_data
)
185 /* All already found industry types */
186 StationNameInformation
*sni
= (StationNameInformation
*)user_data
;
187 if (!IsIndustryTile(tile
)) return false;
189 /* If the station name is undefined it means that it doesn't name a station */
190 IndustryType indtype
= GetIndustryType(tile
);
191 if (GetIndustrySpec(indtype
)->station_name
== STR_UNDEFINED
) return false;
193 /* In all cases if an industry that provides a name is found two of
194 * the standard names will be disabled. */
195 sni
->free_names
&= ~(1 << M(STR_SV_STNAME_OILFIELD
) | 1 << M(STR_SV_STNAME_MINES
));
196 return !sni
->indtypes
[indtype
];
199 static StringID
GenerateStationName(Station
*st
, TileIndex tile
, StationNaming name_class
)
201 static const uint32 _gen_station_name_bits
[] = {
202 0, // STATIONNAMING_RAIL
203 0, // STATIONNAMING_ROAD
204 1U << M(STR_SV_STNAME_AIRPORT
), // STATIONNAMING_AIRPORT
205 1U << M(STR_SV_STNAME_OILFIELD
), // STATIONNAMING_OILRIG
206 1U << M(STR_SV_STNAME_DOCKS
), // STATIONNAMING_DOCK
207 1U << M(STR_SV_STNAME_HELIPORT
), // STATIONNAMING_HELIPORT
210 const Town
*t
= st
->town
;
211 uint32 free_names
= UINT32_MAX
;
213 bool indtypes
[NUM_INDUSTRYTYPES
];
214 memset(indtypes
, 0, sizeof(indtypes
));
217 FOR_ALL_STATIONS(s
) {
218 if (s
!= st
&& s
->town
== t
) {
219 if (s
->indtype
!= IT_INVALID
) {
220 indtypes
[s
->indtype
] = true;
223 uint str
= M(s
->string_id
);
225 if (str
== M(STR_SV_STNAME_FOREST
)) {
226 str
= M(STR_SV_STNAME_WOODS
);
228 ClrBit(free_names
, str
);
233 TileIndex indtile
= tile
;
234 StationNameInformation sni
= { free_names
, indtypes
};
235 if (CircularTileSearch(&indtile
, 7, FindNearIndustryName
, &sni
)) {
236 /* An industry has been found nearby */
237 IndustryType indtype
= GetIndustryType(indtile
);
238 const IndustrySpec
*indsp
= GetIndustrySpec(indtype
);
239 /* STR_NULL means it only disables oil rig/mines */
240 if (indsp
->station_name
!= STR_NULL
) {
241 st
->indtype
= indtype
;
242 return STR_SV_STNAME_FALLBACK
;
246 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
247 free_names
= sni
.free_names
;
249 /* check default names */
250 uint32 tmp
= free_names
& _gen_station_name_bits
[name_class
];
251 if (tmp
!= 0) return STR_SV_STNAME
+ FindFirstBit(tmp
);
254 if (HasBit(free_names
, M(STR_SV_STNAME_MINES
))) {
255 if (CountMapSquareAround(tile
, CMSAMine
) >= 2) {
256 return STR_SV_STNAME_MINES
;
260 /* check close enough to town to get central as name? */
261 if (DistanceMax(tile
, t
->xy
) < 8) {
262 if (HasBit(free_names
, M(STR_SV_STNAME
))) return STR_SV_STNAME
;
264 if (HasBit(free_names
, M(STR_SV_STNAME_CENTRAL
))) return STR_SV_STNAME_CENTRAL
;
268 if (HasBit(free_names
, M(STR_SV_STNAME_LAKESIDE
)) &&
269 DistanceFromEdge(tile
) < 20 &&
270 CountMapSquareAround(tile
, CMSAWater
) >= 5) {
271 return STR_SV_STNAME_LAKESIDE
;
275 if (HasBit(free_names
, M(STR_SV_STNAME_WOODS
)) && (
276 CountMapSquareAround(tile
, CMSATree
) >= 8 ||
277 CountMapSquareAround(tile
, IsTileForestIndustry
) >= 2)
279 return _settings_game
.game_creation
.landscape
== LT_TROPIC
? STR_SV_STNAME_FOREST
: STR_SV_STNAME_WOODS
;
282 /* check elevation compared to town */
283 int z
= GetTileZ(tile
);
284 int z2
= GetTileZ(t
->xy
);
286 if (HasBit(free_names
, M(STR_SV_STNAME_VALLEY
))) return STR_SV_STNAME_VALLEY
;
288 if (HasBit(free_names
, M(STR_SV_STNAME_HEIGHTS
))) return STR_SV_STNAME_HEIGHTS
;
291 /* check direction compared to town */
292 static const int8 _direction_and_table
[] = {
293 ~( (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
294 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
295 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
296 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) ),
299 free_names
&= _direction_and_table
[
300 (TileX(tile
) < TileX(t
->xy
)) +
301 (TileY(tile
) < TileY(t
->xy
)) * 2];
303 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));
304 return (tmp
== 0) ? STR_SV_STNAME_FALLBACK
: (STR_SV_STNAME
+ FindFirstBit(tmp
));
309 * Find the closest deleted station of the current company
310 * @param tile the tile to search from.
311 * @return the closest station or NULL if too far.
313 static Station
*GetClosestDeletedStation(TileIndex tile
)
316 Station
*best_station
= NULL
;
319 FOR_ALL_STATIONS(st
) {
320 if (!st
->IsInUse() && st
->owner
== _current_company
) {
321 uint cur_dist
= DistanceManhattan(tile
, st
->xy
);
323 if (cur_dist
< threshold
) {
324 threshold
= cur_dist
;
334 void Station::GetTileArea(TileArea
*ta
, StationType type
) const
338 *ta
= this->train_station
;
341 case STATION_AIRPORT
:
346 *ta
= this->truck_station
;
350 *ta
= this->bus_station
;
355 *ta
= this->dock_area
;
358 default: NOT_REACHED();
366 * Update the virtual coords needed to draw the station sign.
368 void Station::UpdateVirtCoord()
370 Point pt
= RemapCoords2(TileX(this->xy
) * TILE_SIZE
, TileY(this->xy
) * TILE_SIZE
);
372 pt
.y
-= 32 * ZOOM_LVL_BASE
;
373 if ((this->facilities
& FACIL_AIRPORT
) && this->airport
.type
== AT_OILRIG
) pt
.y
-= 16 * ZOOM_LVL_BASE
;
375 SetDParam(0, this->index
);
376 SetDParam(1, this->facilities
);
377 this->sign
.UpdatePosition(pt
.x
, pt
.y
, STR_VIEWPORT_STATION
);
379 SetWindowDirty(WC_STATION_VIEW
, this->index
);
382 /** Update the virtual coords needed to draw the station sign for all stations. */
383 void UpdateAllStationVirtCoords()
387 FOR_ALL_BASE_STATIONS(st
) {
388 st
->UpdateVirtCoord();
393 * Get a mask of the cargo types that the station accepts.
394 * @param st Station to query
395 * @return the expected mask
397 static uint
GetAcceptanceMask(const Station
*st
)
401 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
402 if (HasBit(st
->goods
[i
].acceptance_pickup
, GoodsEntry::GES_ACCEPTANCE
)) mask
|= 1 << i
;
408 * Items contains the two cargo names that are to be accepted or rejected.
409 * msg is the string id of the message to display.
411 static void ShowRejectOrAcceptNews(const Station
*st
, uint num_items
, CargoID
*cargo
, StringID msg
)
413 for (uint i
= 0; i
< num_items
; i
++) {
414 SetDParam(i
+ 1, CargoSpec::Get(cargo
[i
])->name
);
417 SetDParam(0, st
->index
);
418 AddNewsItem(msg
, NT_ACCEPTANCE
, NF_INCOLOUR
| NF_SMALL
, NR_STATION
, st
->index
);
422 * Get the cargo types being produced around the tile (in a rectangle).
423 * @param tile Northtile of area
424 * @param w X extent of the area
425 * @param h Y extent of the area
426 * @param rad Search radius in addition to the given area
428 CargoArray
GetProductionAroundTiles(TileIndex tile
, int w
, int h
, int rad
)
435 /* expand the region by rad tiles on each side
436 * while making sure that we remain inside the board. */
437 int x2
= min(x
+ w
+ rad
, MapSizeX());
438 int x1
= max(x
- rad
, 0);
440 int y2
= min(y
+ h
+ rad
, MapSizeY());
441 int y1
= max(y
- rad
, 0);
448 TileArea
ta(TileXY(x1
, y1
), TileXY(x2
- 1, y2
- 1));
450 /* Loop over all tiles to get the produced cargo of
451 * everything except industries */
452 TILE_AREA_LOOP(tile
, ta
) AddProducedCargo(tile
, produced
);
454 /* Loop over the industries. They produce cargo for
455 * anything that is within 'rad' from their bounding
456 * box. As such if you have e.g. a oil well the tile
457 * area loop might not hit an industry tile while
458 * the industry would produce cargo for the station.
461 FOR_ALL_INDUSTRIES(i
) {
462 if (!ta
.Intersects(i
->location
)) continue;
464 for (uint j
= 0; j
< lengthof(i
->produced_cargo
); j
++) {
465 CargoID cargo
= i
->produced_cargo
[j
];
466 if (cargo
!= CT_INVALID
) produced
[cargo
]++;
474 * Get the acceptance of cargoes around the tile in 1/8.
475 * @param tile Center of the search area
476 * @param w X extent of area
477 * @param h Y extent of area
478 * @param rad Search radius in addition to given area
479 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be NULL
481 CargoArray
GetAcceptanceAroundTiles(TileIndex tile
, int w
, int h
, int rad
, uint32
*always_accepted
)
483 CargoArray acceptance
;
484 if (always_accepted
!= NULL
) *always_accepted
= 0;
489 /* expand the region by rad tiles on each side
490 * while making sure that we remain inside the board. */
491 int x2
= min(x
+ w
+ rad
, MapSizeX());
492 int y2
= min(y
+ h
+ rad
, MapSizeY());
493 int x1
= max(x
- rad
, 0);
494 int y1
= max(y
- rad
, 0);
501 for (int yc
= y1
; yc
!= y2
; yc
++) {
502 for (int xc
= x1
; xc
!= x2
; xc
++) {
503 TileIndex tile
= TileXY(xc
, yc
);
504 AddAcceptedCargo(tile
, acceptance
, always_accepted
);
512 * Update the acceptance for a station.
513 * @param st Station to update
514 * @param show_msg controls whether to display a message that acceptance was changed.
516 void UpdateStationAcceptance(Station
*st
, bool show_msg
)
518 /* old accepted goods types */
519 uint old_acc
= GetAcceptanceMask(st
);
521 /* And retrieve the acceptance. */
522 CargoArray acceptance
;
523 if (!st
->rect
.IsEmpty()) {
524 acceptance
= GetAcceptanceAroundTiles(
525 TileXY(st
->rect
.left
, st
->rect
.top
),
526 st
->rect
.right
- st
->rect
.left
+ 1,
527 st
->rect
.bottom
- st
->rect
.top
+ 1,
528 st
->GetCatchmentRadius(),
533 /* Adjust in case our station only accepts fewer kinds of goods */
534 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
535 uint amt
= acceptance
[i
];
537 /* Make sure the station can accept the goods type. */
538 bool is_passengers
= IsCargoInClass(i
, CC_PASSENGERS
);
539 if ((!is_passengers
&& !(st
->facilities
& ~FACIL_BUS_STOP
)) ||
540 (is_passengers
&& !(st
->facilities
& ~FACIL_TRUCK_STOP
))) {
544 GoodsEntry
&ge
= st
->goods
[i
];
545 SB(ge
.acceptance_pickup
, GoodsEntry::GES_ACCEPTANCE
, 1, amt
>= 8);
546 if (LinkGraph::IsValidID(ge
.link_graph
)) {
547 (*LinkGraph::Get(ge
.link_graph
))[ge
.node
].SetDemand(amt
/ 8);
551 /* Only show a message in case the acceptance was actually changed. */
552 uint new_acc
= GetAcceptanceMask(st
);
553 if (old_acc
== new_acc
) return;
555 /* show a message to report that the acceptance was changed? */
556 if (show_msg
&& st
->owner
== _local_company
&& st
->IsInUse()) {
557 /* List of accept and reject strings for different number of
559 static const StringID accept_msg
[] = {
560 STR_NEWS_STATION_NOW_ACCEPTS_CARGO
,
561 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO
,
563 static const StringID reject_msg
[] = {
564 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO
,
565 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO
,
568 /* Array of accepted and rejected cargo types */
569 CargoID accepts
[2] = { CT_INVALID
, CT_INVALID
};
570 CargoID rejects
[2] = { CT_INVALID
, CT_INVALID
};
574 /* Test each cargo type to see if its acceptance has changed */
575 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
576 if (HasBit(new_acc
, i
)) {
577 if (!HasBit(old_acc
, i
) && num_acc
< lengthof(accepts
)) {
578 /* New cargo is accepted */
579 accepts
[num_acc
++] = i
;
582 if (HasBit(old_acc
, i
) && num_rej
< lengthof(rejects
)) {
583 /* Old cargo is no longer accepted */
584 rejects
[num_rej
++] = i
;
589 /* Show news message if there are any changes */
590 if (num_acc
> 0) ShowRejectOrAcceptNews(st
, num_acc
, accepts
, accept_msg
[num_acc
- 1]);
591 if (num_rej
> 0) ShowRejectOrAcceptNews(st
, num_rej
, rejects
, reject_msg
[num_rej
- 1]);
594 /* redraw the station view since acceptance changed */
595 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ACCEPT_RATING_LIST
);
598 static void UpdateStationSignCoord(BaseStation
*st
)
600 const StationRect
*r
= &st
->rect
;
602 if (r
->IsEmpty()) return; // no tiles belong to this station
604 /* clamp sign coord to be inside the station rect */
605 st
->xy
= TileXY(ClampU(TileX(st
->xy
), r
->left
, r
->right
), ClampU(TileY(st
->xy
), r
->top
, r
->bottom
));
606 st
->UpdateVirtCoord();
610 * Common part of building various station parts and possibly attaching them to an existing one.
611 * @param [in,out] st Station to attach to
612 * @param flags Command flags
613 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
614 * @param area Area occupied by the new part
615 * @param name_class Station naming class to use to generate the new station's name
616 * @return Command error that occured, if any
618 static CommandCost
BuildStationPart(Station
**st
, DoCommandFlag flags
, bool reuse
, TileArea area
, StationNaming name_class
)
620 /* Find a deleted station close to us */
621 if (*st
== NULL
&& reuse
) *st
= GetClosestDeletedStation(area
.tile
);
624 if ((*st
)->owner
!= _current_company
) {
625 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION
);
628 CommandCost ret
= (*st
)->rect
.BeforeAddRect(area
.tile
, area
.w
, area
.h
, StationRect::ADD_TEST
);
629 if (ret
.Failed()) return ret
;
631 /* allocate and initialize new station */
632 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING
);
634 if (flags
& DC_EXEC
) {
635 *st
= new Station(area
.tile
);
637 (*st
)->town
= ClosestTownFromTile(area
.tile
, UINT_MAX
);
638 (*st
)->string_id
= GenerateStationName(*st
, area
.tile
, name_class
);
640 if (Company::IsValidID(_current_company
)) {
641 SetBit((*st
)->town
->have_ratings
, _current_company
);
645 return CommandCost();
649 * This is called right after a station was deleted.
650 * It checks if the whole station is free of substations, and if so, the station will be
651 * deleted after a little while.
654 static void DeleteStationIfEmpty(BaseStation
*st
)
656 if (!st
->IsInUse()) {
658 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
660 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
661 UpdateStationSignCoord(st
);
664 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
);
667 * Checks if the given tile is buildable, flat and has a certain height.
668 * @param tile TileIndex to check.
669 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
670 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
671 * @param allow_steep Whether steep slopes are allowed.
672 * @param check_bridge Check for the existence of a bridge.
673 * @return The cost in case of success, or an error code if it failed.
675 CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
= true)
677 if (check_bridge
&& HasBridgeAbove(tile
)) {
678 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
681 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
682 if (ret
.Failed()) return ret
;
685 Slope tileh
= GetTileSlope(tile
, &z
);
687 /* Prohibit building if
688 * 1) The tile is "steep" (i.e. stretches two height levels).
689 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
691 if ((!allow_steep
&& IsSteepSlope(tileh
)) ||
692 ((!_settings_game
.construction
.build_on_slopes
) && tileh
!= SLOPE_FLAT
)) {
693 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
696 CommandCost
cost(EXPENSES_CONSTRUCTION
);
697 int flat_z
= z
+ GetSlopeMaxZ(tileh
);
698 if (tileh
!= SLOPE_FLAT
) {
699 /* Forbid building if the tile faces a slope in a invalid direction. */
700 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
!= DIAGDIR_END
; dir
++) {
701 if (HasBit(invalid_dirs
, dir
) && !CanBuildDepotByTileh(dir
, tileh
)) {
702 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
705 cost
.AddCost(_price
[PR_BUILD_FOUNDATION
]);
708 /* The level of this tile must be equal to allowed_z. */
712 } else if (allowed_z
!= flat_z
) {
713 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
720 * Tries to clear the given area.
721 * @param tile_area Area to check.
722 * @param flags Operation to perform.
723 * @return The cost in case of success, or an error code if it failed.
725 CommandCost
CheckFlatLand(TileArea tile_area
, DoCommandFlag flags
)
727 CommandCost
cost(EXPENSES_CONSTRUCTION
);
730 TILE_AREA_LOOP(tile_cur
, tile_area
) {
731 CommandCost ret
= CheckBuildableTile(tile_cur
, 0, allowed_z
, true);
732 if (ret
.Failed()) return ret
;
735 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
736 if (ret
.Failed()) return ret
;
744 * Checks if a rail station can be built at the given area.
745 * @param tile_area Area to check.
746 * @param flags Operation to perform.
747 * @param axis Rail station axis.
748 * @param station StationID to be queried and returned if available.
749 * @param rt The rail type to check for (overbuilding rail stations over rail).
750 * @param affected_vehicles List of trains with PBS reservations on the tiles
751 * @param spec_class Station class.
752 * @param spec_index Index into the station class.
753 * @param plat_len Platform length.
754 * @param numtracks Number of platforms.
755 * @return The cost in case of success, or an error code if it failed.
757 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
)
759 CommandCost
cost(EXPENSES_CONSTRUCTION
);
761 uint invalid_dirs
= 5 << axis
;
763 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
764 bool slope_cb
= statspec
!= NULL
&& HasBit(statspec
->callback_mask
, CBM_STATION_SLOPE_CHECK
);
766 TILE_AREA_LOOP(tile_cur
, tile_area
) {
767 CommandCost ret
= CheckBuildableTile(tile_cur
, invalid_dirs
, allowed_z
, false);
768 if (ret
.Failed()) return ret
;
772 /* Do slope check if requested. */
773 ret
= PerformStationTileSlopeCheck(tile_area
.tile
, tile_cur
, statspec
, axis
, plat_len
, numtracks
);
774 if (ret
.Failed()) return ret
;
777 /* if station is set, then we have special handling to allow building on top of already existing stations.
778 * so station points to INVALID_STATION if we can build on any station.
779 * Or it points to a station if we're only allowed to build on exactly that station. */
780 if (station
!= NULL
&& IsStationTile(tile_cur
)) {
781 if (!IsRailStation(tile_cur
)) {
782 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
784 StationID st
= GetStationIndex(tile_cur
);
785 if (*station
== INVALID_STATION
) {
787 } else if (*station
!= st
) {
788 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
792 /* Rail type is only valid when building a railway station; if station to
793 * build isn't a rail station it's INVALID_RAILTYPE. */
794 if (rt
!= INVALID_RAILTYPE
&& IsNormalRailTile(tile_cur
) &&
795 HasPowerOnRail(GetRailType(tile_cur
), rt
)) {
796 /* Allow overbuilding if the tile:
797 * - has rail, but no signals
798 * - it has exactly one track
799 * - the track is in line with the station
800 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
802 Track track
= AxisToTrack(axis
);
804 if (GetTrackBits(tile_cur
) == TrackToTrackBits(track
) && !HasSignalOnTrack(tile_cur
, track
)) {
805 /* Check for trains having a reservation for this tile. */
806 if (HasBit(GetRailReservationTrackBits(tile_cur
), track
)) {
807 Train
*v
= GetTrainForReservation(tile_cur
, track
);
809 *affected_vehicles
.Append() = v
;
812 CommandCost ret
= DoCommand(tile_cur
, 0, track
, flags
, CMD_REMOVE_SINGLE_RAIL
);
813 if (ret
.Failed()) return ret
;
815 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
819 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
820 if (ret
.Failed()) return ret
;
829 * Checks if a road stop can be built at the given tile.
830 * @param tile_area Area to check.
831 * @param flags Operation to perform.
832 * @param invalid_dirs Prohibited directions (set of DiagDirections).
833 * @param is_drive_through True if trying to build a drive-through station.
834 * @param is_truck_stop True when building a truck stop, false otherwise.
835 * @param axis Axis of a drive-through road stop.
836 * @param station StationID to be queried and returned if available.
837 * @param rts Road types to build.
838 * @return The cost in case of success, or an error code if it failed.
840 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
)
842 CommandCost
cost(EXPENSES_CONSTRUCTION
);
845 TILE_AREA_LOOP(cur_tile
, tile_area
) {
846 CommandCost ret
= CheckBuildableTile(cur_tile
, invalid_dirs
, allowed_z
, !is_drive_through
);
847 if (ret
.Failed()) return ret
;
850 /* If station is set, then we have special handling to allow building on top of already existing stations.
851 * Station points to INVALID_STATION if we can build on any station.
852 * Or it points to a station if we're only allowed to build on exactly that station. */
853 if (station
!= NULL
&& IsStationTile(cur_tile
)) {
854 if (!IsRoadStop(cur_tile
)) {
855 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
857 if (is_truck_stop
!= IsTruckStop(cur_tile
) ||
858 is_drive_through
!= IsDriveThroughStopTile(cur_tile
)) {
859 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
861 /* Drive-through station in the wrong direction. */
862 if (is_drive_through
&& IsDriveThroughStopTile(cur_tile
) && GetRoadStopAxis(cur_tile
) != axis
){
863 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
865 StationID st
= GetStationIndex(cur_tile
);
866 if (*station
== INVALID_STATION
) {
868 } else if (*station
!= st
) {
869 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
873 bool build_over_road
= is_drive_through
&& IsNormalRoadTile(cur_tile
);
874 /* Road bits in the wrong direction. */
875 RoadBits rb
= IsRoadTile(cur_tile
) ? GetAllRoadBits(cur_tile
) : ROAD_NONE
;
876 if (build_over_road
&& (rb
& (axis
== AXIS_X
? ROAD_Y
: ROAD_X
)) != 0) {
877 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
878 switch (CountBits(rb
)) {
880 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
883 if (rb
== ROAD_X
|| rb
== ROAD_Y
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
884 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER
);
887 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION
);
891 RoadTypes cur_rts
= IsRoadTile(cur_tile
) ? GetRoadTypes(cur_tile
) : ROADTYPES_NONE
;
892 uint num_roadbits
= 0;
893 if (build_over_road
) {
894 /* There is a road, check if we can build road+tram stop over it. */
895 if (HasBit(cur_rts
, ROADTYPE_ROAD
)) {
896 Owner road_owner
= GetRoadOwner(cur_tile
, ROADTYPE_ROAD
);
897 if (road_owner
== OWNER_TOWN
) {
898 if (!_settings_game
.construction
.road_stop_on_town_road
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD
);
899 } else if (!_settings_game
.construction
.road_stop_on_competitor_road
&& road_owner
!= OWNER_NONE
) {
900 CommandCost ret
= CheckOwnership(road_owner
);
901 if (ret
.Failed()) return ret
;
903 num_roadbits
+= CountBits(GetRoadBits(cur_tile
, ROADTYPE_ROAD
));
906 /* There is a tram, check if we can build road+tram stop over it. */
907 if (HasBit(cur_rts
, ROADTYPE_TRAM
)) {
908 Owner tram_owner
= GetRoadOwner(cur_tile
, ROADTYPE_TRAM
);
909 if (!_settings_game
.construction
.road_stop_on_competitor_road
&& tram_owner
!= OWNER_NONE
) {
910 CommandCost ret
= CheckOwnership(tram_owner
);
911 if (ret
.Failed()) return ret
;
913 num_roadbits
+= CountBits(GetRoadBits(cur_tile
, ROADTYPE_TRAM
));
916 /* Take into account existing roadbits. */
919 ret
= DoCommand(cur_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
920 if (ret
.Failed()) return ret
;
924 uint roadbits_to_build
= CountBits(rts
) * 2 - num_roadbits
;
925 cost
.AddCost(_price
[PR_BUILD_ROAD
] * roadbits_to_build
);
933 * Checks if an airport can be built at the given area.
934 * @param tile_area Area to check.
935 * @param flags Operation to perform.
936 * @param station StationID of airport allowed in search area.
937 * @return The cost in case of success, or an error code if it failed.
939 static CommandCost
CheckFlatLandAirport(TileArea tile_area
, DoCommandFlag flags
, StationID
*station
)
941 CommandCost
cost(EXPENSES_CONSTRUCTION
);
944 TILE_AREA_LOOP(tile_cur
, tile_area
) {
945 CommandCost ret
= CheckBuildableTile(tile_cur
, 0, allowed_z
, true);
946 if (ret
.Failed()) return ret
;
949 /* if station is set, then allow building on top of an already
950 * existing airport, either the one in *station if it is not
951 * INVALID_STATION, or anyone otherwise and store which one
953 if (station
!= NULL
&& IsStationTile(tile_cur
)) {
954 if (!IsAirport(tile_cur
)) {
955 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
957 StationID st
= GetStationIndex(tile_cur
);
958 if (*station
== INVALID_STATION
) {
960 } else if (*station
!= st
) {
961 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
965 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
966 if (ret
.Failed()) return ret
;
975 * Check whether we can expand the rail part of the given station.
976 * @param st the station to expand
977 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
978 * @param axis the axis of the newly build rail
979 * @return Succeeded or failed command.
981 CommandCost
CanExpandRailStation(const BaseStation
*st
, TileArea
&new_ta
, Axis axis
)
983 TileArea cur_ta
= st
->train_station
;
985 /* determine new size of train station region.. */
986 int x
= min(TileX(cur_ta
.tile
), TileX(new_ta
.tile
));
987 int y
= min(TileY(cur_ta
.tile
), TileY(new_ta
.tile
));
988 new_ta
.w
= max(TileX(cur_ta
.tile
) + cur_ta
.w
, TileX(new_ta
.tile
) + new_ta
.w
) - x
;
989 new_ta
.h
= max(TileY(cur_ta
.tile
) + cur_ta
.h
, TileY(new_ta
.tile
) + new_ta
.h
) - y
;
990 new_ta
.tile
= TileXY(x
, y
);
992 /* make sure the final size is not too big. */
993 if (new_ta
.w
> _settings_game
.station
.station_spread
|| new_ta
.h
> _settings_game
.station
.station_spread
) {
994 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
997 return CommandCost();
1000 static inline byte
*CreateSingle(byte
*layout
, int n
)
1003 do *layout
++ = 0; while (--i
);
1004 layout
[((n
- 1) >> 1) - n
] = 2;
1008 static inline byte
*CreateMulti(byte
*layout
, int n
, byte b
)
1011 do *layout
++ = b
; while (--i
);
1014 layout
[n
- 1 - n
] = 0;
1020 * Create the station layout for the given number of tracks and platform length.
1021 * @param layout The layout to write to.
1022 * @param numtracks The number of tracks to write.
1023 * @param plat_len The length of the platforms.
1024 * @param statspec The specification of the station to (possibly) get the layout from.
1026 void GetStationLayout(byte
*layout
, int numtracks
, int plat_len
, const StationSpec
*statspec
)
1028 if (statspec
!= NULL
&& statspec
->lengths
>= plat_len
&&
1029 statspec
->platforms
[plat_len
- 1] >= numtracks
&&
1030 statspec
->layouts
[plat_len
- 1][numtracks
- 1]) {
1031 /* Custom layout defined, follow it. */
1032 memcpy(layout
, statspec
->layouts
[plat_len
- 1][numtracks
- 1],
1033 plat_len
* numtracks
);
1037 if (plat_len
== 1) {
1038 CreateSingle(layout
, numtracks
);
1040 if (numtracks
& 1) layout
= CreateSingle(layout
, plat_len
);
1043 while (--numtracks
>= 0) {
1044 layout
= CreateMulti(layout
, plat_len
, 4);
1045 layout
= CreateMulti(layout
, plat_len
, 6);
1051 * Find a nearby station that joins this station.
1052 * @tparam T the class to find a station for
1053 * @param existing_station an existing station we build over
1054 * @param station_to_join the station to join to
1055 * @param adjacent whether adjacent stations are allowed
1056 * @param ta the area of the newly build station
1057 * @param st 'return' pointer for the found station
1058 * @param error_message the error message when building a station on top of others
1059 * @return command cost with the error or 'okay'
1062 CommandCost
FindJoiningBaseStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, T
**st
, StringID error_message
)
1064 assert(*st
== NULL
);
1066 bool check_surrounding
;
1067 if (!_settings_game
.station
.adjacent_stations
) {
1068 check_surrounding
= true;
1069 } else if (existing_station
== INVALID_STATION
) {
1070 /* There's no station here. Don't check the tiles surrounding this
1071 * one if the company wanted to build an adjacent station. */
1072 check_surrounding
= !adjacent
;
1073 } else if (adjacent
&& existing_station
!= station_to_join
) {
1074 /* You can't build an adjacent station over the top of one that
1075 * already exists. */
1076 return_cmd_error(error_message
);
1078 /* Extend the current station, and don't check whether it will
1079 * be near any other stations. */
1080 *st
= T::GetIfValid(existing_station
);
1081 check_surrounding
= (*st
== NULL
);
1084 if (check_surrounding
) {
1085 /* Make sure there are no similar stations around us. */
1086 ta
.tile
-= TileDiffXY(1, 1);
1090 /* check around to see if there are any stations there */
1091 TILE_AREA_LOOP(tile_cur
, ta
) {
1092 if (IsStationTile(tile_cur
)) {
1093 StationID t
= GetStationIndex(tile_cur
);
1094 if (!T::IsValidID(t
)) continue;
1096 if (existing_station
== INVALID_STATION
) {
1097 existing_station
= t
;
1098 } else if (existing_station
!= t
) {
1099 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
1104 *st
= (existing_station
== INVALID_STATION
) ? NULL
: T::Get(existing_station
);
1108 if (*st
== NULL
&& station_to_join
!= INVALID_STATION
) *st
= T::GetIfValid(station_to_join
);
1110 return CommandCost();
1114 * Find a nearby station that joins this station.
1115 * @param existing_station an existing station we build over
1116 * @param station_to_join the station to join to
1117 * @param adjacent whether adjacent stations are allowed
1118 * @param ta the area of the newly build station
1119 * @param st 'return' pointer for the found station
1120 * @param error_message the error message when building a station on top of others
1121 * @return command cost with the error or 'okay'
1123 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
)
1125 return FindJoiningBaseStation
<Station
>(existing_station
, station_to_join
, adjacent
, ta
, st
, error_message
);
1129 * Find a nearby waypoint that joins this waypoint.
1130 * @param existing_waypoint an existing waypoint we build over
1131 * @param waypoint_to_join the waypoint to join to
1132 * @param adjacent whether adjacent waypoints are allowed
1133 * @param ta the area of the newly build waypoint
1134 * @param wp 'return' pointer for the found waypoint
1135 * @return command cost with the error or 'okay'
1137 CommandCost
FindJoiningWaypoint(StationID existing_waypoint
, StationID waypoint_to_join
, bool adjacent
, TileArea ta
, Waypoint
**wp
)
1139 return FindJoiningBaseStation
<Waypoint
>(existing_waypoint
, waypoint_to_join
, adjacent
, ta
, wp
, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST
);
1142 static void FreeTrainReservation(Train
*v
)
1144 FreeTrainTrackReservation(v
);
1146 const PFPos pos
= v
->GetPos();
1147 if (!pos
.InWormhole() && IsRailStationTile(pos
.tile
)) SetRailStationPlatformReservation(pos
, false);
1149 const PFPos rev
= v
->Last()->GetReversePos();
1150 if (!rev
.InWormhole() && IsRailStationTile(rev
.tile
)) SetRailStationPlatformReservation(rev
, false);
1153 static void RestoreTrainReservation(Train
*v
)
1155 const PFPos pos
= v
->GetPos();
1156 if (!pos
.InWormhole() && IsRailStationTile(pos
.tile
)) SetRailStationPlatformReservation(pos
, true);
1158 TryPathReserve(v
, true, true);
1160 const PFPos rev
= v
->Last()->GetReversePos();
1161 if (!rev
.InWormhole() && IsRailStationTile(rev
.tile
)) SetRailStationPlatformReservation(rev
, true);
1165 * Build rail station
1166 * @param tile_org northern most position of station dragging/placement
1167 * @param flags operation to perform
1168 * @param p1 various bitstuffed elements
1169 * - p1 = (bit 0- 3) - railtype
1170 * - p1 = (bit 4) - orientation (Axis)
1171 * - p1 = (bit 8-15) - number of tracks
1172 * - p1 = (bit 16-23) - platform length
1173 * - p1 = (bit 24) - allow stations directly adjacent to other stations.
1174 * @param p2 various bitstuffed elements
1175 * - p2 = (bit 0- 7) - custom station class
1176 * - p2 = (bit 8-15) - custom station id
1177 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
1178 * @param text unused
1179 * @return the cost of this operation or an error
1181 CommandCost
CmdBuildRailStation(TileIndex tile_org
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1183 /* Unpack parameters */
1184 RailType rt
= Extract
<RailType
, 0, 4>(p1
);
1185 Axis axis
= Extract
<Axis
, 4, 1>(p1
);
1186 byte numtracks
= GB(p1
, 8, 8);
1187 byte plat_len
= GB(p1
, 16, 8);
1188 bool adjacent
= HasBit(p1
, 24);
1190 StationClassID spec_class
= Extract
<StationClassID
, 0, 8>(p2
);
1191 byte spec_index
= GB(p2
, 8, 8);
1192 StationID station_to_join
= GB(p2
, 16, 16);
1194 /* Does the authority allow this? */
1195 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile_org
, flags
);
1196 if (ret
.Failed()) return ret
;
1198 if (!ValParamRailtype(rt
)) return CMD_ERROR
;
1200 /* Check if the given station class is valid */
1201 if ((uint
)spec_class
>= StationClass::GetClassCount() || spec_class
== STAT_CLASS_WAYP
) return CMD_ERROR
;
1202 if (spec_index
>= StationClass::Get(spec_class
)->GetSpecCount()) return CMD_ERROR
;
1203 if (plat_len
== 0 || numtracks
== 0) return CMD_ERROR
;
1206 if (axis
== AXIS_X
) {
1214 bool reuse
= (station_to_join
!= NEW_STATION
);
1215 if (!reuse
) station_to_join
= INVALID_STATION
;
1216 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1218 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1220 if (h_org
> _settings_game
.station
.station_spread
|| w_org
> _settings_game
.station
.station_spread
) return CMD_ERROR
;
1222 /* these values are those that will be stored in train_tile and station_platforms */
1223 TileArea
new_location(tile_org
, w_org
, h_org
);
1225 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1226 StationID est
= INVALID_STATION
;
1227 SmallVector
<Train
*, 4> affected_vehicles
;
1228 /* Clear the land below the station. */
1229 CommandCost cost
= CheckFlatLandRailStation(new_location
, flags
, axis
, &est
, rt
, affected_vehicles
, spec_class
, spec_index
, plat_len
, numtracks
);
1230 if (cost
.Failed()) return cost
;
1231 /* Add construction expenses. */
1232 cost
.AddCost((numtracks
* _price
[PR_BUILD_STATION_RAIL
] + _price
[PR_BUILD_STATION_RAIL_LENGTH
]) * plat_len
);
1233 cost
.AddCost(numtracks
* plat_len
* RailBuildCost(rt
));
1236 ret
= FindJoiningStation(est
, station_to_join
, adjacent
, new_location
, &st
);
1237 if (ret
.Failed()) return ret
;
1239 ret
= BuildStationPart(&st
, flags
, reuse
, new_location
, STATIONNAMING_RAIL
);
1240 if (ret
.Failed()) return ret
;
1242 if (st
!= NULL
&& st
->train_station
.tile
!= INVALID_TILE
) {
1243 CommandCost ret
= CanExpandRailStation(st
, new_location
, axis
);
1244 if (ret
.Failed()) return ret
;
1247 /* Check if we can allocate a custom stationspec to this station */
1248 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
1249 int specindex
= AllocateSpecToStation(statspec
, st
, (flags
& DC_EXEC
) != 0);
1250 if (specindex
== -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS
);
1252 if (statspec
!= NULL
) {
1253 /* Perform NewStation checks */
1255 /* Check if the station size is permitted */
1256 if (HasBit(statspec
->disallowed_platforms
, numtracks
- 1) || HasBit(statspec
->disallowed_lengths
, plat_len
- 1)) {
1260 /* Check if the station is buildable */
1261 if (HasBit(statspec
->callback_mask
, CBM_STATION_AVAIL
)) {
1262 uint16 cb_res
= GetStationCallback(CBID_STATION_AVAILABILITY
, 0, 0, statspec
, NULL
, INVALID_TILE
);
1263 if (cb_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(statspec
->grf_prop
.grffile
, CBID_STATION_AVAILABILITY
, cb_res
)) return CMD_ERROR
;
1267 if (flags
& DC_EXEC
) {
1268 TileIndexDiff tile_delta
;
1270 byte numtracks_orig
;
1273 st
->train_station
= new_location
;
1274 st
->AddFacility(FACIL_TRAIN
, new_location
.tile
);
1276 st
->rect
.BeforeAddRect(tile_org
, w_org
, h_org
, StationRect::ADD_TRY
);
1278 if (statspec
!= NULL
) {
1279 /* Include this station spec's animation trigger bitmask
1280 * in the station's cached copy. */
1281 st
->cached_anim_triggers
|= statspec
->animation
.triggers
;
1284 tile_delta
= (axis
== AXIS_X
? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1285 track
= AxisToTrack(axis
);
1287 layout_ptr
= AllocaM(byte
, numtracks
* plat_len
);
1288 GetStationLayout(layout_ptr
, numtracks
, plat_len
, statspec
);
1290 numtracks_orig
= numtracks
;
1292 Company
*c
= Company::Get(st
->owner
);
1293 TileIndex tile_track
= tile_org
;
1295 TileIndex tile
= tile_track
;
1298 byte layout
= *layout_ptr
++;
1299 if (IsRailStationTile(tile
) && HasStationReservation(tile
)) {
1300 /* Check for trains having a reservation for this tile. */
1301 Train
*v
= GetTrainForReservation(tile
, AxisToTrack(GetRailStationAxis(tile
)));
1303 *affected_vehicles
.Append() = v
;
1304 FreeTrainReservation(v
);
1308 /* Railtype can change when overbuilding. */
1309 if (IsRailStationTile(tile
)) {
1310 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[GetRailType(tile
)]--;
1311 c
->infrastructure
.station
--;
1314 /* Remove animation if overbuilding */
1315 DeleteAnimatedTile(tile
);
1316 byte old_specindex
= HasStationTileRail(tile
) ? GetCustomStationSpecIndex(tile
) : 0;
1317 MakeRailStation(tile
, st
->owner
, st
->index
, axis
, layout
& ~1, rt
);
1318 /* Free the spec if we overbuild something */
1319 DeallocateSpecFromStation(st
, old_specindex
);
1321 SetCustomStationSpecIndex(tile
, specindex
);
1322 SetStationTileRandomBits(tile
, GB(Random(), 0, 4));
1323 SetAnimationFrame(tile
, 0);
1325 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[rt
]++;
1326 c
->infrastructure
.station
++;
1328 if (statspec
!= NULL
) {
1329 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1330 uint32 platinfo
= GetPlatformInfo(AXIS_X
, GetStationGfx(tile
), plat_len
, numtracks_orig
, plat_len
- w
, numtracks_orig
- numtracks
, false);
1332 /* As the station is not yet completely finished, the station does not yet exist. */
1333 uint16 callback
= GetStationCallback(CBID_STATION_TILE_LAYOUT
, platinfo
, 0, statspec
, NULL
, tile
);
1334 if (callback
!= CALLBACK_FAILED
) {
1336 SetStationGfx(tile
, (callback
& ~1) + axis
);
1338 ErrorUnknownCallbackResult(statspec
->grf_prop
.grffile
->grfid
, CBID_STATION_TILE_LAYOUT
, callback
);
1342 /* Trigger station animation -- after building? */
1343 TriggerStationAnimation(st
, tile
, SAT_BUILT
);
1348 AddTrackToSignalBuffer(tile_track
, track
, _current_company
);
1349 YapfNotifyTrackLayoutChange(tile_track
, track
);
1350 tile_track
+= tile_delta
^ TileDiffXY(1, 1); // perpendicular to tile_delta
1351 } while (--numtracks
);
1353 for (uint i
= 0; i
< affected_vehicles
.Length(); ++i
) {
1354 RestoreTrainReservation(affected_vehicles
[i
]);
1357 /* Check whether we need to expand the reservation of trains already on the station. */
1358 TileArea update_reservation_area
;
1359 if (axis
== AXIS_X
) {
1360 update_reservation_area
= TileArea(tile_org
, 1, numtracks_orig
);
1362 update_reservation_area
= TileArea(tile_org
, numtracks_orig
, 1);
1365 TILE_AREA_LOOP(tile
, update_reservation_area
) {
1366 /* Don't even try to make eye candy parts reserved. */
1367 if (IsStationTileBlocked(tile
)) continue;
1369 DiagDirection dir
= AxisToDiagDir(axis
);
1370 TileIndexDiff tile_offset
= TileOffsByDiagDir(dir
);
1371 TileIndex platform_begin
= tile
;
1372 TileIndex platform_end
= tile
;
1374 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1375 for (TileIndex next_tile
= platform_begin
- tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_begin
); next_tile
-= tile_offset
) {
1376 platform_begin
= next_tile
;
1378 for (TileIndex next_tile
= platform_end
+ tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_end
); next_tile
+= tile_offset
) {
1379 platform_end
= next_tile
;
1382 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1383 bool reservation
= false;
1384 for (TileIndex t
= platform_begin
; !reservation
&& t
<= platform_end
; t
+= tile_offset
) {
1385 reservation
= HasStationReservation(t
);
1389 SetRailStationPlatformReservation(platform_begin
, dir
, true);
1393 st
->MarkTilesDirty(false);
1394 st
->UpdateVirtCoord();
1395 UpdateStationAcceptance(st
, false);
1396 st
->RecomputeIndustriesNear();
1397 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
1398 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
1399 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1400 DirtyCompanyInfrastructureWindows(st
->owner
);
1406 static void MakeRailStationAreaSmaller(BaseStation
*st
)
1408 TileArea ta
= st
->train_station
;
1413 if (ta
.w
!= 0 && ta
.h
!= 0) {
1414 /* check the left side, x = constant, y changes */
1415 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(0, i
));) {
1416 /* the left side is unused? */
1418 ta
.tile
+= TileDiffXY(1, 0);
1424 /* check the right side, x = constant, y changes */
1425 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(ta
.w
- 1, i
));) {
1426 /* the right side is unused? */
1433 /* check the upper side, y = constant, x changes */
1434 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(i
, 0));) {
1435 /* the left side is unused? */
1437 ta
.tile
+= TileDiffXY(0, 1);
1443 /* check the lower side, y = constant, x changes */
1444 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(i
, ta
.h
- 1));) {
1445 /* the left side is unused? */
1455 st
->train_station
= ta
;
1459 * Remove a number of tiles from any rail station within the area.
1460 * @param ta the area to clear station tile from.
1461 * @param affected_stations the stations affected.
1462 * @param flags the command flags.
1463 * @param removal_cost the cost for removing the tile, including the rail.
1464 * @param keep_rail whether to keep the rail of the station.
1465 * @tparam T the type of station to remove.
1466 * @return the number of cleared tiles or an error.
1469 CommandCost
RemoveFromRailBaseStation(TileArea ta
, SmallVector
<T
*, 4> &affected_stations
, DoCommandFlag flags
, Money removal_cost
, bool keep_rail
)
1471 /* Count of the number of tiles removed */
1473 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
1474 /* Accumulator for the errors seen during clearing. If no errors happen,
1475 * and the quantity is 0 there is no station. Otherwise it will be one
1476 * of the other error that got accumulated. */
1479 /* Do the action for every tile into the area */
1480 TILE_AREA_LOOP(tile
, ta
) {
1481 /* Make sure the specified tile is a rail station */
1482 if (!HasStationTileRail(tile
)) continue;
1484 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1485 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1487 if (ret
.Failed()) continue;
1489 /* Check ownership of station */
1490 T
*st
= T::GetByTile(tile
);
1491 if (st
== NULL
) continue;
1493 if (_current_company
!= OWNER_WATER
) {
1494 CommandCost ret
= CheckOwnership(st
->owner
);
1496 if (ret
.Failed()) continue;
1499 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1502 if (keep_rail
|| IsStationTileBlocked(tile
)) {
1503 /* Don't refund the 'steel' of the track when we keep the
1504 * rail, or when the tile didn't have any rail at all. */
1505 total_cost
.AddCost(-_price
[PR_CLEAR_RAIL
]);
1508 if (flags
& DC_EXEC
) {
1509 /* read variables before the station tile is removed */
1510 uint specindex
= GetCustomStationSpecIndex(tile
);
1511 Track track
= GetRailStationTrack(tile
);
1512 Owner owner
= GetTileOwner(tile
);
1513 RailType rt
= GetRailType(tile
);
1516 if (HasStationReservation(tile
)) {
1517 v
= GetTrainForReservation(tile
, track
);
1518 if (v
!= NULL
) FreeTrainReservation(v
);
1521 bool build_rail
= keep_rail
&& !IsStationTileBlocked(tile
);
1522 if (!build_rail
&& !IsStationTileBlocked(tile
)) Company::Get(owner
)->infrastructure
.rail
[rt
]--;
1524 DoClearSquare(tile
);
1525 DeleteNewGRFInspectWindow(GSF_STATIONS
, tile
);
1526 if (build_rail
) MakeRailNormal(tile
, owner
, TrackToTrackBits(track
), rt
);
1527 Company::Get(owner
)->infrastructure
.station
--;
1528 DirtyCompanyInfrastructureWindows(owner
);
1530 st
->rect
.AfterRemoveTile(st
, tile
);
1531 AddTrackToSignalBuffer(tile
, track
, owner
);
1532 YapfNotifyTrackLayoutChange(tile
, track
);
1534 DeallocateSpecFromStation(st
, specindex
);
1536 affected_stations
.Include(st
);
1538 if (v
!= NULL
) RestoreTrainReservation(v
);
1542 if (quantity
== 0) return error
.Failed() ? error
: CommandCost(STR_ERROR_THERE_IS_NO_STATION
);
1544 for (T
**stp
= affected_stations
.Begin(); stp
!= affected_stations
.End(); stp
++) {
1547 /* now we need to make the "spanned" area of the railway station smaller
1548 * if we deleted something at the edges.
1549 * we also need to adjust train_tile. */
1550 MakeRailStationAreaSmaller(st
);
1551 UpdateStationSignCoord(st
);
1553 /* if we deleted the whole station, delete the train facility. */
1554 if (st
->train_station
.tile
== INVALID_TILE
) {
1555 st
->facilities
&= ~FACIL_TRAIN
;
1556 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1557 st
->UpdateVirtCoord();
1558 DeleteStationIfEmpty(st
);
1562 total_cost
.AddCost(quantity
* removal_cost
);
1567 * Remove a single tile from a rail station.
1568 * This allows for custom-built station with holes and weird layouts
1569 * @param start tile of station piece to remove
1570 * @param flags operation to perform
1571 * @param p1 start_tile
1572 * @param p2 various bitstuffed elements
1573 * - p2 = bit 0 - if set keep the rail
1574 * @param text unused
1575 * @return the cost of this operation or an error
1577 CommandCost
CmdRemoveFromRailStation(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1579 TileIndex end
= p1
== 0 ? start
: p1
;
1580 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1582 TileArea
ta(start
, end
);
1583 SmallVector
<Station
*, 4> affected_stations
;
1585 CommandCost ret
= RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_STATION_RAIL
], HasBit(p2
, 0));
1586 if (ret
.Failed()) return ret
;
1588 /* Do all station specific functions here. */
1589 for (Station
**stp
= affected_stations
.Begin(); stp
!= affected_stations
.End(); stp
++) {
1592 if (st
->train_station
.tile
== INVALID_TILE
) SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1593 st
->MarkTilesDirty(false);
1594 st
->RecomputeIndustriesNear();
1597 /* Now apply the rail cost to the number that we deleted */
1602 * Remove a single tile from a waypoint.
1603 * This allows for custom-built waypoint with holes and weird layouts
1604 * @param start tile of waypoint piece to remove
1605 * @param flags operation to perform
1606 * @param p1 start_tile
1607 * @param p2 various bitstuffed elements
1608 * - p2 = bit 0 - if set keep the rail
1609 * @param text unused
1610 * @return the cost of this operation or an error
1612 CommandCost
CmdRemoveFromRailWaypoint(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1614 TileIndex end
= p1
== 0 ? start
: p1
;
1615 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1617 TileArea
ta(start
, end
);
1618 SmallVector
<Waypoint
*, 4> affected_stations
;
1620 return RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
], HasBit(p2
, 0));
1625 * Remove a rail station/waypoint
1626 * @param st The station/waypoint to remove the rail part from
1627 * @param flags operation to perform
1628 * @tparam T the type of station to remove
1629 * @return cost or failure of operation
1632 CommandCost
RemoveRailStation(T
*st
, DoCommandFlag flags
)
1634 /* Current company owns the station? */
1635 if (_current_company
!= OWNER_WATER
) {
1636 CommandCost ret
= CheckOwnership(st
->owner
);
1637 if (ret
.Failed()) return ret
;
1640 /* determine width and height of platforms */
1641 TileArea ta
= st
->train_station
;
1643 assert(ta
.w
!= 0 && ta
.h
!= 0);
1645 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1646 /* clear all areas of the station */
1647 TILE_AREA_LOOP(tile
, ta
) {
1648 /* only remove tiles that are actually train station tiles */
1649 if (!st
->TileBelongsToRailStation(tile
)) continue;
1651 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1652 if (ret
.Failed()) return ret
;
1654 cost
.AddCost(_price
[PR_CLEAR_STATION_RAIL
]);
1655 if (flags
& DC_EXEC
) {
1656 /* read variables before the station tile is removed */
1657 Track track
= GetRailStationTrack(tile
);
1658 Owner owner
= GetTileOwner(tile
); // _current_company can be OWNER_WATER
1660 if (HasStationReservation(tile
)) {
1661 v
= GetTrainForReservation(tile
, track
);
1662 if (v
!= NULL
) FreeTrainTrackReservation(v
);
1664 if (!IsStationTileBlocked(tile
)) Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)]--;
1665 Company::Get(owner
)->infrastructure
.station
--;
1666 DoClearSquare(tile
);
1667 DeleteNewGRFInspectWindow(GSF_STATIONS
, tile
);
1668 AddTrackToSignalBuffer(tile
, track
, owner
);
1669 YapfNotifyTrackLayoutChange(tile
, track
);
1670 if (v
!= NULL
) TryPathReserve(v
, true);
1674 if (flags
& DC_EXEC
) {
1675 st
->rect
.AfterRemoveRect(st
, st
->train_station
);
1677 st
->train_station
.Clear();
1679 st
->facilities
&= ~FACIL_TRAIN
;
1683 st
->speclist
= NULL
;
1684 st
->cached_anim_triggers
= 0;
1686 DirtyCompanyInfrastructureWindows(st
->owner
);
1687 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1688 st
->UpdateVirtCoord();
1689 DeleteStationIfEmpty(st
);
1696 * Remove a rail station
1697 * @param tile Tile of the station.
1698 * @param flags operation to perform
1699 * @return cost or failure of operation
1701 static CommandCost
RemoveRailStation(TileIndex tile
, DoCommandFlag flags
)
1703 /* if there is flooding, remove platforms tile by tile */
1704 if (_current_company
== OWNER_WATER
) {
1705 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_STATION
);
1708 Station
*st
= Station::GetByTile(tile
);
1709 CommandCost cost
= RemoveRailStation(st
, flags
);
1711 if (flags
& DC_EXEC
) st
->RecomputeIndustriesNear();
1717 * Remove a rail waypoint
1718 * @param tile Tile of the waypoint.
1719 * @param flags operation to perform
1720 * @return cost or failure of operation
1722 static CommandCost
RemoveRailWaypoint(TileIndex tile
, DoCommandFlag flags
)
1724 /* if there is flooding, remove waypoints tile by tile */
1725 if (_current_company
== OWNER_WATER
) {
1726 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_WAYPOINT
);
1729 return RemoveRailStation(Waypoint::GetByTile(tile
), flags
);
1734 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1735 * @param st The Station to do the whole procedure for
1736 * @return a pointer to where to link a new RoadStop*
1738 static RoadStop
**FindRoadStopSpot(bool truck_station
, Station
*st
)
1740 RoadStop
**primary_stop
= (truck_station
) ? &st
->truck_stops
: &st
->bus_stops
;
1742 if (*primary_stop
== NULL
) {
1743 /* we have no roadstop of the type yet, so write a "primary stop" */
1744 return primary_stop
;
1746 /* there are stops already, so append to the end of the list */
1747 RoadStop
*stop
= *primary_stop
;
1748 while (stop
->next
!= NULL
) stop
= stop
->next
;
1753 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
);
1756 * Build a bus or truck stop.
1757 * @param tile Northernmost tile of the stop.
1758 * @param flags Operation to perform.
1759 * @param p1 bit 0..7: Width of the road stop.
1760 * bit 8..15: Length of the road stop.
1761 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1762 * bit 1: 0 For normal stops, 1 for drive-through.
1763 * bit 2..3: The roadtypes.
1764 * bit 5: Allow stations directly adjacent to other stations.
1765 * bit 6..7: Entrance direction (#DiagDirection).
1766 * bit 16..31: Station ID to join (NEW_STATION if build new one).
1767 * @param text Unused.
1768 * @return The cost of this operation or an error.
1770 CommandCost
CmdBuildRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1772 bool type
= HasBit(p2
, 0);
1773 bool is_drive_through
= HasBit(p2
, 1);
1774 RoadTypes rts
= Extract
<RoadTypes
, 2, 2>(p2
);
1775 StationID station_to_join
= GB(p2
, 16, 16);
1776 bool reuse
= (station_to_join
!= NEW_STATION
);
1777 if (!reuse
) station_to_join
= INVALID_STATION
;
1778 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1780 uint8 width
= (uint8
)GB(p1
, 0, 8);
1781 uint8 lenght
= (uint8
)GB(p1
, 8, 8);
1783 /* Check if the requested road stop is too big */
1784 if (width
> _settings_game
.station
.station_spread
|| lenght
> _settings_game
.station
.station_spread
) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1785 /* Check for incorrect width / length. */
1786 if (width
== 0 || lenght
== 0) return CMD_ERROR
;
1787 /* Check if the first tile and the last tile are valid */
1788 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, lenght
- 1) == INVALID_TILE
) return CMD_ERROR
;
1790 TileArea
roadstop_area(tile
, width
, lenght
);
1792 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1794 if (!HasExactlyOneBit(rts
) || !HasRoadTypesAvail(_current_company
, rts
)) return CMD_ERROR
;
1796 /* Trams only have drive through stops */
1797 if (!is_drive_through
&& HasBit(rts
, ROADTYPE_TRAM
)) return CMD_ERROR
;
1799 DiagDirection ddir
= Extract
<DiagDirection
, 6, 2>(p2
);
1801 /* Safeguard the parameters. */
1802 if (!IsValidDiagDirection(ddir
)) return CMD_ERROR
;
1803 /* If it is a drive-through stop, check for valid axis. */
1804 if (is_drive_through
&& !IsValidAxis((Axis
)ddir
)) return CMD_ERROR
;
1806 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
1807 if (ret
.Failed()) return ret
;
1809 /* Total road stop cost. */
1810 CommandCost
cost(EXPENSES_CONSTRUCTION
, roadstop_area
.w
* roadstop_area
.h
* _price
[type
? PR_BUILD_STATION_TRUCK
: PR_BUILD_STATION_BUS
]);
1811 StationID est
= INVALID_STATION
;
1812 ret
= CheckFlatLandRoadStop(roadstop_area
, flags
, is_drive_through
? 5 << ddir
: 1 << ddir
, is_drive_through
, type
, DiagDirToAxis(ddir
), &est
, rts
);
1813 if (ret
.Failed()) return ret
;
1817 ret
= FindJoiningStation(est
, station_to_join
, HasBit(p2
, 5), roadstop_area
, &st
, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST
);
1818 if (ret
.Failed()) return ret
;
1820 /* Check if this number of road stops can be allocated. */
1821 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
);
1823 ret
= BuildStationPart(&st
, flags
, reuse
, roadstop_area
, STATIONNAMING_ROAD
);
1824 if (ret
.Failed()) return ret
;
1826 if (flags
& DC_EXEC
) {
1827 /* Check every tile in the area. */
1828 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
1829 RoadTypes cur_rts
= (IsRoadTile(cur_tile
) || IsStationTile(cur_tile
)) ? GetRoadTypes(cur_tile
) : ROADTYPES_NONE
;
1830 Owner road_owner
= HasBit(cur_rts
, ROADTYPE_ROAD
) ? GetRoadOwner(cur_tile
, ROADTYPE_ROAD
) : _current_company
;
1831 Owner tram_owner
= HasBit(cur_rts
, ROADTYPE_TRAM
) ? GetRoadOwner(cur_tile
, ROADTYPE_TRAM
) : _current_company
;
1833 if (IsStationTile(cur_tile
) && IsRoadStop(cur_tile
)) {
1834 RemoveRoadStop(cur_tile
, flags
);
1837 RoadStop
*road_stop
= new RoadStop(cur_tile
);
1838 /* Insert into linked list of RoadStops. */
1839 RoadStop
**currstop
= FindRoadStopSpot(type
, st
);
1840 *currstop
= road_stop
;
1843 st
->truck_station
.Add(cur_tile
);
1845 st
->bus_station
.Add(cur_tile
);
1848 /* Initialize an empty station. */
1849 st
->AddFacility((type
) ? FACIL_TRUCK_STOP
: FACIL_BUS_STOP
, cur_tile
);
1851 st
->rect
.BeforeAddTile(cur_tile
, StationRect::ADD_TRY
);
1853 RoadStopType rs_type
= type
? ROADSTOP_TRUCK
: ROADSTOP_BUS
;
1854 if (is_drive_through
) {
1855 /* Update company infrastructure counts. If the current tile is a normal
1856 * road tile, count only the new road bits needed to get a full diagonal road. */
1858 FOR_EACH_SET_ROADTYPE(rt
, cur_rts
| rts
) {
1859 Company
*c
= Company::GetIfValid(rt
== ROADTYPE_ROAD
? road_owner
: tram_owner
);
1861 c
->infrastructure
.road
[rt
] += 2 - (IsRoadTile(cur_tile
) && HasBit(cur_rts
, rt
) ? CountBits(GetRoadBits(cur_tile
, rt
)) : 0);
1862 DirtyCompanyInfrastructureWindows(c
->index
);
1866 MakeDriveThroughRoadStop(cur_tile
, st
->owner
, road_owner
, tram_owner
, st
->index
, rs_type
, rts
| cur_rts
, DiagDirToAxis(ddir
));
1867 road_stop
->MakeDriveThrough();
1869 /* Non-drive-through stop never overbuild and always count as two road bits. */
1870 Company::Get(st
->owner
)->infrastructure
.road
[FIND_FIRST_BIT(rts
)] += 2;
1871 MakeRoadStop(cur_tile
, st
->owner
, st
->index
, rs_type
, rts
, ddir
);
1873 Company::Get(st
->owner
)->infrastructure
.station
++;
1874 DirtyCompanyInfrastructureWindows(st
->owner
);
1876 MarkTileDirtyByTile(cur_tile
);
1881 st
->UpdateVirtCoord();
1882 UpdateStationAcceptance(st
, false);
1883 st
->RecomputeIndustriesNear();
1884 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
1885 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
1886 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ROADVEHS
);
1892 static Vehicle
*ClearRoadStopStatusEnum(Vehicle
*v
, void *)
1894 if (v
->type
== VEH_ROAD
) {
1895 /* Okay... we are a road vehicle on a drive through road stop.
1896 * But that road stop has just been removed, so we need to make
1897 * sure we are in a valid state... however, vehicles can also
1898 * turn on road stop tiles, so only clear the 'road stop' state
1899 * bits and only when the state was 'in road stop', otherwise
1900 * we'll end up clearing the turn around bits. */
1901 RoadVehicle
*rv
= RoadVehicle::From(v
);
1902 if (HasBit(rv
->state
, RVS_IN_DT_ROAD_STOP
)) rv
->state
&= RVSB_ROAD_STOP_TRACKDIR_MASK
;
1910 * Remove a bus station/truck stop
1911 * @param tile TileIndex been queried
1912 * @param flags operation to perform
1913 * @return cost or failure of operation
1915 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
)
1917 Station
*st
= Station::GetByTile(tile
);
1919 if (_current_company
!= OWNER_WATER
) {
1920 CommandCost ret
= CheckOwnership(st
->owner
);
1921 if (ret
.Failed()) return ret
;
1924 bool is_truck
= IsTruckStop(tile
);
1926 RoadStop
**primary_stop
;
1928 if (is_truck
) { // truck stop
1929 primary_stop
= &st
->truck_stops
;
1930 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_TRUCK
);
1932 primary_stop
= &st
->bus_stops
;
1933 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_BUS
);
1936 assert(cur_stop
!= NULL
);
1938 /* don't do the check for drive-through road stops when company bankrupts */
1939 if (IsDriveThroughStopTile(tile
) && (flags
& DC_BANKRUPT
)) {
1940 /* remove the 'going through road stop' status from all vehicles on that tile */
1941 if (flags
& DC_EXEC
) FindVehicleOnPos(tile
, NULL
, &ClearRoadStopStatusEnum
);
1943 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1944 if (ret
.Failed()) return ret
;
1947 if (flags
& DC_EXEC
) {
1948 if (*primary_stop
== cur_stop
) {
1949 /* removed the first stop in the list */
1950 *primary_stop
= cur_stop
->next
;
1951 /* removed the only stop? */
1952 if (*primary_stop
== NULL
) {
1953 st
->facilities
&= (is_truck
? ~FACIL_TRUCK_STOP
: ~FACIL_BUS_STOP
);
1956 /* tell the predecessor in the list to skip this stop */
1957 RoadStop
*pred
= *primary_stop
;
1958 while (pred
->next
!= cur_stop
) pred
= pred
->next
;
1959 pred
->next
= cur_stop
->next
;
1962 /* Update company infrastructure counts. */
1964 FOR_EACH_SET_ROADTYPE(rt
, GetRoadTypes(tile
)) {
1965 Company
*c
= Company::GetIfValid(GetRoadOwner(tile
, rt
));
1967 c
->infrastructure
.road
[rt
] -= 2;
1968 DirtyCompanyInfrastructureWindows(c
->index
);
1971 Company::Get(st
->owner
)->infrastructure
.station
--;
1973 if (IsDriveThroughStopTile(tile
)) {
1974 /* Clears the tile for us */
1975 cur_stop
->ClearDriveThrough();
1977 DoClearSquare(tile
);
1980 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ROADVEHS
);
1983 /* Make sure no vehicle is going to the old roadstop */
1985 FOR_ALL_ROADVEHICLES(v
) {
1986 if (v
->First() == v
&& v
->current_order
.IsType(OT_GOTO_STATION
) &&
1987 v
->dest_tile
== tile
) {
1988 v
->dest_tile
= v
->GetOrderStationLocation(st
->index
);
1992 st
->rect
.AfterRemoveTile(st
, tile
);
1994 st
->UpdateVirtCoord();
1995 st
->RecomputeIndustriesNear();
1996 DeleteStationIfEmpty(st
);
1998 /* Update the tile area of the truck/bus stop */
2000 st
->truck_station
.Clear();
2001 for (const RoadStop
*rs
= st
->truck_stops
; rs
!= NULL
; rs
= rs
->next
) st
->truck_station
.Add(rs
->xy
);
2003 st
->bus_station
.Clear();
2004 for (const RoadStop
*rs
= st
->bus_stops
; rs
!= NULL
; rs
= rs
->next
) st
->bus_station
.Add(rs
->xy
);
2008 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[is_truck
? PR_CLEAR_STATION_TRUCK
: PR_CLEAR_STATION_BUS
]);
2012 * Remove bus or truck stops.
2013 * @param tile Northernmost tile of the removal area.
2014 * @param flags Operation to perform.
2015 * @param p1 bit 0..7: Width of the removal area.
2016 * bit 8..15: Height of the removal area.
2017 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
2018 * @param text Unused.
2019 * @return The cost of this operation or an error.
2021 CommandCost
CmdRemoveRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2023 uint8 width
= (uint8
)GB(p1
, 0, 8);
2024 uint8 height
= (uint8
)GB(p1
, 8, 8);
2026 /* Check for incorrect width / height. */
2027 if (width
== 0 || height
== 0) return CMD_ERROR
;
2028 /* Check if the first tile and the last tile are valid */
2029 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, height
- 1) == INVALID_TILE
) return CMD_ERROR
;
2031 TileArea
roadstop_area(tile
, width
, height
);
2034 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2035 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
2036 /* Make sure the specified tile is a road stop of the correct type */
2037 if (!IsStationTile(cur_tile
) || !IsRoadStop(cur_tile
) || (uint32
)GetRoadStopType(cur_tile
) != GB(p2
, 0, 1)) continue;
2039 /* Save the stop info before it is removed */
2040 bool is_drive_through
= IsDriveThroughStopTile(cur_tile
);
2041 RoadTypes rts
= GetRoadTypes(cur_tile
);
2042 RoadBits road_bits
= IsDriveThroughStopTile(cur_tile
) ?
2043 AxisToRoadBits(GetRoadStopAxis(cur_tile
)) :
2044 DiagDirToRoadBits(GetRoadStopDir(cur_tile
));
2046 Owner road_owner
= GetRoadOwner(cur_tile
, ROADTYPE_ROAD
);
2047 Owner tram_owner
= GetRoadOwner(cur_tile
, ROADTYPE_TRAM
);
2048 CommandCost ret
= RemoveRoadStop(cur_tile
, flags
);
2049 if (ret
.Failed()) return ret
;
2053 /* If the stop was a drive-through stop replace the road */
2054 if ((flags
& DC_EXEC
) && is_drive_through
) {
2055 MakeRoadNormal(cur_tile
, road_bits
, rts
, ClosestTownFromTile(cur_tile
, UINT_MAX
)->index
,
2056 road_owner
, tram_owner
);
2058 /* Update company infrastructure counts. */
2060 FOR_EACH_SET_ROADTYPE(rt
, rts
) {
2061 Company
*c
= Company::GetIfValid(GetRoadOwner(cur_tile
, rt
));
2063 c
->infrastructure
.road
[rt
] += CountBits(road_bits
);
2064 DirtyCompanyInfrastructureWindows(c
->index
);
2070 if (quantity
== 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION
);
2076 * Computes the minimal distance from town's xy to any airport's tile.
2077 * @param it An iterator over all airport tiles.
2078 * @param town_tile town's tile (t->xy)
2079 * @return minimal manhattan distance from town_tile to any airport's tile
2081 static uint
GetMinimalAirportDistanceToTile(TileIterator
&it
, TileIndex town_tile
)
2083 uint mindist
= UINT_MAX
;
2085 for (TileIndex cur_tile
= it
; cur_tile
!= INVALID_TILE
; cur_tile
= ++it
) {
2086 mindist
= min(mindist
, DistanceManhattan(town_tile
, cur_tile
));
2093 * Get a possible noise reduction factor based on distance from town center.
2094 * The further you get, the less noise you generate.
2095 * So all those folks at city council can now happily slee... work in their offices
2096 * @param as airport information
2097 * @param it An iterator over all airport tiles.
2098 * @param town_tile TileIndex of town's center, the one who will receive the airport's candidature
2099 * @return the noise that will be generated, according to distance
2101 uint8
GetAirportNoiseLevelForTown(const AirportSpec
*as
, TileIterator
&it
, TileIndex town_tile
)
2103 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2104 * So no need to go any further*/
2105 if (as
->noise_level
< 2) return as
->noise_level
;
2107 uint distance
= GetMinimalAirportDistanceToTile(it
, town_tile
);
2109 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2110 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2111 * Basically, it says that the less tolerant a town is, the bigger the distance before
2112 * an actual decrease can be granted */
2113 uint8 town_tolerance_distance
= 8 + (_settings_game
.difficulty
.town_council_tolerance
* 4);
2115 /* now, we want to have the distance segmented using the distance judged bareable by town
2116 * This will give us the coefficient of reduction the distance provides. */
2117 uint noise_reduction
= distance
/ town_tolerance_distance
;
2119 /* If the noise reduction equals the airport noise itself, don't give it for free.
2120 * Otherwise, simply reduce the airport's level. */
2121 return noise_reduction
>= as
->noise_level
? 1 : as
->noise_level
- noise_reduction
;
2125 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2126 * If two towns have the same distance, town with lower index is returned.
2127 * @param as airport's description
2128 * @param it An iterator over all airport tiles
2129 * @return nearest town to airport
2131 Town
*AirportGetNearestTown(const AirportSpec
*as
, const TileIterator
&it
)
2133 Town
*t
, *nearest
= NULL
;
2134 uint add
= as
->size_x
+ as
->size_y
- 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2135 uint mindist
= UINT_MAX
- add
; // prevent overflow
2137 if (DistanceManhattan(t
->xy
, it
) < mindist
+ add
) { // avoid calling GetMinimalAirportDistanceToTile too often
2138 TileIterator
*copy
= it
.Clone();
2139 uint dist
= GetMinimalAirportDistanceToTile(*copy
, t
->xy
);
2141 if (dist
< mindist
) {
2152 /** Recalculate the noise generated by the airports of each town */
2153 void UpdateAirportsNoise()
2158 FOR_ALL_TOWNS(t
) t
->noise_reached
= 0;
2160 FOR_ALL_STATIONS(st
) {
2161 if (st
->airport
.tile
!= INVALID_TILE
&& st
->airport
.type
!= AT_OILRIG
) {
2162 const AirportSpec
*as
= st
->airport
.GetSpec();
2163 AirportTileIterator
it(st
);
2164 Town
*nearest
= AirportGetNearestTown(as
, it
);
2165 nearest
->noise_reached
+= GetAirportNoiseLevelForTown(as
, it
, nearest
->xy
);
2172 * Checks if an airport can be removed (no aircraft on it or landing)
2173 * @param st Station whose airport is to be removed
2174 * @param flags Operation to perform
2175 * @return Cost or failure of operation
2177 static CommandCost
CanRemoveAirport(Station
*st
, DoCommandFlag flags
)
2180 FOR_ALL_AIRCRAFT(a
) {
2181 if (!a
->IsNormalAircraft()) continue;
2182 if (a
->targetairport
== st
->index
&& a
->state
!= FLYING
)
2183 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY
);
2186 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2188 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2189 if (!st
->TileBelongsToAirport(tile_cur
)) continue;
2191 CommandCost ret
= EnsureNoVehicleOnGround(tile_cur
);
2192 if (ret
.Failed()) return ret
;
2194 cost
.AddCost(_price
[PR_CLEAR_STATION_AIRPORT
]);
2203 * @param tile tile where airport will be built
2204 * @param flags operation to perform
2206 * - p1 = (bit 0- 7) - airport type, @see airport.h
2207 * - p1 = (bit 8-15) - airport layout
2208 * @param p2 various bitstuffed elements
2209 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2210 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2211 * @param text unused
2212 * @return the cost of this operation or an error
2214 CommandCost
CmdBuildAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2216 StationID station_to_join
= GB(p2
, 16, 16);
2217 bool reuse
= (station_to_join
!= NEW_STATION
);
2218 if (!reuse
) station_to_join
= INVALID_STATION
;
2219 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2220 byte airport_type
= GB(p1
, 0, 8);
2221 byte layout
= GB(p1
, 8, 8);
2223 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2225 if (airport_type
>= NUM_AIRPORTS
) return CMD_ERROR
;
2227 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2228 if (ret
.Failed()) return ret
;
2230 /* Check if a valid, buildable airport was chosen for construction */
2231 const AirportSpec
*as
= AirportSpec::Get(airport_type
);
2232 if (!as
->IsAvailable() || layout
>= as
->num_table
) return CMD_ERROR
;
2234 Direction rotation
= as
->rotation
[layout
];
2237 if (rotation
== DIR_E
|| rotation
== DIR_W
) Swap(w
, h
);
2238 TileArea airport_area
= TileArea(tile
, w
, h
);
2240 if (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
) {
2241 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
2244 StationID est
= INVALID_STATION
;
2245 CommandCost cost
= CheckFlatLandAirport(airport_area
, flags
, &est
);
2246 if (cost
.Failed()) return cost
;
2249 ret
= FindJoiningStation(est
, station_to_join
, HasBit(p2
, 0), airport_area
, &st
, STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
2250 if (ret
.Failed()) return ret
;
2253 if (st
== NULL
&& distant_join
) st
= Station::GetIfValid(station_to_join
);
2255 ret
= BuildStationPart(&st
, flags
, reuse
, airport_area
, (GetAirport(airport_type
)->flags
& AirportFTAClass::AIRPLANES
) ? STATIONNAMING_AIRPORT
: STATIONNAMING_HELIPORT
);
2256 if (ret
.Failed()) return ret
;
2258 /* action to be performed */
2260 AIRPORT_NEW
, // airport is a new station
2261 AIRPORT_ADD
, // add an airport to an existing station
2262 AIRPORT_UPGRADE
, // upgrade the airport in a station
2264 (est
!= INVALID_STATION
) ? AIRPORT_UPGRADE
:
2265 (st
!= NULL
) ? AIRPORT_ADD
: AIRPORT_NEW
;
2267 if (action
== AIRPORT_ADD
&& st
->airport
.tile
!= INVALID_TILE
) {
2268 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT
);
2271 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2272 AirportTileTableIterator
iter(as
->table
[layout
], tile
);
2273 Town
*nearest
= AirportGetNearestTown(as
, iter
);
2274 uint newnoise_level
= nearest
->noise_reached
+ GetAirportNoiseLevelForTown(as
, iter
, nearest
->xy
);
2276 if (action
== AIRPORT_UPGRADE
) {
2277 const AirportSpec
*old_as
= st
->airport
.GetSpec();
2278 AirportTileTableIterator
old_iter(old_as
->table
[st
->airport
.layout
], st
->airport
.tile
);
2279 Town
*old_nearest
= AirportGetNearestTown(old_as
, old_iter
);
2280 if (old_nearest
== nearest
) {
2281 newnoise_level
-= GetAirportNoiseLevelForTown(old_as
, old_iter
, nearest
->xy
);
2285 /* Check if local auth would allow a new airport */
2286 StringID authority_refuse_message
= STR_NULL
;
2287 Town
*authority_refuse_town
= NULL
;
2289 if (_settings_game
.economy
.station_noise_level
) {
2290 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2291 if (newnoise_level
> nearest
->MaxTownNoise()) {
2292 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE
;
2293 authority_refuse_town
= nearest
;
2295 } else if (action
!= AIRPORT_UPGRADE
) {
2296 Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
2299 FOR_ALL_STATIONS(st
) {
2300 if (st
->town
== t
&& (st
->facilities
& FACIL_AIRPORT
) && st
->airport
.type
!= AT_OILRIG
) num
++;
2303 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT
;
2304 authority_refuse_town
= t
;
2308 if (authority_refuse_message
!= STR_NULL
) {
2309 SetDParam(0, authority_refuse_town
->index
);
2310 return_cmd_error(authority_refuse_message
);
2313 if (action
== AIRPORT_UPGRADE
) {
2314 /* check that the old airport can be removed */
2315 CommandCost r
= CanRemoveAirport(st
, flags
);
2316 if (r
.Failed()) return r
;
2320 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2321 cost
.AddCost(_price
[PR_BUILD_STATION_AIRPORT
]);
2324 if (flags
& DC_EXEC
) {
2325 if (action
== AIRPORT_UPGRADE
) {
2326 /* delete old airport if upgrading */
2327 const AirportSpec
*old_as
= st
->airport
.GetSpec();
2328 AirportTileTableIterator
old_iter(old_as
->table
[st
->airport
.layout
], st
->airport
.tile
);
2329 Town
*old_nearest
= AirportGetNearestTown(old_as
, old_iter
);
2331 if (old_nearest
!= nearest
) {
2332 old_nearest
->noise_reached
-= GetAirportNoiseLevelForTown(old_as
, old_iter
, old_nearest
->xy
);
2333 if (_settings_game
.economy
.station_noise_level
) {
2334 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2338 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2339 if (IsHangarTile(tile_cur
)) OrderBackup::Reset(tile_cur
, false);
2340 DeleteAnimatedTile(tile_cur
);
2341 DoClearSquare(tile_cur
);
2342 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
);
2345 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2347 WC_VEHICLE_DEPOT
, st
->airport
.GetHangarTile(i
)
2351 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2352 st
->airport
.Clear();
2355 /* Always add the noise, so there will be no need to recalculate when option toggles */
2356 nearest
->noise_reached
= newnoise_level
;
2358 st
->AddFacility(FACIL_AIRPORT
, tile
);
2359 st
->airport
.type
= airport_type
;
2360 st
->airport
.layout
= layout
;
2361 st
->airport
.flags
= 0;
2362 st
->airport
.rotation
= rotation
;
2364 st
->rect
.BeforeAddRect(tile
, w
, h
, StationRect::ADD_TRY
);
2366 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2367 MakeAirport(iter
, st
->owner
, st
->index
, iter
.GetStationGfx(), WATER_CLASS_INVALID
);
2368 SetStationTileRandomBits(iter
, GB(Random(), 0, 4));
2369 st
->airport
.Add(iter
);
2371 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter
.GetStationGfx()))->animation
.status
!= ANIM_STATUS_NO_ANIMATION
) AddAnimatedTile(iter
);
2374 /* Only call the animation trigger after all tiles have been built */
2375 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2376 AirportTileAnimationTrigger(st
, iter
, AAT_BUILT
);
2379 if (action
!= AIRPORT_NEW
) UpdateAirplanesOnNewStation(st
);
2381 if (action
== AIRPORT_UPGRADE
) {
2382 UpdateStationSignCoord(st
);
2384 Company::Get(st
->owner
)->infrastructure
.airport
++;
2385 DirtyCompanyInfrastructureWindows(st
->owner
);
2386 st
->UpdateVirtCoord();
2389 UpdateStationAcceptance(st
, false);
2390 st
->RecomputeIndustriesNear();
2391 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2392 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2393 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2395 if (_settings_game
.economy
.station_noise_level
) {
2396 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2405 * @param tile TileIndex been queried
2406 * @param flags operation to perform
2407 * @return cost or failure of operation
2409 static CommandCost
RemoveAirport(TileIndex tile
, DoCommandFlag flags
)
2411 Station
*st
= Station::GetByTile(tile
);
2413 if (_current_company
!= OWNER_WATER
) {
2414 CommandCost ret
= CheckOwnership(st
->owner
);
2415 if (ret
.Failed()) return ret
;
2418 CommandCost cost
= CanRemoveAirport(st
, flags
);
2419 if (cost
.Failed()) return cost
;
2421 if (flags
& DC_EXEC
) {
2422 const AirportSpec
*as
= st
->airport
.GetSpec();
2423 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2424 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2425 * need of recalculation */
2426 AirportTileIterator
it(st
);
2427 Town
*nearest
= AirportGetNearestTown(as
, it
);
2428 nearest
->noise_reached
-= GetAirportNoiseLevelForTown(as
, it
, nearest
->xy
);
2430 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2431 if (IsHangarTile(tile_cur
)) OrderBackup::Reset(tile_cur
, false);
2432 DeleteAnimatedTile(tile_cur
);
2433 DoClearSquare(tile_cur
);
2434 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
);
2437 /* Clear the persistent storage. */
2438 delete st
->airport
.psa
;
2440 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2442 WC_VEHICLE_DEPOT
, st
->airport
.GetHangarTile(i
)
2446 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2448 st
->airport
.Clear();
2449 st
->facilities
&= ~FACIL_AIRPORT
;
2451 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2453 if (_settings_game
.economy
.station_noise_level
) {
2454 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2457 Company::Get(st
->owner
)->infrastructure
.airport
--;
2458 DirtyCompanyInfrastructureWindows(st
->owner
);
2460 st
->UpdateVirtCoord();
2461 st
->RecomputeIndustriesNear();
2462 DeleteStationIfEmpty(st
);
2463 DeleteNewGRFInspectWindow(GSF_AIRPORTS
, st
->index
);
2470 * Open/close an airport to incoming aircraft.
2471 * @param tile Unused.
2472 * @param flags Operation to perform.
2473 * @param p1 Station ID of the airport.
2475 * @param text unused
2476 * @return the cost of this operation or an error
2478 CommandCost
CmdOpenCloseAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2480 if (!Station::IsValidID(p1
)) return CMD_ERROR
;
2481 Station
*st
= Station::Get(p1
);
2483 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->owner
== OWNER_NONE
) return CMD_ERROR
;
2485 CommandCost ret
= CheckOwnership(st
->owner
);
2486 if (ret
.Failed()) return ret
;
2488 if (flags
& DC_EXEC
) {
2489 st
->airport
.flags
^= AIRPORT_CLOSED_block
;
2490 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_CLOSE_AIRPORT
);
2492 return CommandCost();
2496 * Tests whether the company's vehicles have this station in orders
2497 * @param station station ID
2498 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2499 * @param company company ID
2501 bool HasStationInUse(StationID station
, bool include_company
, CompanyID company
)
2504 FOR_ALL_VEHICLES(v
) {
2505 if ((v
->owner
== company
) == include_company
) {
2507 FOR_VEHICLE_ORDERS(v
, order
) {
2508 if ((order
->IsType(OT_GOTO_STATION
) || order
->IsType(OT_GOTO_WAYPOINT
)) && order
->GetDestination() == station
) {
2517 /** Information about dock tile area for a given direction. */
2518 struct DockTileArea
{
2519 CoordDiff offset
; ///< offset to northern tile
2520 byte width
; ///< width of dock area
2521 byte height
; ///< height of dock area
2525 * Build a dock/haven.
2526 * @param tile tile where dock will be built
2527 * @param flags operation to perform
2528 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
2529 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
2530 * @param text unused
2531 * @return the cost of this operation or an error
2533 CommandCost
CmdBuildDock(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2535 static const DockTileArea dock_tilearea
[DIAGDIR_END
] = {
2536 { { -1, 0 }, 2, 1 },
2539 { { 0, -1 }, 1, 2 },
2542 StationID station_to_join
= GB(p2
, 16, 16);
2543 bool reuse
= (station_to_join
!= NEW_STATION
);
2544 if (!reuse
) station_to_join
= INVALID_STATION
;
2545 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2547 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2549 DiagDirection direction
= GetInclinedSlopeDirection(GetTileSlope(tile
));
2550 if (direction
== INVALID_DIAGDIR
) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2551 direction
= ReverseDiagDir(direction
);
2553 /* Docks cannot be placed on rapids */
2554 if (HasTileWaterGround(tile
)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2556 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2557 if (ret
.Failed()) return ret
;
2559 if (HasBridgeAbove(tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2561 ret
= DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2562 if (ret
.Failed()) return ret
;
2564 TileIndex tile_cur
= tile
+ TileOffsByDiagDir(direction
);
2566 if (!IsWaterTile(tile_cur
) || !IsTileFlat(tile_cur
)) {
2567 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2570 if (HasBridgeAbove(tile_cur
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2572 /* Get the water class of the water tile before it is cleared.*/
2573 WaterClass wc
= GetWaterClass(tile_cur
);
2575 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2576 if (ret
.Failed()) return ret
;
2578 tile_cur
+= TileOffsByDiagDir(direction
);
2579 if (!IsWaterTile(tile_cur
) || !IsTileFlat(tile_cur
)) {
2580 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2583 TileArea dock_area
= TileArea(tile
+ ToTileIndexDiff(dock_tilearea
[direction
].offset
),
2584 dock_tilearea
[direction
].width
, dock_tilearea
[direction
].height
);
2588 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, HasBit(p1
, 0), dock_area
, &st
);
2589 if (ret
.Failed()) return ret
;
2592 if (st
== NULL
&& distant_join
) st
= Station::GetIfValid(station_to_join
);
2594 /* Check if we can allocate a new dock. */
2595 if (!Dock::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_DOCKS
);
2597 ret
= BuildStationPart(&st
, flags
, reuse
, dock_area
, STATIONNAMING_DOCK
);
2598 if (ret
.Failed()) return ret
;
2600 if (flags
& DC_EXEC
) {
2601 Dock
**dl
= &st
->docks
;
2602 while (*dl
!= NULL
) dl
= &(*dl
)->next
;
2604 *dl
= new Dock(tile
);
2605 st
->dock_area
.Add(dock_area
);
2607 st
->AddFacility(FACIL_DOCK
, tile
);
2609 st
->rect
.BeforeAddRect(dock_area
.tile
, dock_area
.w
, dock_area
.h
, StationRect::ADD_TRY
);
2611 /* If the water part of the dock is on a canal, update infrastructure counts.
2612 * This is needed as we've unconditionally cleared that tile before. */
2613 if (wc
== WATER_CLASS_CANAL
) {
2614 Company::Get(st
->owner
)->infrastructure
.water
++;
2616 Company::Get(st
->owner
)->infrastructure
.station
+= 2;
2617 DirtyCompanyInfrastructureWindows(st
->owner
);
2619 MakeDock(tile
, st
->owner
, st
->index
, direction
, wc
);
2621 st
->UpdateVirtCoord();
2622 UpdateStationAcceptance(st
, false);
2623 st
->RecomputeIndustriesNear();
2624 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2625 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2626 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_SHIPS
);
2629 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_STATION_DOCK
]);
2634 * @param tile TileIndex been queried
2635 * @param flags operation to perform
2636 * @return cost or failure of operation
2638 static CommandCost
RemoveDock(TileIndex tile
, DoCommandFlag flags
)
2640 assert(IsDock(tile
));
2642 Station
*st
= Station::GetByTile(tile
);
2643 CommandCost ret
= CheckOwnership(st
->owner
);
2644 if (ret
.Failed()) return ret
;
2646 Dock
**d
= &st
->docks
;
2647 TileIndex tile1
, tile2
;
2648 while ( tile1
= (*d
)->xy
, tile2
= tile1
+ TileOffsByDiagDir(GetDockDirection(tile1
)),
2649 tile
!= tile1
&& tile
!= tile2
) {
2650 /* the dock should really be there, so no check for NULL */
2654 ret
= EnsureNoVehicleOnGround(tile1
);
2655 if (ret
.Succeeded()) ret
= EnsureNoVehicleOnGround(tile2
);
2656 if (ret
.Failed()) return ret
;
2658 if (flags
& DC_EXEC
) {
2659 TileIndex docking_location
= GetDockingTile(tile1
);
2661 DoClearSquare(tile1
);
2662 MarkTileDirtyByTile(tile1
);
2663 MakeWaterKeepingClass(tile2
, st
->owner
);
2665 st
->rect
.AfterRemoveTile(st
, tile1
);
2666 st
->rect
.AfterRemoveTile(st
, tile2
);
2668 Dock
*next
= (*d
)->next
;
2671 if (next
== NULL
&& d
== &st
->docks
) st
->facilities
&= ~FACIL_DOCK
;
2673 Company::Get(st
->owner
)->infrastructure
.station
-= 2;
2674 DirtyCompanyInfrastructureWindows(st
->owner
);
2676 /* Update the tile area of the docks */
2677 st
->dock_area
.Clear();
2678 for (const Dock
*dock
= st
->docks
; dock
!= NULL
; dock
= dock
->next
) {
2679 st
->dock_area
.Add(dock
->xy
);
2680 st
->dock_area
.Add(dock
->xy
+ TileOffsByDiagDir(GetDockDirection(dock
->xy
)));
2683 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_SHIPS
);
2684 st
->UpdateVirtCoord();
2685 st
->RecomputeIndustriesNear();
2686 DeleteStationIfEmpty(st
);
2688 /* All ships that were going to our station, can't go to it anymore.
2689 * Just clear the order, then automatically the next appropriate order
2690 * will be selected and in case of no appropriate order it will just
2691 * wander around the world. */
2694 if (s
->current_order
.IsType(OT_LOADING
) && s
->tile
== docking_location
) {
2698 if (s
->dest_tile
== docking_location
) {
2700 s
->current_order
.Free();
2705 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_STATION_DOCK
]);
2708 #include "table/station_land.h"
2710 const DrawTileSprites
*GetStationTileLayout(StationType st
, byte gfx
)
2712 return &_station_display_datas
[st
][gfx
];
2716 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
2717 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
2718 * is set to the overlay to draw.
2719 * @param ti Positional info for the tile to decide snowyness etc. May be NULL.
2720 * @param [in,out] ground Groundsprite to draw.
2721 * @param [out] overlay_offset Overlay to draw.
2722 * @return true if overlay can be drawn.
2724 bool SplitGroundSpriteForOverlay(const TileInfo
*ti
, SpriteID
*ground
, RailTrackOffset
*overlay_offset
)
2728 case SPR_RAIL_TRACK_X
:
2729 snow_desert
= false;
2730 *overlay_offset
= RTO_X
;
2733 case SPR_RAIL_TRACK_Y
:
2734 snow_desert
= false;
2735 *overlay_offset
= RTO_Y
;
2738 case SPR_RAIL_TRACK_X_SNOW
:
2740 *overlay_offset
= RTO_X
;
2743 case SPR_RAIL_TRACK_Y_SNOW
:
2745 *overlay_offset
= RTO_Y
;
2753 /* Decide snow/desert from tile */
2754 switch (_settings_game
.game_creation
.landscape
) {
2756 snow_desert
= (uint
)ti
->z
> GetSnowLine() * TILE_HEIGHT
;
2760 snow_desert
= GetTropicZone(ti
->tile
) == TROPICZONE_DESERT
;
2768 *ground
= snow_desert
? SPR_FLAT_SNOW_DESERT_TILE
: SPR_FLAT_GRASS_TILE
;
2772 static void DrawTile_Station(TileInfo
*ti
)
2774 const NewGRFSpriteLayout
*layout
= NULL
;
2775 DrawTileSprites tmp_rail_layout
;
2776 const DrawTileSprites
*t
= NULL
;
2777 RoadTypes roadtypes
;
2779 const RailtypeInfo
*rti
= NULL
;
2780 uint32 relocation
= 0;
2781 uint32 ground_relocation
= 0;
2782 BaseStation
*st
= NULL
;
2783 const StationSpec
*statspec
= NULL
;
2784 uint tile_layout
= 0;
2786 if (HasStationRail(ti
->tile
)) {
2787 rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
2788 roadtypes
= ROADTYPES_NONE
;
2789 total_offset
= rti
->GetRailtypeSpriteOffset();
2791 if (IsCustomStationSpecIndex(ti
->tile
)) {
2792 /* look for customization */
2793 st
= BaseStation::GetByTile(ti
->tile
);
2794 statspec
= st
->speclist
[GetCustomStationSpecIndex(ti
->tile
)].spec
;
2796 if (statspec
!= NULL
) {
2797 tile_layout
= GetStationGfx(ti
->tile
);
2799 if (HasBit(statspec
->callback_mask
, CBM_STATION_SPRITE_LAYOUT
)) {
2800 uint16 callback
= GetStationCallback(CBID_STATION_SPRITE_LAYOUT
, 0, 0, statspec
, st
, ti
->tile
);
2801 if (callback
!= CALLBACK_FAILED
) tile_layout
= (callback
& ~1) + GetRailStationAxis(ti
->tile
);
2804 /* Ensure the chosen tile layout is valid for this custom station */
2805 if (statspec
->renderdata
!= NULL
) {
2806 layout
= &statspec
->renderdata
[tile_layout
< statspec
->tiles
? tile_layout
: (uint
)GetRailStationAxis(ti
->tile
)];
2807 if (!layout
->NeedsPreprocessing()) {
2815 roadtypes
= IsRoadStop(ti
->tile
) ? GetRoadTypes(ti
->tile
) : ROADTYPES_NONE
;
2819 StationGfx gfx
= GetStationGfx(ti
->tile
);
2820 if (IsAirport(ti
->tile
)) {
2821 gfx
= GetAirportGfx(ti
->tile
);
2822 if (gfx
>= NEW_AIRPORTTILE_OFFSET
) {
2823 const AirportTileSpec
*ats
= AirportTileSpec::Get(gfx
);
2824 if (ats
->grf_prop
.spritegroup
[0] != NULL
&& DrawNewAirportTile(ti
, Station::GetByTile(ti
->tile
), gfx
, ats
)) {
2827 /* No sprite group (or no valid one) found, meaning no graphics associated.
2828 * Use the substitute one instead */
2829 assert(ats
->grf_prop
.subst_id
!= INVALID_AIRPORTTILE
);
2830 gfx
= ats
->grf_prop
.subst_id
;
2833 case APT_RADAR_GRASS_FENCE_SW
:
2834 t
= &_station_display_datas_airport_radar_grass_fence_sw
[GetAnimationFrame(ti
->tile
)];
2836 case APT_GRASS_FENCE_NE_FLAG
:
2837 t
= &_station_display_datas_airport_flag_grass_fence_ne
[GetAnimationFrame(ti
->tile
)];
2839 case APT_RADAR_FENCE_SW
:
2840 t
= &_station_display_datas_airport_radar_fence_sw
[GetAnimationFrame(ti
->tile
)];
2842 case APT_RADAR_FENCE_NE
:
2843 t
= &_station_display_datas_airport_radar_fence_ne
[GetAnimationFrame(ti
->tile
)];
2845 case APT_GRASS_FENCE_NE_FLAG_2
:
2846 t
= &_station_display_datas_airport_flag_grass_fence_ne_2
[GetAnimationFrame(ti
->tile
)];
2851 Owner owner
= GetTileOwner(ti
->tile
);
2854 if (Company::IsValidID(owner
)) {
2855 palette
= COMPANY_SPRITE_COLOUR(owner
);
2857 /* Some stations are not owner by a company, namely oil rigs */
2858 palette
= PALETTE_TO_GREY
;
2861 if (layout
== NULL
&& (t
== NULL
|| t
->seq
== NULL
)) t
= GetStationTileLayout(GetStationType(ti
->tile
), gfx
);
2863 /* don't show foundation for docks */
2864 if (ti
->tileh
!= SLOPE_FLAT
&& !IsDock(ti
->tile
)) {
2865 if (statspec
!= NULL
&& HasBit(statspec
->flags
, SSF_CUSTOM_FOUNDATIONS
)) {
2866 /* Station has custom foundations.
2867 * Check whether the foundation continues beyond the tile's upper sides. */
2870 Slope slope
= GetFoundationPixelSlope(ti
->tile
, &z
);
2871 if (!HasFoundationNW(ti
->tile
, slope
, z
)) SetBit(edge_info
, 0);
2872 if (!HasFoundationNE(ti
->tile
, slope
, z
)) SetBit(edge_info
, 1);
2873 SpriteID image
= GetCustomStationFoundationRelocation(statspec
, st
, ti
->tile
, tile_layout
, edge_info
);
2874 if (image
== 0) goto draw_default_foundation
;
2876 if (HasBit(statspec
->flags
, SSF_EXTENDED_FOUNDATIONS
)) {
2877 /* Station provides extended foundations. */
2879 static const uint8 foundation_parts
[] = {
2880 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2881 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2882 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2883 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2886 AddSortableSpriteToDraw(image
+ foundation_parts
[ti
->tileh
], PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
2888 /* Draw simple foundations, built up from 8 possible foundation sprites. */
2890 /* Each set bit represents one of the eight composite sprites to be drawn.
2891 * 'Invalid' entries will not drawn but are included for completeness. */
2892 static const uint8 composite_foundation_parts
[] = {
2893 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2894 0x00, 0xD1, 0xE4, 0xE0,
2895 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2896 0xCA, 0xC9, 0xC4, 0xC0,
2897 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2898 0xD2, 0x91, 0xE4, 0xA0,
2899 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2903 uint8 parts
= composite_foundation_parts
[ti
->tileh
];
2905 /* If foundations continue beyond the tile's upper sides then
2906 * mask out the last two pieces. */
2907 if (HasBit(edge_info
, 0)) ClrBit(parts
, 6);
2908 if (HasBit(edge_info
, 1)) ClrBit(parts
, 7);
2911 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2912 * correct offset for the childsprites.
2913 * So, draw the (completely empty) sprite of the default foundations. */
2914 goto draw_default_foundation
;
2917 StartSpriteCombine();
2918 for (int i
= 0; i
< 8; i
++) {
2919 if (HasBit(parts
, i
)) {
2920 AddSortableSpriteToDraw(image
+ i
, PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
2926 OffsetGroundSprite(31, 1);
2927 ti
->z
+= ApplyPixelFoundationToSlope(FOUNDATION_LEVELED
, &ti
->tileh
);
2929 draw_default_foundation
:
2930 DrawFoundation(ti
, FOUNDATION_LEVELED
);
2934 if (IsBuoy(ti
->tile
)) {
2935 DrawWaterClassGround(ti
);
2936 SpriteID sprite
= GetCanalSprite(CF_BUOY
, ti
->tile
);
2937 if (sprite
!= 0) total_offset
= sprite
- SPR_IMG_BUOY
;
2938 } else if (IsDock(ti
->tile
) || (IsOilRig(ti
->tile
) && IsTileOnWater(ti
->tile
))) {
2939 if (ti
->tileh
== SLOPE_FLAT
) {
2940 DrawWaterClassGround(ti
);
2942 assert(IsDock(ti
->tile
));
2943 TileIndex water_tile
= ti
->tile
+ TileOffsByDiagDir(GetDockDirection(ti
->tile
));
2944 WaterClass wc
= GetWaterClass(water_tile
);
2945 if (wc
== WATER_CLASS_SEA
) {
2946 DrawShoreTile(ti
->tileh
);
2948 DrawClearLandTile(ti
, 3);
2952 if (layout
!= NULL
) {
2953 /* Sprite layout which needs preprocessing */
2954 bool separate_ground
= HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
);
2955 uint32 var10_values
= layout
->PrepareLayout(total_offset
, rti
->fallback_railtype
, 0, 0, separate_ground
);
2957 FOR_EACH_SET_BIT(var10
, var10_values
) {
2958 uint32 var10_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, var10
);
2959 layout
->ProcessRegisters(var10
, var10_relocation
, separate_ground
);
2961 tmp_rail_layout
.seq
= layout
->GetLayout(&tmp_rail_layout
.ground
);
2962 t
= &tmp_rail_layout
;
2964 } else if (statspec
!= NULL
) {
2965 /* Simple sprite layout */
2966 ground_relocation
= relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 0);
2967 if (HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
)) {
2968 ground_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 1);
2970 ground_relocation
+= rti
->fallback_railtype
;
2973 SpriteID image
= t
->ground
.sprite
;
2974 PaletteID pal
= t
->ground
.pal
;
2975 RailTrackOffset overlay_offset
;
2976 if (rti
!= NULL
&& rti
->UsesOverlay() && SplitGroundSpriteForOverlay(ti
, &image
, &overlay_offset
)) {
2977 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
);
2978 DrawGroundSprite(image
, PAL_NONE
);
2979 DrawGroundSprite(ground
+ overlay_offset
, PAL_NONE
);
2981 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationReservation(ti
->tile
)) {
2982 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
2983 DrawGroundSprite(overlay
+ overlay_offset
, PALETTE_CRASH
);
2986 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
2987 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
2988 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
));
2990 /* PBS debugging, draw reserved tracks darker */
2991 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationRail(ti
->tile
) && HasStationReservation(ti
->tile
)) {
2992 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
2993 DrawGroundSprite(GetRailStationAxis(ti
->tile
) == AXIS_X
? rti
->base_sprites
.single_x
: rti
->base_sprites
.single_y
, PALETTE_CRASH
);
2998 if (HasStationRail(ti
->tile
) && HasCatenaryDrawn(GetRailType(ti
->tile
))) DrawCatenary(ti
);
3000 if (HasBit(roadtypes
, ROADTYPE_TRAM
)) {
3001 Axis axis
= GetRoadStopAxis(ti
->tile
); // tram stops are always drive-through
3002 DrawGroundSprite((HasBit(roadtypes
, ROADTYPE_ROAD
) ? SPR_TRAMWAY_OVERLAY
: SPR_TRAMWAY_TRAM
) + (axis
^ 1), PAL_NONE
);
3003 DrawTramCatenary(ti
, axis
== AXIS_X
? ROAD_X
: ROAD_Y
);
3006 if (IsRailWaypoint(ti
->tile
)) {
3007 /* Don't offset the waypoint graphics; they're always the same. */
3011 DrawRailTileSeq(ti
, t
, TO_BUILDINGS
, total_offset
, relocation
, palette
);
3014 void StationPickerDrawSprite(int x
, int y
, StationType st
, RailType railtype
, RoadType roadtype
, int image
)
3016 int32 total_offset
= 0;
3017 PaletteID pal
= COMPANY_SPRITE_COLOUR(_local_company
);
3018 const DrawTileSprites
*t
= GetStationTileLayout(st
, image
);
3019 const RailtypeInfo
*rti
= NULL
;
3021 if (railtype
!= INVALID_RAILTYPE
) {
3022 rti
= GetRailTypeInfo(railtype
);
3023 total_offset
= rti
->GetRailtypeSpriteOffset();
3026 SpriteID img
= t
->ground
.sprite
;
3027 RailTrackOffset overlay_offset
;
3028 if (rti
!= NULL
&& rti
->UsesOverlay() && SplitGroundSpriteForOverlay(NULL
, &img
, &overlay_offset
)) {
3029 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
3030 DrawSprite(img
, PAL_NONE
, x
, y
);
3031 DrawSprite(ground
+ overlay_offset
, PAL_NONE
, x
, y
);
3033 DrawSprite(img
+ total_offset
, HasBit(img
, PALETTE_MODIFIER_COLOUR
) ? pal
: PAL_NONE
, x
, y
);
3036 if (roadtype
== ROADTYPE_TRAM
) {
3037 DrawSprite(SPR_TRAMWAY_TRAM
+ (t
->ground
.sprite
== SPR_ROAD_PAVED_STRAIGHT_X
? 1 : 0), PAL_NONE
, x
, y
);
3040 /* Default waypoint has no railtype specific sprites */
3041 DrawRailTileSeqInGUI(x
, y
, t
, st
== STATION_WAYPOINT
? 0 : total_offset
, 0, pal
);
3044 static int GetSlopePixelZ_Station(TileIndex tile
, uint x
, uint y
)
3046 return GetTileMaxPixelZ(tile
);
3049 static Foundation
GetFoundation_Station(TileIndex tile
, Slope tileh
)
3051 return FlatteningFoundation(tileh
);
3054 static void GetTileDesc_Station(TileIndex tile
, TileDesc
*td
)
3056 td
->owner
[0] = GetTileOwner(tile
);
3057 if (IsDriveThroughStopTile(tile
)) {
3058 Owner road_owner
= INVALID_OWNER
;
3059 Owner tram_owner
= INVALID_OWNER
;
3060 RoadTypes rts
= GetRoadTypes(tile
);
3061 if (HasBit(rts
, ROADTYPE_ROAD
)) road_owner
= GetRoadOwner(tile
, ROADTYPE_ROAD
);
3062 if (HasBit(rts
, ROADTYPE_TRAM
)) tram_owner
= GetRoadOwner(tile
, ROADTYPE_TRAM
);
3064 /* Is there a mix of owners? */
3065 if ((tram_owner
!= INVALID_OWNER
&& tram_owner
!= td
->owner
[0]) ||
3066 (road_owner
!= INVALID_OWNER
&& road_owner
!= td
->owner
[0])) {
3068 if (road_owner
!= INVALID_OWNER
) {
3069 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_ROAD_OWNER
;
3070 td
->owner
[i
] = road_owner
;
3073 if (tram_owner
!= INVALID_OWNER
) {
3074 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_TRAM_OWNER
;
3075 td
->owner
[i
] = tram_owner
;
3079 td
->build_date
= BaseStation::GetByTile(tile
)->build_date
;
3081 if (HasStationTileRail(tile
)) {
3082 const StationSpec
*spec
= GetStationSpec(tile
);
3085 td
->station_class
= StationClass::Get(spec
->cls_id
)->name
;
3086 td
->station_name
= spec
->name
;
3088 if (spec
->grf_prop
.grffile
!= NULL
) {
3089 const GRFConfig
*gc
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
);
3090 td
->grf
= gc
->GetName();
3094 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(tile
));
3095 td
->rail_speed
= rti
->max_speed
;
3098 if (IsAirport(tile
)) {
3099 const AirportSpec
*as
= Station::GetByTile(tile
)->airport
.GetSpec();
3100 td
->airport_class
= AirportClass::Get(as
->cls_id
)->name
;
3101 td
->airport_name
= as
->name
;
3103 const AirportTileSpec
*ats
= AirportTileSpec::GetByTile(tile
);
3104 td
->airport_tile_name
= ats
->name
;
3106 if (as
->grf_prop
.grffile
!= NULL
) {
3107 const GRFConfig
*gc
= GetGRFConfig(as
->grf_prop
.grffile
->grfid
);
3108 td
->grf
= gc
->GetName();
3109 } else if (ats
->grf_prop
.grffile
!= NULL
) {
3110 const GRFConfig
*gc
= GetGRFConfig(ats
->grf_prop
.grffile
->grfid
);
3111 td
->grf
= gc
->GetName();
3116 switch (GetStationType(tile
)) {
3117 default: NOT_REACHED();
3118 case STATION_RAIL
: str
= STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION
; break;
3119 case STATION_AIRPORT
:
3120 str
= (IsHangar(tile
) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR
: STR_LAI_STATION_DESCRIPTION_AIRPORT
);
3122 case STATION_TRUCK
: str
= STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA
; break;
3123 case STATION_BUS
: str
= STR_LAI_STATION_DESCRIPTION_BUS_STATION
; break;
3124 case STATION_OILRIG
: str
= STR_INDUSTRY_NAME_OIL_RIG
; break;
3125 case STATION_DOCK
: str
= STR_LAI_STATION_DESCRIPTION_SHIP_DOCK
; break;
3126 case STATION_BUOY
: str
= STR_LAI_STATION_DESCRIPTION_BUOY
; break;
3127 case STATION_WAYPOINT
: str
= STR_LAI_STATION_DESCRIPTION_WAYPOINT
; break;
3133 static TrackStatus
GetTileRailwayStatus_Station(TileIndex tile
, DiagDirection side
)
3135 if (!HasStationRail(tile
) || IsStationTileBlocked(tile
)) return 0;
3137 return CombineTrackStatus(TrackBitsToTrackdirBits(GetRailStationTrackBits(tile
)), TRACKDIR_BIT_NONE
);
3140 static TrackStatus
GetTileRoadStatus_Station(TileIndex tile
, uint sub_mode
, DiagDirection side
)
3142 if (!IsRoadStop(tile
) || (GetRoadTypes(tile
) & sub_mode
) == 0) return 0;
3144 TrackBits trackbits
;
3146 if (IsStandardRoadStopTile(tile
)) {
3147 DiagDirection dir
= GetRoadStopDir(tile
);
3149 if (side
!= INVALID_DIAGDIR
&& dir
!= side
) return 0;
3151 trackbits
= DiagDirToDiagTrackBits(dir
);
3153 Axis axis
= GetRoadStopAxis(tile
);
3155 if (side
!= INVALID_DIAGDIR
&& axis
!= DiagDirToAxis(side
)) return 0;
3157 trackbits
= AxisToTrackBits(axis
);
3160 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits
), TRACKDIR_BIT_NONE
);
3163 static TrackStatus
GetTileWaterwayStatus_Station(TileIndex tile
, DiagDirection side
)
3165 if (!IsBuoy(tile
)) return 0;
3167 /* buoy is coded as a station, it is always on open water */
3168 TrackBits trackbits
= TRACK_BIT_ALL
;
3169 /* remove tracks that connect NE map edge */
3170 if (TileX(tile
) == 0) trackbits
&= ~(TRACK_BIT_X
| TRACK_BIT_UPPER
| TRACK_BIT_RIGHT
);
3171 /* remove tracks that connect NW map edge */
3172 if (TileY(tile
) == 0) trackbits
&= ~(TRACK_BIT_Y
| TRACK_BIT_LEFT
| TRACK_BIT_UPPER
);
3174 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits
), TRACKDIR_BIT_NONE
);
3178 static void TileLoop_Station(TileIndex tile
)
3180 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3181 * hardcoded.....not good */
3182 switch (GetStationType(tile
)) {
3183 case STATION_AIRPORT
:
3184 AirportTileAnimationTrigger(Station::GetByTile(tile
), tile
, AAT_TILELOOP
);
3188 if (!IsTileFlat(tile
)) break; // only handle water part
3190 case STATION_OILRIG
: //(station part)
3192 TileLoop_Water(tile
);
3200 static void AnimateTile_Station(TileIndex tile
)
3202 if (HasStationRail(tile
)) {
3203 AnimateStationTile(tile
);
3207 if (IsAirport(tile
)) {
3208 AnimateAirportTile(tile
);
3213 static bool ClickTile_Station(TileIndex tile
)
3215 const BaseStation
*bst
= BaseStation::GetByTile(tile
);
3217 if (bst
->facilities
& FACIL_WAYPOINT
) {
3218 ShowWaypointWindow(Waypoint::From(bst
));
3219 } else if (IsHangar(tile
)) {
3220 const Station
*st
= Station::From(bst
);
3221 ShowDepotWindow(st
->airport
.GetHangarTile(st
->airport
.GetHangarNum(tile
)), VEH_AIRCRAFT
);
3223 ShowStationViewWindow(bst
->index
);
3229 * Run the watched cargo callback for all houses in the catchment area.
3230 * @param st Station.
3232 void TriggerWatchedCargoCallbacks(Station
*st
)
3234 /* Collect cargoes accepted since the last big tick. */
3236 for (CargoID cid
= 0; cid
< NUM_CARGO
; cid
++) {
3237 if (HasBit(st
->goods
[cid
].acceptance_pickup
, GoodsEntry::GES_ACCEPTED_BIGTICK
)) SetBit(cargoes
, cid
);
3240 /* Anything to do? */
3241 if (cargoes
== 0) return;
3243 /* Loop over all houses in the catchment. */
3244 Rect r
= st
->GetCatchmentRect();
3245 TileArea
ta(TileXY(r
.left
, r
.top
), TileXY(r
.right
, r
.bottom
));
3246 TILE_AREA_LOOP(tile
, ta
) {
3247 if (IsHouseTile(tile
)) {
3248 WatchedCargoCallback(tile
, cargoes
);
3254 * This function is called for each station once every 250 ticks.
3255 * Not all stations will get the tick at the same time.
3256 * @param st the station receiving the tick.
3257 * @return true if the station is still valid (wasn't deleted)
3259 static bool StationHandleBigTick(BaseStation
*st
)
3261 if (!st
->IsInUse()) {
3262 if (++st
->delete_ctr
>= 8) delete st
;
3266 if (Station::IsExpected(st
)) {
3267 TriggerWatchedCargoCallbacks(Station::From(st
));
3269 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3270 ClrBit(Station::From(st
)->goods
[i
].acceptance_pickup
, GoodsEntry::GES_ACCEPTED_BIGTICK
);
3275 if ((st
->facilities
& FACIL_WAYPOINT
) == 0) UpdateStationAcceptance(Station::From(st
), true);
3280 static inline void byte_inc_sat(byte
*p
)
3286 static void UpdateStationRating(Station
*st
)
3288 bool waiting_changed
= false;
3290 byte_inc_sat(&st
->time_since_load
);
3291 byte_inc_sat(&st
->time_since_unload
);
3293 const CargoSpec
*cs
;
3294 FOR_ALL_CARGOSPECS(cs
) {
3295 GoodsEntry
*ge
= &st
->goods
[cs
->Index()];
3296 /* Slowly increase the rating back to his original level in the case we
3297 * didn't deliver cargo yet to this station. This happens when a bribe
3298 * failed while you didn't moved that cargo yet to a station. */
3299 if (!ge
->HasRating() && ge
->rating
< INITIAL_STATION_RATING
) {
3303 /* Only change the rating if we are moving this cargo */
3304 if (ge
->HasRating()) {
3305 byte_inc_sat(&ge
->time_since_pickup
);
3309 uint waiting
= ge
->cargo
.TotalCount();
3311 /* num_dests is at least 1 if there is any cargo as
3312 * INVALID_STATION is also a destination.
3314 uint num_dests
= (uint
)ge
->cargo
.Packets()->MapSize();
3316 /* Average amount of cargo per next hop, but prefer solitary stations
3317 * with only one or two next hops. They are allowed to have more
3318 * cargo waiting per next hop.
3319 * With manual cargo distribution waiting_avg = waiting / 2 as then
3320 * INVALID_STATION is the only destination.
3322 uint waiting_avg
= waiting
/ (num_dests
+ 1);
3324 if (HasBit(cs
->callback_mask
, CBM_CARGO_STATION_RATING_CALC
)) {
3325 /* Perform custom station rating. If it succeeds the speed, days in transit and
3326 * waiting cargo ratings must not be executed. */
3328 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3329 uint last_speed
= ge
->HasVehicleEverTriedLoading() ? ge
->last_speed
: 0xFF;
3331 uint32 var18
= min(ge
->time_since_pickup
, 0xFF) | (min(ge
->max_waiting_cargo
, 0xFFFF) << 8) | (min(last_speed
, 0xFF) << 24);
3332 /* Convert to the 'old' vehicle types */
3333 uint32 var10
= (st
->last_vehicle_type
== VEH_INVALID
) ? 0x0 : (st
->last_vehicle_type
+ 0x10);
3334 uint16 callback
= GetCargoCallback(CBID_CARGO_STATION_RATING_CALC
, var10
, var18
, cs
);
3335 if (callback
!= CALLBACK_FAILED
) {
3337 rating
= GB(callback
, 0, 14);
3339 /* Simulate a 15 bit signed value */
3340 if (HasBit(callback
, 14)) rating
-= 0x4000;
3345 int b
= ge
->last_speed
- 85;
3346 if (b
>= 0) rating
+= b
>> 2;
3348 byte waittime
= ge
->time_since_pickup
;
3349 if (st
->last_vehicle_type
== VEH_SHIP
) waittime
>>= 2;
3351 (rating
+= 25, waittime
> 12) ||
3352 (rating
+= 25, waittime
> 6) ||
3353 (rating
+= 45, waittime
> 3) ||
3354 (rating
+= 35, true);
3356 (rating
-= 90, ge
->max_waiting_cargo
> 1500) ||
3357 (rating
+= 55, ge
->max_waiting_cargo
> 1000) ||
3358 (rating
+= 35, ge
->max_waiting_cargo
> 600) ||
3359 (rating
+= 10, ge
->max_waiting_cargo
> 300) ||
3360 (rating
+= 20, ge
->max_waiting_cargo
> 100) ||
3361 (rating
+= 10, true);
3364 if (Company::IsValidID(st
->owner
) && HasBit(st
->town
->statues
, st
->owner
)) rating
+= 26;
3366 byte age
= ge
->last_age
;
3368 (rating
+= 10, age
>= 2) ||
3369 (rating
+= 10, age
>= 1) ||
3370 (rating
+= 13, true);
3373 int or_
= ge
->rating
; // old rating
3375 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3376 ge
->rating
= rating
= or_
+ Clamp(Clamp(rating
, 0, 255) - or_
, -2, 2);
3378 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3379 * remove some random amount of goods from the station */
3380 if (rating
<= 64 && waiting_avg
>= 100) {
3381 int dec
= Random() & 0x1F;
3382 if (waiting_avg
< 200) dec
&= 7;
3383 waiting
-= (dec
+ 1) * num_dests
;
3384 waiting_changed
= true;
3387 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3388 if (rating
<= 127 && waiting
!= 0) {
3389 uint32 r
= Random();
3390 if (rating
<= (int)GB(r
, 0, 7)) {
3391 /* Need to have int, otherwise it will just overflow etc. */
3392 waiting
= max((int)waiting
- (int)((GB(r
, 8, 2) - 1) * num_dests
), 0);
3393 waiting_changed
= true;
3397 /* At some point we really must cap the cargo. Previously this
3398 * was a strict 4095, but now we'll have a less strict, but
3399 * increasingly aggressive truncation of the amount of cargo. */
3400 static const uint WAITING_CARGO_THRESHOLD
= 1 << 12;
3401 static const uint WAITING_CARGO_CUT_FACTOR
= 1 << 6;
3402 static const uint MAX_WAITING_CARGO
= 1 << 15;
3404 if (waiting
> WAITING_CARGO_THRESHOLD
) {
3405 uint difference
= waiting
- WAITING_CARGO_THRESHOLD
;
3406 waiting
-= (difference
/ WAITING_CARGO_CUT_FACTOR
);
3408 waiting
= min(waiting
, MAX_WAITING_CARGO
);
3409 waiting_changed
= true;
3412 /* We can't truncate cargo that's already reserved for loading.
3413 * Thus StoredCount() here. */
3414 if (waiting_changed
&& waiting
< ge
->cargo
.AvailableCount()) {
3415 /* Feed back the exact own waiting cargo at this station for the
3416 * next rating calculation. */
3417 ge
->max_waiting_cargo
= 0;
3419 /* If truncating also punish the source stations' ratings to
3420 * decrease the flow of incoming cargo. */
3422 StationCargoAmountMap waiting_per_source
;
3423 ge
->cargo
.Truncate(ge
->cargo
.AvailableCount() - waiting
, &waiting_per_source
);
3424 for (StationCargoAmountMap::iterator
i(waiting_per_source
.begin()); i
!= waiting_per_source
.end(); ++i
) {
3425 Station
*source_station
= Station::GetIfValid(i
->first
);
3426 if (source_station
== NULL
) continue;
3428 GoodsEntry
&source_ge
= source_station
->goods
[cs
->Index()];
3429 source_ge
.max_waiting_cargo
= max(source_ge
.max_waiting_cargo
, i
->second
);
3432 /* If the average number per next hop is low, be more forgiving. */
3433 ge
->max_waiting_cargo
= waiting_avg
;
3439 StationID index
= st
->index
;
3440 if (waiting_changed
) {
3441 SetWindowDirty(WC_STATION_VIEW
, index
); // update whole window
3443 SetWindowWidgetDirty(WC_STATION_VIEW
, index
, WID_SV_ACCEPT_RATING_LIST
); // update only ratings list
3448 * Reroute cargo of type c at station st or in any vehicles unloading there.
3449 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3450 * @param st Station to be rerouted at.
3451 * @param c Type of cargo.
3452 * @param avoid Original next hop of cargo, avoid this.
3453 * @param avoid2 Another station to be avoided when rerouting.
3455 void RerouteCargo(Station
*st
, CargoID c
, StationID avoid
, StationID avoid2
)
3457 GoodsEntry
&ge
= st
->goods
[c
];
3459 /* Reroute cargo in station. */
3460 ge
.cargo
.Reroute(UINT_MAX
, &ge
.cargo
, avoid
, avoid2
, &ge
);
3462 /* Reroute cargo staged to be transfered. */
3463 for (std::list
<Vehicle
*>::iterator
it(st
->loading_vehicles
.begin()); it
!= st
->loading_vehicles
.end(); ++it
) {
3464 for (Vehicle
*v
= *it
; v
!= NULL
; v
= v
->Next()) {
3465 if (v
->cargo_type
!= c
) continue;
3466 v
->cargo
.Reroute(UINT_MAX
, &v
->cargo
, avoid
, avoid2
, &ge
);
3472 * Check all next hops of cargo packets in this station for existance of a
3473 * a valid link they may use to travel on. Reroute any cargo not having a valid
3474 * link and remove timed out links found like this from the linkgraph. We're
3475 * not all links here as that is expensive and useless. A link no one is using
3476 * doesn't hurt either.
3477 * @param from Station to check.
3479 void DeleteStaleLinks(Station
*from
)
3481 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
3482 GoodsEntry
&ge
= from
->goods
[c
];
3483 LinkGraph
*lg
= LinkGraph::GetIfValid(ge
.link_graph
);
3484 if (lg
== NULL
) continue;
3485 Node node
= (*lg
)[ge
.node
];
3486 for (EdgeIterator
it(node
.Begin()); it
!= node
.End();) {
3487 Edge edge
= it
->second
;
3488 Station
*to
= Station::Get((*lg
)[it
->first
].Station());
3489 assert(to
->goods
[c
].node
== it
->first
);
3490 ++it
; // Do that before removing the edge. Anything else may crash.
3491 assert(_date
>= edge
.LastUpdate());
3492 uint timeout
= LinkGraph::MIN_TIMEOUT_DISTANCE
+ (DistanceManhattan(from
->xy
, to
->xy
) >> 3);
3493 if ((uint
)(_date
- edge
.LastUpdate()) > timeout
) {
3494 /* Have all vehicles refresh their next hops before deciding to
3495 * remove the node. */
3496 bool updated
= false;
3498 FOR_ALL_ORDER_LISTS(l
) {
3499 bool found_from
= false;
3500 bool found_to
= false;
3501 for (Order
*order
= l
->GetFirstOrder(); order
!= NULL
; order
= order
->next
) {
3502 if (!order
->IsType(OT_GOTO_STATION
) && !order
->IsType(OT_IMPLICIT
)) continue;
3503 if (order
->GetDestination() == from
->index
) {
3505 if (found_to
) break;
3506 } else if (order
->GetDestination() == to
->index
) {
3508 if (found_from
) break;
3511 if (!found_to
|| !found_from
) continue;
3512 for (Vehicle
*v
= l
->GetFirstSharedVehicle(); !updated
&& v
!= NULL
; v
= v
->NextShared()) {
3513 /* There is potential for optimization here:
3514 * - Usually consists of the same order list are the same. It's probably better to
3515 * first check the first of each list, then the second of each list and so on.
3516 * - We could try to figure out if we've seen a consist with the same cargo on the
3517 * same list already and if the consist can actually carry the cargo we're looking
3518 * for. With conditional and refit orders this is not quite trivial, though. */
3519 LinkRefresher::Run(v
, false); // Don't allow merging. Otherwise lg might get deleted.
3520 if (edge
.LastUpdate() == _date
) updated
= true;
3525 /* If it's still considered dead remove it. */
3526 node
.RemoveEdge(to
->goods
[c
].node
);
3527 ge
.flows
.DeleteFlows(to
->index
);
3528 RerouteCargo(from
, c
, to
->index
, from
->index
);
3530 } else if (edge
.LastUnrestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastUnrestrictedUpdate()) > timeout
) {
3532 ge
.flows
.RestrictFlows(to
->index
);
3533 RerouteCargo(from
, c
, to
->index
, from
->index
);
3534 } else if (edge
.LastRestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastRestrictedUpdate()) > timeout
) {
3538 assert(_date
>= lg
->LastCompression());
3539 if ((uint
)(_date
- lg
->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL
) {
3546 * Increase capacity for a link stat given by station cargo and next hop.
3547 * @param st Station to get the link stats from.
3548 * @param cargo Cargo to increase stat for.
3549 * @param next_station_id Station the consist will be travelling to next.
3550 * @param capacity Capacity to add to link stat.
3551 * @param usage Usage to add to link stat. If UINT_MAX refresh the link instead of increasing.
3553 void IncreaseStats(Station
*st
, CargoID cargo
, StationID next_station_id
, uint capacity
, uint usage
)
3555 GoodsEntry
&ge1
= st
->goods
[cargo
];
3556 Station
*st2
= Station::Get(next_station_id
);
3557 GoodsEntry
&ge2
= st2
->goods
[cargo
];
3558 LinkGraph
*lg
= NULL
;
3559 if (ge1
.link_graph
== INVALID_LINK_GRAPH
) {
3560 if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3561 if (LinkGraph::CanAllocateItem()) {
3562 lg
= new LinkGraph(cargo
);
3563 LinkGraphSchedule::Instance()->Queue(lg
);
3564 ge2
.link_graph
= lg
->index
;
3565 ge2
.node
= lg
->AddNode(st2
);
3567 DEBUG(misc
, 0, "Can't allocate link graph");
3570 lg
= LinkGraph::Get(ge2
.link_graph
);
3573 ge1
.link_graph
= lg
->index
;
3574 ge1
.node
= lg
->AddNode(st
);
3576 } else if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3577 lg
= LinkGraph::Get(ge1
.link_graph
);
3578 ge2
.link_graph
= lg
->index
;
3579 ge2
.node
= lg
->AddNode(st2
);
3581 lg
= LinkGraph::Get(ge1
.link_graph
);
3582 if (ge1
.link_graph
!= ge2
.link_graph
) {
3583 LinkGraph
*lg2
= LinkGraph::Get(ge2
.link_graph
);
3584 if (lg
->Size() < lg2
->Size()) {
3585 LinkGraphSchedule::Instance()->Unqueue(lg
);
3586 lg2
->Merge(lg
); // Updates GoodsEntries of lg
3589 LinkGraphSchedule::Instance()->Unqueue(lg2
);
3590 lg
->Merge(lg2
); // Updates GoodsEntries of lg2
3595 (*lg
)[ge1
.node
].UpdateEdge(ge2
.node
, capacity
, usage
);
3600 * Increase capacity for all link stats associated with vehicles in the given consist.
3601 * @param st Station to get the link stats from.
3602 * @param front First vehicle in the consist.
3603 * @param next_station_id Station the consist will be travelling to next.
3605 void IncreaseStats(Station
*st
, const Vehicle
*front
, StationID next_station_id
)
3607 for (const Vehicle
*v
= front
; v
!= NULL
; v
= v
->Next()) {
3608 if (v
->refit_cap
> 0) {
3609 /* The cargo count can indeed be higher than the refit_cap if
3610 * wagons have been auto-replaced and subsequently auto-
3611 * refitted to a higher capacity. The cargo gets redistributed
3612 * among the wagons in that case.
3613 * As usage is not such an important figure anyway we just
3614 * ignore the additional cargo then.*/
3615 IncreaseStats(st
, v
->cargo_type
, next_station_id
, v
->refit_cap
,
3616 min(v
->refit_cap
, v
->cargo
.StoredCount()));
3621 /* called for every station each tick */
3622 static void StationHandleSmallTick(BaseStation
*st
)
3624 if ((st
->facilities
& FACIL_WAYPOINT
) != 0 || !st
->IsInUse()) return;
3626 byte b
= st
->delete_ctr
+ 1;
3627 if (b
>= STATION_RATING_TICKS
) b
= 0;
3630 if (b
== 0) UpdateStationRating(Station::From(st
));
3633 void OnTick_Station()
3635 if (_game_mode
== GM_EDITOR
) return;
3638 FOR_ALL_BASE_STATIONS(st
) {
3639 StationHandleSmallTick(st
);
3641 /* Clean up the link graph about once a week. */
3642 if (Station::IsExpected(st
) && (_tick_counter
+ st
->index
) % STATION_LINKGRAPH_TICKS
== 0) {
3643 DeleteStaleLinks(Station::From(st
));
3646 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3647 * Station index is included so that triggers are not all done
3648 * at the same time. */
3649 if ((_tick_counter
+ st
->index
) % STATION_ACCEPTANCE_TICKS
== 0) {
3650 /* Stop processing this station if it was deleted */
3651 if (!StationHandleBigTick(st
)) continue;
3652 TriggerStationAnimation(st
, st
->xy
, SAT_250_TICKS
);
3653 if (Station::IsExpected(st
)) AirportAnimationTrigger(Station::From(st
), AAT_STATION_250_TICKS
);
3658 /** Monthly loop for stations. */
3659 void StationMonthlyLoop()
3663 FOR_ALL_STATIONS(st
) {
3664 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3665 GoodsEntry
*ge
= &st
->goods
[i
];
3666 SB(ge
->acceptance_pickup
, GoodsEntry::GES_LAST_MONTH
, 1, GB(ge
->acceptance_pickup
, GoodsEntry::GES_CURRENT_MONTH
, 1));
3667 ClrBit(ge
->acceptance_pickup
, GoodsEntry::GES_CURRENT_MONTH
);
3673 void ModifyStationRatingAround(TileIndex tile
, Owner owner
, int amount
, uint radius
)
3677 FOR_ALL_STATIONS(st
) {
3678 if (st
->owner
== owner
&&
3679 DistanceManhattan(tile
, st
->xy
) <= radius
) {
3680 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3681 GoodsEntry
*ge
= &st
->goods
[i
];
3683 if (ge
->acceptance_pickup
!= 0) {
3684 ge
->rating
= Clamp(ge
->rating
+ amount
, 0, 255);
3691 static uint
UpdateStationWaiting(Station
*st
, CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
)
3693 /* We can't allocate a CargoPacket? Then don't do anything
3694 * at all; i.e. just discard the incoming cargo. */
3695 if (!CargoPacket::CanAllocateItem()) return 0;
3697 GoodsEntry
&ge
= st
->goods
[type
];
3698 amount
+= ge
.amount_fract
;
3699 ge
.amount_fract
= GB(amount
, 0, 8);
3702 /* No new "real" cargo item yet. */
3703 if (amount
== 0) return 0;
3705 StationID next
= ge
.GetVia(st
->index
);
3706 ge
.cargo
.Append(new CargoPacket(st
->index
, st
->xy
, amount
, source_type
, source_id
), next
);
3707 LinkGraph
*lg
= NULL
;
3708 if (ge
.link_graph
== INVALID_LINK_GRAPH
) {
3709 if (LinkGraph::CanAllocateItem()) {
3710 lg
= new LinkGraph(type
);
3711 LinkGraphSchedule::Instance()->Queue(lg
);
3712 ge
.link_graph
= lg
->index
;
3713 ge
.node
= lg
->AddNode(st
);
3715 DEBUG(misc
, 0, "Can't allocate link graph");
3718 lg
= LinkGraph::Get(ge
.link_graph
);
3720 if (lg
!= NULL
) (*lg
)[ge
.node
].UpdateSupply(amount
);
3722 if (!ge
.HasRating()) {
3723 InvalidateWindowData(WC_STATION_LIST
, st
->index
);
3724 SetBit(ge
.acceptance_pickup
, GoodsEntry::GES_PICKUP
);
3727 TriggerStationRandomisation(st
, st
->xy
, SRT_NEW_CARGO
, type
);
3728 TriggerStationAnimation(st
, st
->xy
, SAT_NEW_CARGO
, type
);
3729 AirportAnimationTrigger(st
, AAT_STATION_NEW_CARGO
, type
);
3731 SetWindowDirty(WC_STATION_VIEW
, st
->index
);
3732 st
->MarkTilesDirty(true);
3736 static bool IsUniqueStationName(const char *name
)
3740 FOR_ALL_STATIONS(st
) {
3741 if (st
->name
!= NULL
&& strcmp(st
->name
, name
) == 0) return false;
3749 * @param tile unused
3750 * @param flags operation to perform
3751 * @param p1 station ID that is to be renamed
3753 * @param text the new name or an empty string when resetting to the default
3754 * @return the cost of this operation or an error
3756 CommandCost
CmdRenameStation(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
3758 Station
*st
= Station::GetIfValid(p1
);
3759 if (st
== NULL
) return CMD_ERROR
;
3761 CommandCost ret
= CheckOwnership(st
->owner
);
3762 if (ret
.Failed()) return ret
;
3764 bool reset
= StrEmpty(text
);
3767 if (Utf8StringLength(text
) >= MAX_LENGTH_STATION_NAME_CHARS
) return CMD_ERROR
;
3768 if (!IsUniqueStationName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
3771 if (flags
& DC_EXEC
) {
3773 st
->name
= reset
? NULL
: strdup(text
);
3775 st
->UpdateVirtCoord();
3776 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 1);
3779 return CommandCost();
3783 * Find all stations around a rectangular producer (industry, house, headquarter, ...)
3785 * @param location The location/area of the producer
3786 * @param stations The list to store the stations in
3788 void FindStationsAroundTiles(const TileArea
&location
, StationList
*stations
)
3790 /* area to search = producer plus station catchment radius */
3791 uint max_rad
= (_settings_game
.station
.modified_catchment
? MAX_CATCHMENT
: CA_UNMODIFIED
);
3793 uint x
= TileX(location
.tile
);
3794 uint y
= TileY(location
.tile
);
3796 uint min_x
= (x
> max_rad
) ? x
- max_rad
: 0;
3797 uint max_x
= x
+ location
.w
+ max_rad
;
3798 uint min_y
= (y
> max_rad
) ? y
- max_rad
: 0;
3799 uint max_y
= y
+ location
.h
+ max_rad
;
3801 if (min_x
== 0 && _settings_game
.construction
.freeform_edges
) min_x
= 1;
3802 if (min_y
== 0 && _settings_game
.construction
.freeform_edges
) min_y
= 1;
3803 if (max_x
>= MapSizeX()) max_x
= MapSizeX() - 1;
3804 if (max_y
>= MapSizeY()) max_y
= MapSizeY() - 1;
3806 for (uint cy
= min_y
; cy
< max_y
; cy
++) {
3807 for (uint cx
= min_x
; cx
< max_x
; cx
++) {
3808 TileIndex cur_tile
= TileXY(cx
, cy
);
3809 if (!IsStationTile(cur_tile
)) continue;
3811 Station
*st
= Station::GetByTile(cur_tile
);
3812 /* st can be NULL in case of waypoints */
3813 if (st
== NULL
) continue;
3815 if (_settings_game
.station
.modified_catchment
) {
3816 int rad
= st
->GetCatchmentRadius();
3820 if (rad_x
< -rad
|| rad_x
>= rad
+ location
.w
) continue;
3821 if (rad_y
< -rad
|| rad_y
>= rad
+ location
.h
) continue;
3824 /* Insert the station in the set. This will fail if it has
3825 * already been added.
3827 stations
->Include(st
);
3833 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
3834 * @return pointer to a StationList containing all stations found
3836 const StationList
*StationFinder::GetStations()
3838 if (this->tile
!= INVALID_TILE
) {
3839 FindStationsAroundTiles(*this, &this->stations
);
3840 this->tile
= INVALID_TILE
;
3842 return &this->stations
;
3845 uint
MoveGoodsToStation(CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
, const StationList
*all_stations
)
3847 /* Return if nothing to do. Also the rounding below fails for 0. */
3848 if (amount
== 0) return 0;
3850 Station
*st1
= NULL
; // Station with best rating
3851 Station
*st2
= NULL
; // Second best station
3852 uint best_rating1
= 0; // rating of st1
3853 uint best_rating2
= 0; // rating of st2
3855 for (Station
* const *st_iter
= all_stations
->Begin(); st_iter
!= all_stations
->End(); ++st_iter
) {
3856 Station
*st
= *st_iter
;
3858 /* Is the station reserved exclusively for somebody else? */
3859 if (st
->town
->exclusive_counter
> 0 && st
->town
->exclusivity
!= st
->owner
) continue;
3861 if (st
->goods
[type
].rating
== 0) continue; // Lowest possible rating, better not to give cargo anymore
3863 if (_settings_game
.order
.selectgoods
&& !st
->goods
[type
].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
3865 if (IsCargoInClass(type
, CC_PASSENGERS
)) {
3866 if (st
->facilities
== FACIL_TRUCK_STOP
) continue; // passengers are never served by just a truck stop
3868 if (st
->facilities
== FACIL_BUS_STOP
) continue; // non-passengers are never served by just a bus stop
3871 /* This station can be used, add it to st1/st2 */
3872 if (st1
== NULL
|| st
->goods
[type
].rating
>= best_rating1
) {
3873 st2
= st1
; best_rating2
= best_rating1
; st1
= st
; best_rating1
= st
->goods
[type
].rating
;
3874 } else if (st2
== NULL
|| st
->goods
[type
].rating
>= best_rating2
) {
3875 st2
= st
; best_rating2
= st
->goods
[type
].rating
;
3879 /* no stations around at all? */
3880 if (st1
== NULL
) return 0;
3882 /* From now we'll calculate with fractal cargo amounts.
3883 * First determine how much cargo we really have. */
3884 amount
*= best_rating1
+ 1;
3887 /* only one station around */
3888 return UpdateStationWaiting(st1
, type
, amount
, source_type
, source_id
);
3891 /* several stations around, the best two (highest rating) are in st1 and st2 */
3892 assert(st1
!= NULL
);
3893 assert(st2
!= NULL
);
3894 assert(best_rating1
!= 0 || best_rating2
!= 0);
3896 /* Then determine the amount the worst station gets. We do it this way as the
3897 * best should get a bonus, which in this case is the rounding difference from
3898 * this calculation. In reality that will mean the bonus will be pretty low.
3899 * Nevertheless, the best station should always get the most cargo regardless
3900 * of rounding issues. */
3901 uint worst_cargo
= amount
* best_rating2
/ (best_rating1
+ best_rating2
);
3902 assert(worst_cargo
<= (amount
- worst_cargo
));
3904 /* And then send the cargo to the stations! */
3905 uint moved
= UpdateStationWaiting(st1
, type
, amount
- worst_cargo
, source_type
, source_id
);
3906 /* These two UpdateStationWaiting's can't be in the statement as then the order
3907 * of execution would be undefined and that could cause desyncs with callbacks. */
3908 return moved
+ UpdateStationWaiting(st2
, type
, worst_cargo
, source_type
, source_id
);
3911 void BuildOilRig(TileIndex tile
)
3913 if (!Station::CanAllocateItem()) {
3914 DEBUG(misc
, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile
);
3918 if (!Dock::CanAllocateItem()) {
3919 DEBUG(misc
, 0, "Can't allocate dock for oilrig at 0x%X, reverting to oilrig only", tile
);
3923 Station
*st
= new Station(tile
);
3924 st
->town
= ClosestTownFromTile(tile
, UINT_MAX
);
3926 st
->string_id
= GenerateStationName(st
, tile
, STATIONNAMING_OILRIG
);
3928 assert(IsIndustryTile(tile
));
3929 DeleteAnimatedTile(tile
);
3930 MakeOilrig(tile
, st
->index
, GetWaterClass(tile
));
3932 st
->owner
= OWNER_NONE
;
3933 st
->docks
= new Dock(tile
);
3934 st
->dock_area
= TileArea(tile
, 1, 1);
3935 st
->airport
.type
= AT_OILRIG
;
3936 st
->airport
.Add(tile
);
3937 st
->facilities
= FACIL_AIRPORT
| FACIL_DOCK
;
3938 st
->build_date
= _date
;
3940 st
->rect
.BeforeAddTile(tile
, StationRect::ADD_FORCE
);
3942 st
->UpdateVirtCoord();
3943 UpdateStationAcceptance(st
, false);
3944 st
->RecomputeIndustriesNear();
3947 void DeleteOilRig(TileIndex tile
)
3949 Station
*st
= Station::GetByTile(tile
);
3951 MakeWaterKeepingClass(tile
, OWNER_NONE
);
3955 st
->dock_area
.Clear();
3956 st
->airport
.Clear();
3957 st
->facilities
&= ~(FACIL_AIRPORT
| FACIL_DOCK
);
3958 st
->airport
.flags
= 0;
3960 st
->rect
.AfterRemoveTile(st
, tile
);
3962 st
->UpdateVirtCoord();
3963 st
->RecomputeIndustriesNear();
3964 if (!st
->IsInUse()) delete st
;
3967 static void ChangeTileOwner_Station(TileIndex tile
, Owner old_owner
, Owner new_owner
)
3969 if (IsRoadStopTile(tile
)) {
3970 for (RoadType rt
= ROADTYPE_ROAD
; rt
< ROADTYPE_END
; rt
++) {
3971 /* Update all roadtypes, no matter if they are present */
3972 if (GetRoadOwner(tile
, rt
) == old_owner
) {
3973 if (HasTileRoadType(tile
, rt
)) {
3974 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
3975 Company::Get(old_owner
)->infrastructure
.road
[rt
] -= 2;
3976 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.road
[rt
] += 2;
3978 SetRoadOwner(tile
, rt
, new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
);
3983 if (!IsTileOwner(tile
, old_owner
)) return;
3985 if (new_owner
!= INVALID_OWNER
) {
3986 /* Update company infrastructure counts. Only do it here
3987 * if the new owner is valid as otherwise the clear
3988 * command will do it for us. No need to dirty windows
3989 * here, we'll redraw the whole screen anyway.*/
3990 Company
*old_company
= Company::Get(old_owner
);
3991 Company
*new_company
= Company::Get(new_owner
);
3993 /* Update counts for underlying infrastructure. */
3994 switch (GetStationType(tile
)) {
3996 case STATION_WAYPOINT
:
3997 if (!IsStationTileBlocked(tile
)) {
3998 old_company
->infrastructure
.rail
[GetRailType(tile
)]--;
3999 new_company
->infrastructure
.rail
[GetRailType(tile
)]++;
4005 /* Road stops were already handled above. */
4010 if (GetWaterClass(tile
) == WATER_CLASS_CANAL
) {
4011 old_company
->infrastructure
.water
--;
4012 new_company
->infrastructure
.water
++;
4020 /* Update station tile count. */
4021 if (!IsBuoy(tile
) && !IsAirport(tile
)) {
4022 old_company
->infrastructure
.station
--;
4023 new_company
->infrastructure
.station
++;
4026 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4027 SetTileOwner(tile
, new_owner
);
4028 InvalidateWindowClassesData(WC_STATION_LIST
, 0);
4030 if (IsDriveThroughStopTile(tile
)) {
4031 /* Remove the drive-through road stop */
4032 DoCommand(tile
, 1 | 1 << 8, (GetStationType(tile
) == STATION_TRUCK
) ? ROADSTOP_TRUCK
: ROADSTOP_BUS
, DC_EXEC
| DC_BANKRUPT
, CMD_REMOVE_ROAD_STOP
);
4033 assert(IsNormalRoadTile(tile
));
4034 /* Change owner of tile and all roadtypes */
4035 ChangeTileOwner(tile
, old_owner
, new_owner
);
4037 DoCommand(tile
, 0, 0, DC_EXEC
| DC_BANKRUPT
, CMD_LANDSCAPE_CLEAR
);
4038 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4039 * Update owner of buoy if it was not removed (was in orders).
4040 * Do not update when owned by OWNER_WATER (sea and rivers). */
4041 if ((IsWaterTile(tile
) || IsBuoyTile(tile
)) && IsTileOwner(tile
, old_owner
)) SetTileOwner(tile
, OWNER_NONE
);
4047 * Check if a drive-through road stop tile can be cleared.
4048 * Road stops built on town-owned roads check the conditions
4049 * that would allow clearing of the original road.
4050 * @param tile road stop tile to check
4051 * @param flags command flags
4052 * @return true if the road can be cleared
4054 static bool CanRemoveRoadWithStop(TileIndex tile
, DoCommandFlag flags
)
4056 /* Yeah... water can always remove stops, right? */
4057 if (_current_company
== OWNER_WATER
) return true;
4059 RoadTypes rts
= GetRoadTypes(tile
);
4060 if (HasBit(rts
, ROADTYPE_TRAM
)) {
4061 Owner tram_owner
= GetRoadOwner(tile
, ROADTYPE_TRAM
);
4062 if (tram_owner
!= OWNER_NONE
&& CheckOwnership(tram_owner
).Failed()) return false;
4064 if (HasBit(rts
, ROADTYPE_ROAD
)) {
4065 Owner road_owner
= GetRoadOwner(tile
, ROADTYPE_ROAD
);
4066 if (road_owner
!= OWNER_TOWN
) {
4067 if (road_owner
!= OWNER_NONE
&& CheckOwnership(road_owner
).Failed()) return false;
4069 if (CheckAllowRemoveRoad(tile
, GetAnyRoadBits(tile
, ROADTYPE_ROAD
), OWNER_TOWN
, ROADTYPE_ROAD
, flags
).Failed()) return false;
4077 * Clear a single tile of a station.
4078 * @param tile The tile to clear.
4079 * @param flags The DoCommand flags related to the "command".
4080 * @return The cost, or error of clearing.
4082 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
)
4084 if (flags
& DC_AUTO
) {
4085 switch (GetStationType(tile
)) {
4087 case STATION_RAIL
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD
);
4088 case STATION_WAYPOINT
: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
4089 case STATION_AIRPORT
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
4090 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
);
4091 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
);
4092 case STATION_BUOY
: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY
);
4093 case STATION_DOCK
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST
);
4094 case STATION_OILRIG
:
4095 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG
);
4096 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY
);
4100 switch (GetStationType(tile
)) {
4101 case STATION_RAIL
: return RemoveRailStation(tile
, flags
);
4102 case STATION_WAYPOINT
: return RemoveRailWaypoint(tile
, flags
);
4103 case STATION_AIRPORT
: return RemoveAirport(tile
, flags
);
4105 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4106 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST
);
4108 return RemoveRoadStop(tile
, flags
);
4110 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4111 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST
);
4113 return RemoveRoadStop(tile
, flags
);
4114 case STATION_BUOY
: return RemoveBuoy(tile
, flags
);
4115 case STATION_DOCK
: return RemoveDock(tile
, flags
);
4122 static CommandCost
TerraformTile_Station(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
4124 if (_settings_game
.construction
.build_on_slopes
&& AutoslopeEnabled()) {
4125 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4126 * TTDP does not call it.
4128 if (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
)) {
4129 switch (GetStationType(tile
)) {
4130 case STATION_WAYPOINT
:
4131 case STATION_RAIL
: {
4132 DiagDirection direction
= AxisToDiagDir(GetRailStationAxis(tile
));
4133 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4134 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4135 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4138 case STATION_AIRPORT
:
4139 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4143 DiagDirection direction
= GetRoadStopDir(tile
);
4144 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4145 if (IsDriveThroughStopTile(tile
)) {
4146 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4148 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4155 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
4159 * Get flow for a station.
4160 * @param st Station to get flow for.
4161 * @return Flow for st.
4163 uint
FlowStat::GetShare(StationID st
) const
4166 for (SharesMap::const_iterator it
= this->shares
.begin(); it
!= this->shares
.end(); ++it
) {
4167 if (it
->second
== st
) {
4168 return it
->first
- prev
;
4177 * Get a station a package can be routed to, but exclude the given ones.
4178 * @param excluded StationID not to be selected.
4179 * @param excluded2 Another StationID not to be selected.
4180 * @return A station ID from the shares map.
4182 StationID
FlowStat::GetVia(StationID excluded
, StationID excluded2
) const
4184 if (this->unrestricted
== 0) return INVALID_STATION
;
4185 assert(!this->shares
.empty());
4186 SharesMap::const_iterator it
= this->shares
.upper_bound(RandomRange(this->unrestricted
));
4187 assert(it
!= this->shares
.end() && it
->first
<= this->unrestricted
);
4188 if (it
->second
!= excluded
&& it
->second
!= excluded2
) return it
->second
;
4190 /* We've hit one of the excluded stations.
4191 * Draw another share, from outside its range. */
4193 uint end
= it
->first
;
4194 uint begin
= (it
== this->shares
.begin() ? 0 : (--it
)->first
);
4195 uint interval
= end
- begin
;
4196 if (interval
>= this->unrestricted
) return INVALID_STATION
; // Only one station in the map.
4197 uint new_max
= this->unrestricted
- interval
;
4198 uint rand
= RandomRange(new_max
);
4199 SharesMap::const_iterator it2
= (rand
< begin
) ? this->shares
.upper_bound(rand
) :
4200 this->shares
.upper_bound(rand
+ interval
);
4201 assert(it2
!= this->shares
.end() && it2
->first
<= this->unrestricted
);
4202 if (it2
->second
!= excluded
&& it2
->second
!= excluded2
) return it2
->second
;
4204 /* We've hit the second excluded station.
4205 * Same as before, only a bit more complicated. */
4207 uint end2
= it2
->first
;
4208 uint begin2
= (it2
== this->shares
.begin() ? 0 : (--it2
)->first
);
4209 uint interval2
= end2
- begin2
;
4210 if (interval2
>= new_max
) return INVALID_STATION
; // Only the two excluded stations in the map.
4211 new_max
-= interval2
;
4212 if (begin
> begin2
) {
4213 Swap(begin
, begin2
);
4215 Swap(interval
, interval2
);
4217 rand
= RandomRange(new_max
);
4218 SharesMap::const_iterator it3
= this->shares
.upper_bound(this->unrestricted
);
4220 it3
= this->shares
.upper_bound(rand
);
4221 } else if (rand
< begin2
- interval
) {
4222 it3
= this->shares
.upper_bound(rand
+ interval
);
4224 it3
= this->shares
.upper_bound(rand
+ interval
+ interval2
);
4226 assert(it3
!= this->shares
.end() && it3
->first
<= this->unrestricted
);
4231 * Reduce all flows to minimum capacity so that they don't get in the way of
4232 * link usage statistics too much. Keep them around, though, to continue
4233 * routing any remaining cargo.
4235 void FlowStat::Invalidate()
4237 assert(!this->shares
.empty());
4238 SharesMap new_shares
;
4240 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4241 new_shares
[++i
] = it
->second
;
4242 if (it
->first
== this->unrestricted
) this->unrestricted
= i
;
4244 this->shares
.swap(new_shares
);
4245 assert(!this->shares
.empty() && this->unrestricted
<= (--this->shares
.end())->first
);
4249 * Change share for specified station. By specifing INT_MIN as parameter you
4250 * can erase a share. Newly added flows will be unrestricted.
4251 * @param st Next Hop to be removed.
4252 * @param flow Share to be added or removed.
4254 void FlowStat::ChangeShare(StationID st
, int flow
)
4256 /* We assert only before changing as afterwards the shares can actually
4257 * be empty. In that case the whole flow stat must be deleted then. */
4258 assert(!this->shares
.empty());
4260 uint removed_shares
= 0;
4261 uint added_shares
= 0;
4262 uint last_share
= 0;
4263 SharesMap new_shares
;
4264 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4265 if (it
->second
== st
) {
4267 uint share
= it
->first
- last_share
;
4268 if (flow
== INT_MIN
|| (uint
)(-flow
) >= share
) {
4269 removed_shares
+= share
;
4270 if (it
->first
<= this->unrestricted
) this->unrestricted
-= share
;
4271 if (flow
!= INT_MIN
) flow
+= share
;
4272 last_share
= it
->first
;
4273 continue; // remove the whole share
4275 removed_shares
+= (uint
)(-flow
);
4277 added_shares
+= (uint
)(flow
);
4279 if (it
->first
<= this->unrestricted
) this->unrestricted
+= flow
;
4281 /* If we don't continue above the whole flow has been added or
4285 new_shares
[it
->first
+ added_shares
- removed_shares
] = it
->second
;
4286 last_share
= it
->first
;
4289 new_shares
[last_share
+ (uint
)flow
] = st
;
4290 if (this->unrestricted
< last_share
) {
4291 this->ReleaseShare(st
);
4293 this->unrestricted
+= flow
;
4296 this->shares
.swap(new_shares
);
4300 * Restrict a flow by moving it to the end of the map and decreasing the amount
4301 * of unrestricted flow.
4302 * @param st Station of flow to be restricted.
4304 void FlowStat::RestrictShare(StationID st
)
4306 assert(!this->shares
.empty());
4308 uint last_share
= 0;
4309 SharesMap new_shares
;
4310 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4312 if (it
->first
> this->unrestricted
) return; // Not present or already restricted.
4313 if (it
->second
== st
) {
4314 flow
= it
->first
- last_share
;
4315 this->unrestricted
-= flow
;
4317 new_shares
[it
->first
] = it
->second
;
4320 new_shares
[it
->first
- flow
] = it
->second
;
4322 last_share
= it
->first
;
4324 if (flow
== 0) return;
4325 new_shares
[last_share
+ flow
] = st
;
4326 this->shares
.swap(new_shares
);
4327 assert(!this->shares
.empty());
4331 * Release ("unrestrict") a flow by moving it to the begin of the map and
4332 * increasing the amount of unrestricted flow.
4333 * @param st Station of flow to be released.
4335 void FlowStat::ReleaseShare(StationID st
)
4337 assert(!this->shares
.empty());
4339 uint next_share
= 0;
4341 for (SharesMap::reverse_iterator
it(this->shares
.rbegin()); it
!= this->shares
.rend(); ++it
) {
4342 if (it
->first
< this->unrestricted
) return; // Note: not <= as the share may hit the limit.
4344 flow
= next_share
- it
->first
;
4345 this->unrestricted
+= flow
;
4348 if (it
->first
== this->unrestricted
) return; // !found -> Limit not hit.
4349 if (it
->second
== st
) found
= true;
4351 next_share
= it
->first
;
4353 if (flow
== 0) return;
4354 SharesMap new_shares
;
4355 new_shares
[flow
] = st
;
4356 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4357 if (it
->second
!= st
) {
4358 new_shares
[flow
+ it
->first
] = it
->second
;
4363 this->shares
.swap(new_shares
);
4364 assert(!this->shares
.empty());
4368 * Add some flow from "origin", going via "via".
4369 * @param origin Origin of the flow.
4370 * @param via Next hop.
4371 * @param flow Amount of flow to be added.
4373 void FlowStatMap::AddFlow(StationID origin
, StationID via
, uint flow
)
4375 FlowStatMap::iterator origin_it
= this->find(origin
);
4376 if (origin_it
== this->end()) {
4377 this->insert(std::make_pair(origin
, FlowStat(via
, flow
)));
4379 origin_it
->second
.ChangeShare(via
, flow
);
4380 assert(!origin_it
->second
.GetShares()->empty());
4385 * Pass on some flow, remembering it as invalid, for later subtraction from
4386 * locally consumed flow. This is necessary because we can't have negative
4387 * flows and we don't want to sort the flows before adding them up.
4388 * @param origin Origin of the flow.
4389 * @param via Next hop.
4390 * @param flow Amount of flow to be passed.
4392 void FlowStatMap::PassOnFlow(StationID origin
, StationID via
, uint flow
)
4394 FlowStatMap::iterator prev_it
= this->find(origin
);
4395 if (prev_it
== this->end()) {
4396 FlowStat
fs(via
, flow
);
4397 fs
.AppendShare(INVALID_STATION
, flow
);
4398 this->insert(std::make_pair(origin
, fs
));
4400 prev_it
->second
.ChangeShare(via
, flow
);
4401 prev_it
->second
.ChangeShare(INVALID_STATION
, flow
);
4402 assert(!prev_it
->second
.GetShares()->empty());
4407 * Subtract invalid flows from locally consumed flow.
4408 * @param self ID of own station.
4410 void FlowStatMap::FinalizeLocalConsumption(StationID self
)
4412 for (FlowStatMap::iterator i
= this->begin(); i
!= this->end(); ++i
) {
4413 FlowStat
&fs
= i
->second
;
4414 uint local
= fs
.GetShare(INVALID_STATION
);
4415 if (local
> INT_MAX
) { // make sure it fits in an int
4416 fs
.ChangeShare(self
, -INT_MAX
);
4417 fs
.ChangeShare(INVALID_STATION
, -INT_MAX
);
4420 fs
.ChangeShare(self
, -(int)local
);
4421 fs
.ChangeShare(INVALID_STATION
, -(int)local
);
4423 /* If the local share is used up there must be a share for some
4424 * remote station. */
4425 assert(!fs
.GetShares()->empty());
4430 * Delete all flows at a station for specific cargo and destination.
4431 * @param via Remote station of flows to be deleted.
4432 * @return IDs of source stations for which the complete FlowStat, not only a
4433 * share, has been erased.
4435 StationIDStack
FlowStatMap::DeleteFlows(StationID via
)
4438 for (FlowStatMap::iterator f_it
= this->begin(); f_it
!= this->end();) {
4439 FlowStat
&s_flows
= f_it
->second
;
4440 s_flows
.ChangeShare(via
, INT_MIN
);
4441 if (s_flows
.GetShares()->empty()) {
4442 ret
.Push(f_it
->first
);
4443 this->erase(f_it
++);
4452 * Restrict all flows at a station for specific cargo and destination.
4453 * @param via Remote station of flows to be restricted.
4455 void FlowStatMap::RestrictFlows(StationID via
)
4457 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4458 it
->second
.RestrictShare(via
);
4463 * Release all flows at a station for specific cargo and destination.
4464 * @param via Remote station of flows to be released.
4466 void FlowStatMap::ReleaseFlows(StationID via
)
4468 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4469 it
->second
.ReleaseShare(via
);
4474 * Get the sum of flows via a specific station from this GoodsEntry.
4475 * @param via Remote station to look for.
4476 * @return a FlowStat with all flows for 'via' added up.
4478 uint
GoodsEntry::GetSumFlowVia(StationID via
) const
4481 for (FlowStatMap::const_iterator i
= this->flows
.begin(); i
!= this->flows
.end(); ++i
) {
4482 ret
+= i
->second
.GetShare(via
);
4487 extern const TileTypeProcs _tile_type_station_procs
= {
4488 DrawTile_Station
, // draw_tile_proc
4489 GetSlopePixelZ_Station
, // get_slope_z_proc
4490 ClearTile_Station
, // clear_tile_proc
4491 NULL
, // add_accepted_cargo_proc
4492 GetTileDesc_Station
, // get_tile_desc_proc
4493 GetTileRailwayStatus_Station
, // get_tile_railway_status_proc
4494 GetTileRoadStatus_Station
, // get_tile_road_status_proc
4495 GetTileWaterwayStatus_Station
, // get_tile_waterway_status_proc
4496 ClickTile_Station
, // click_tile_proc
4497 AnimateTile_Station
, // animate_tile_proc
4498 TileLoop_Station
, // tile_loop_proc
4499 ChangeTileOwner_Station
, // change_tile_owner_proc
4500 NULL
, // add_produced_cargo_proc
4501 GetFoundation_Station
, // get_foundation_proc
4502 TerraformTile_Station
, // terraform_tile_proc