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.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;
221 StringID name
= GetIndustrySpec(s
->indtype
)->station_name
;
222 if (name
!= STR_UNDEFINED
) {
223 /* Filter for other industrytypes with the same name */
224 for (IndustryType it
= 0; it
< NUM_INDUSTRYTYPES
; it
++) {
225 const IndustrySpec
*indsp
= GetIndustrySpec(it
);
226 if (indsp
->enabled
&& indsp
->station_name
== name
) indtypes
[it
] = true;
231 uint str
= M(s
->string_id
);
233 if (str
== M(STR_SV_STNAME_FOREST
)) {
234 str
= M(STR_SV_STNAME_WOODS
);
236 ClrBit(free_names
, str
);
241 TileIndex indtile
= tile
;
242 StationNameInformation sni
= { free_names
, indtypes
};
243 if (CircularTileSearch(&indtile
, 7, FindNearIndustryName
, &sni
)) {
244 /* An industry has been found nearby */
245 IndustryType indtype
= GetIndustryType(indtile
);
246 const IndustrySpec
*indsp
= GetIndustrySpec(indtype
);
247 /* STR_NULL means it only disables oil rig/mines */
248 if (indsp
->station_name
!= STR_NULL
) {
249 st
->indtype
= indtype
;
250 return STR_SV_STNAME_FALLBACK
;
254 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
255 free_names
= sni
.free_names
;
257 /* check default names */
258 uint32 tmp
= free_names
& _gen_station_name_bits
[name_class
];
259 if (tmp
!= 0) return STR_SV_STNAME
+ FindFirstBit(tmp
);
262 if (HasBit(free_names
, M(STR_SV_STNAME_MINES
))) {
263 if (CountMapSquareAround(tile
, CMSAMine
) >= 2) {
264 return STR_SV_STNAME_MINES
;
268 /* check close enough to town to get central as name? */
269 if (DistanceMax(tile
, t
->xy
) < 8) {
270 if (HasBit(free_names
, M(STR_SV_STNAME
))) return STR_SV_STNAME
;
272 if (HasBit(free_names
, M(STR_SV_STNAME_CENTRAL
))) return STR_SV_STNAME_CENTRAL
;
276 if (HasBit(free_names
, M(STR_SV_STNAME_LAKESIDE
)) &&
277 DistanceFromEdge(tile
) < 20 &&
278 CountMapSquareAround(tile
, CMSAWater
) >= 5) {
279 return STR_SV_STNAME_LAKESIDE
;
283 if (HasBit(free_names
, M(STR_SV_STNAME_WOODS
)) && (
284 CountMapSquareAround(tile
, CMSATree
) >= 8 ||
285 CountMapSquareAround(tile
, IsTileForestIndustry
) >= 2)
287 return _settings_game
.game_creation
.landscape
== LT_TROPIC
? STR_SV_STNAME_FOREST
: STR_SV_STNAME_WOODS
;
290 /* check elevation compared to town */
291 int z
= GetTileZ(tile
);
292 int z2
= GetTileZ(t
->xy
);
294 if (HasBit(free_names
, M(STR_SV_STNAME_VALLEY
))) return STR_SV_STNAME_VALLEY
;
296 if (HasBit(free_names
, M(STR_SV_STNAME_HEIGHTS
))) return STR_SV_STNAME_HEIGHTS
;
299 /* check direction compared to town */
300 static const int8 _direction_and_table
[] = {
301 ~( (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
302 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
303 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
304 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) ),
307 free_names
&= _direction_and_table
[
308 (TileX(tile
) < TileX(t
->xy
)) +
309 (TileY(tile
) < TileY(t
->xy
)) * 2];
311 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));
312 return (tmp
== 0) ? STR_SV_STNAME_FALLBACK
: (STR_SV_STNAME
+ FindFirstBit(tmp
));
317 * Find the closest deleted station of the current company
318 * @param tile the tile to search from.
319 * @return the closest station or NULL if too far.
321 static Station
*GetClosestDeletedStation(TileIndex tile
)
324 Station
*best_station
= NULL
;
327 FOR_ALL_STATIONS(st
) {
328 if (!st
->IsInUse() && st
->owner
== _current_company
) {
329 uint cur_dist
= DistanceManhattan(tile
, st
->xy
);
331 if (cur_dist
< threshold
) {
332 threshold
= cur_dist
;
342 void Station::GetTileArea(TileArea
*ta
, StationType type
) const
346 *ta
= this->train_station
;
349 case STATION_AIRPORT
:
354 *ta
= this->truck_station
;
358 *ta
= this->bus_station
;
363 *ta
= this->dock_area
;
366 default: NOT_REACHED();
374 * Update the virtual coords needed to draw the station sign.
376 void Station::UpdateVirtCoord()
378 Point pt
= RemapCoords2(TileX(this->xy
) * TILE_SIZE
, TileY(this->xy
) * TILE_SIZE
);
380 pt
.y
-= 32 * ZOOM_LVL_BASE
;
381 if ((this->facilities
& FACIL_AIRPORT
) && this->airport
.type
== AT_OILRIG
) pt
.y
-= 16 * ZOOM_LVL_BASE
;
383 SetDParam(0, this->index
);
384 SetDParam(1, this->facilities
);
385 this->sign
.UpdatePosition(pt
.x
, pt
.y
, STR_VIEWPORT_STATION
);
387 SetWindowDirty(WC_STATION_VIEW
, this->index
);
390 /** Update the virtual coords needed to draw the station sign for all stations. */
391 void UpdateAllStationVirtCoords()
395 FOR_ALL_BASE_STATIONS(st
) {
396 st
->UpdateVirtCoord();
401 * Get a mask of the cargo types that the station accepts.
402 * @param st Station to query
403 * @return the expected mask
405 static uint
GetAcceptanceMask(const Station
*st
)
409 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
410 if (HasBit(st
->goods
[i
].acceptance_pickup
, GoodsEntry::GES_ACCEPTANCE
)) mask
|= 1 << i
;
416 * Items contains the two cargo names that are to be accepted or rejected.
417 * msg is the string id of the message to display.
419 static void ShowRejectOrAcceptNews(const Station
*st
, uint num_items
, CargoID
*cargo
, StringID msg
)
421 for (uint i
= 0; i
< num_items
; i
++) {
422 SetDParam(i
+ 1, CargoSpec::Get(cargo
[i
])->name
);
425 SetDParam(0, st
->index
);
426 AddNewsItem(msg
, NT_ACCEPTANCE
, NF_INCOLOUR
| NF_SMALL
, NR_STATION
, st
->index
);
430 * Get the cargo types being produced around the tile (in a rectangle).
431 * @param tile Northtile of area
432 * @param w X extent of the area
433 * @param h Y extent of the area
434 * @param rad Search radius in addition to the given area
436 CargoArray
GetProductionAroundTiles(TileIndex tile
, int w
, int h
, int rad
)
443 /* expand the region by rad tiles on each side
444 * while making sure that we remain inside the board. */
445 int x2
= min(x
+ w
+ rad
, MapSizeX());
446 int x1
= max(x
- rad
, 0);
448 int y2
= min(y
+ h
+ rad
, MapSizeY());
449 int y1
= max(y
- rad
, 0);
456 TileArea
ta(TileXY(x1
, y1
), TileXY(x2
- 1, y2
- 1));
458 /* Loop over all tiles to get the produced cargo of
459 * everything except industries */
460 TILE_AREA_LOOP(tile
, ta
) AddProducedCargo(tile
, produced
);
462 /* Loop over the industries. They produce cargo for
463 * anything that is within 'rad' from their bounding
464 * box. As such if you have e.g. a oil well the tile
465 * area loop might not hit an industry tile while
466 * the industry would produce cargo for the station.
469 FOR_ALL_INDUSTRIES(i
) {
470 if (!ta
.Intersects(i
->location
)) continue;
472 for (uint j
= 0; j
< lengthof(i
->produced_cargo
); j
++) {
473 CargoID cargo
= i
->produced_cargo
[j
];
474 if (cargo
!= CT_INVALID
) produced
[cargo
]++;
482 * Get the acceptance of cargoes around the tile in 1/8.
483 * @param tile Center of the search area
484 * @param w X extent of area
485 * @param h Y extent of area
486 * @param rad Search radius in addition to given area
487 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be NULL
489 CargoArray
GetAcceptanceAroundTiles(TileIndex tile
, int w
, int h
, int rad
, uint32
*always_accepted
)
491 CargoArray acceptance
;
492 if (always_accepted
!= NULL
) *always_accepted
= 0;
497 /* expand the region by rad tiles on each side
498 * while making sure that we remain inside the board. */
499 int x2
= min(x
+ w
+ rad
, MapSizeX());
500 int y2
= min(y
+ h
+ rad
, MapSizeY());
501 int x1
= max(x
- rad
, 0);
502 int y1
= max(y
- rad
, 0);
509 for (int yc
= y1
; yc
!= y2
; yc
++) {
510 for (int xc
= x1
; xc
!= x2
; xc
++) {
511 TileIndex tile
= TileXY(xc
, yc
);
512 AddAcceptedCargo(tile
, acceptance
, always_accepted
);
520 * Update the acceptance for a station.
521 * @param st Station to update
522 * @param show_msg controls whether to display a message that acceptance was changed.
524 void UpdateStationAcceptance(Station
*st
, bool show_msg
)
526 /* old accepted goods types */
527 uint old_acc
= GetAcceptanceMask(st
);
529 /* And retrieve the acceptance. */
530 CargoArray acceptance
;
531 if (!st
->rect
.IsEmpty()) {
532 acceptance
= GetAcceptanceAroundTiles(
533 TileXY(st
->rect
.left
, st
->rect
.top
),
534 st
->rect
.right
- st
->rect
.left
+ 1,
535 st
->rect
.bottom
- st
->rect
.top
+ 1,
536 st
->GetCatchmentRadius(),
541 /* Adjust in case our station only accepts fewer kinds of goods */
542 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
543 uint amt
= acceptance
[i
];
545 /* Make sure the station can accept the goods type. */
546 bool is_passengers
= IsCargoInClass(i
, CC_PASSENGERS
);
547 if ((!is_passengers
&& !(st
->facilities
& ~FACIL_BUS_STOP
)) ||
548 (is_passengers
&& !(st
->facilities
& ~FACIL_TRUCK_STOP
))) {
552 GoodsEntry
&ge
= st
->goods
[i
];
553 SB(ge
.acceptance_pickup
, GoodsEntry::GES_ACCEPTANCE
, 1, amt
>= 8);
554 if (LinkGraph::IsValidID(ge
.link_graph
)) {
555 (*LinkGraph::Get(ge
.link_graph
))[ge
.node
].SetDemand(amt
/ 8);
559 /* Only show a message in case the acceptance was actually changed. */
560 uint new_acc
= GetAcceptanceMask(st
);
561 if (old_acc
== new_acc
) return;
563 /* show a message to report that the acceptance was changed? */
564 if (show_msg
&& st
->owner
== _local_company
&& st
->IsInUse()) {
565 /* List of accept and reject strings for different number of
567 static const StringID accept_msg
[] = {
568 STR_NEWS_STATION_NOW_ACCEPTS_CARGO
,
569 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO
,
571 static const StringID reject_msg
[] = {
572 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO
,
573 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO
,
576 /* Array of accepted and rejected cargo types */
577 CargoID accepts
[2] = { CT_INVALID
, CT_INVALID
};
578 CargoID rejects
[2] = { CT_INVALID
, CT_INVALID
};
582 /* Test each cargo type to see if its acceptance has changed */
583 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
584 if (HasBit(new_acc
, i
)) {
585 if (!HasBit(old_acc
, i
) && num_acc
< lengthof(accepts
)) {
586 /* New cargo is accepted */
587 accepts
[num_acc
++] = i
;
590 if (HasBit(old_acc
, i
) && num_rej
< lengthof(rejects
)) {
591 /* Old cargo is no longer accepted */
592 rejects
[num_rej
++] = i
;
597 /* Show news message if there are any changes */
598 if (num_acc
> 0) ShowRejectOrAcceptNews(st
, num_acc
, accepts
, accept_msg
[num_acc
- 1]);
599 if (num_rej
> 0) ShowRejectOrAcceptNews(st
, num_rej
, rejects
, reject_msg
[num_rej
- 1]);
602 /* redraw the station view since acceptance changed */
603 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ACCEPT_RATING_LIST
);
606 static void UpdateStationSignCoord(BaseStation
*st
)
608 const StationRect
*r
= &st
->rect
;
610 if (r
->IsEmpty()) return; // no tiles belong to this station
612 /* clamp sign coord to be inside the station rect */
613 st
->xy
= TileXY(ClampU(TileX(st
->xy
), r
->left
, r
->right
), ClampU(TileY(st
->xy
), r
->top
, r
->bottom
));
614 st
->UpdateVirtCoord();
618 * Common part of building various station parts and possibly attaching them to an existing one.
619 * @param [in,out] st Station to attach to
620 * @param flags Command flags
621 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
622 * @param area Area occupied by the new part
623 * @param name_class Station naming class to use to generate the new station's name
624 * @return Command error that occured, if any
626 static CommandCost
BuildStationPart(Station
**st
, DoCommandFlag flags
, bool reuse
, TileArea area
, StationNaming name_class
)
628 /* Find a deleted station close to us */
629 if (*st
== NULL
&& reuse
) *st
= GetClosestDeletedStation(area
.tile
);
632 if ((*st
)->owner
!= _current_company
) {
633 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION
);
636 CommandCost ret
= (*st
)->rect
.BeforeAddRect(area
.tile
, area
.w
, area
.h
, StationRect::ADD_TEST
);
637 if (ret
.Failed()) return ret
;
639 /* allocate and initialize new station */
640 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING
);
642 if (flags
& DC_EXEC
) {
643 *st
= new Station(area
.tile
);
645 (*st
)->town
= ClosestTownFromTile(area
.tile
, UINT_MAX
);
646 (*st
)->string_id
= GenerateStationName(*st
, area
.tile
, name_class
);
648 if (Company::IsValidID(_current_company
)) {
649 SetBit((*st
)->town
->have_ratings
, _current_company
);
653 return CommandCost();
657 * This is called right after a station was deleted.
658 * It checks if the whole station is free of substations, and if so, the station will be
659 * deleted after a little while.
662 static void DeleteStationIfEmpty(BaseStation
*st
)
664 if (!st
->IsInUse()) {
666 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
668 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
669 UpdateStationSignCoord(st
);
672 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
);
675 * Checks if the given tile is buildable, flat and has a certain height.
676 * @param tile TileIndex to check.
677 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
678 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
679 * @param allow_steep Whether steep slopes are allowed.
680 * @param check_bridge Check for the existence of a bridge.
681 * @return The cost in case of success, or an error code if it failed.
683 CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
= true)
685 if (check_bridge
&& HasBridgeAbove(tile
)) {
686 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
689 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
690 if (ret
.Failed()) return ret
;
693 Slope tileh
= GetTileSlope(tile
, &z
);
695 /* Prohibit building if
696 * 1) The tile is "steep" (i.e. stretches two height levels).
697 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
699 if ((!allow_steep
&& IsSteepSlope(tileh
)) ||
700 ((!_settings_game
.construction
.build_on_slopes
) && tileh
!= SLOPE_FLAT
)) {
701 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
704 CommandCost
cost(EXPENSES_CONSTRUCTION
);
705 int flat_z
= z
+ GetSlopeMaxZ(tileh
);
706 if (tileh
!= SLOPE_FLAT
) {
707 /* Forbid building if the tile faces a slope in a invalid direction. */
708 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
!= DIAGDIR_END
; dir
++) {
709 if (HasBit(invalid_dirs
, dir
) && !CanBuildDepotByTileh(dir
, tileh
)) {
710 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
713 cost
.AddCost(_price
[PR_BUILD_FOUNDATION
]);
716 /* The level of this tile must be equal to allowed_z. */
720 } else if (allowed_z
!= flat_z
) {
721 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
728 * Tries to clear the given area.
729 * @param tile_area Area to check.
730 * @param flags Operation to perform.
731 * @return The cost in case of success, or an error code if it failed.
733 CommandCost
CheckFlatLand(TileArea tile_area
, DoCommandFlag flags
)
735 CommandCost
cost(EXPENSES_CONSTRUCTION
);
738 TILE_AREA_LOOP(tile_cur
, tile_area
) {
739 CommandCost ret
= CheckBuildableTile(tile_cur
, 0, allowed_z
, true);
740 if (ret
.Failed()) return ret
;
743 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
744 if (ret
.Failed()) return ret
;
752 * Checks if a rail station can be built at the given area.
753 * @param tile_area Area to check.
754 * @param flags Operation to perform.
755 * @param axis Rail station axis.
756 * @param station StationID to be queried and returned if available.
757 * @param rt The rail type to check for (overbuilding rail stations over rail).
758 * @param affected_vehicles List of trains with PBS reservations on the tiles
759 * @param spec_class Station class.
760 * @param spec_index Index into the station class.
761 * @param plat_len Platform length.
762 * @param numtracks Number of platforms.
763 * @return The cost in case of success, or an error code if it failed.
765 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
)
767 CommandCost
cost(EXPENSES_CONSTRUCTION
);
769 uint invalid_dirs
= 5 << axis
;
771 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
772 bool slope_cb
= statspec
!= NULL
&& HasBit(statspec
->callback_mask
, CBM_STATION_SLOPE_CHECK
);
774 TILE_AREA_LOOP(tile_cur
, tile_area
) {
775 CommandCost ret
= CheckBuildableTile(tile_cur
, invalid_dirs
, allowed_z
, false);
776 if (ret
.Failed()) return ret
;
780 /* Do slope check if requested. */
781 ret
= PerformStationTileSlopeCheck(tile_area
.tile
, tile_cur
, statspec
, axis
, plat_len
, numtracks
);
782 if (ret
.Failed()) return ret
;
785 /* if station is set, then we have special handling to allow building on top of already existing stations.
786 * so station points to INVALID_STATION if we can build on any station.
787 * Or it points to a station if we're only allowed to build on exactly that station. */
788 if (station
!= NULL
&& IsStationTile(tile_cur
)) {
789 if (!IsRailStation(tile_cur
)) {
790 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
792 StationID st
= GetStationIndex(tile_cur
);
793 if (*station
== INVALID_STATION
) {
795 } else if (*station
!= st
) {
796 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
800 /* Rail type is only valid when building a railway station; if station to
801 * build isn't a rail station it's INVALID_RAILTYPE. */
802 if (rt
!= INVALID_RAILTYPE
&& IsNormalRailTile(tile_cur
) &&
803 HasPowerOnRail(GetRailType(tile_cur
), rt
)) {
804 /* Allow overbuilding if the tile:
805 * - has rail, but no signals
806 * - it has exactly one track
807 * - the track is in line with the station
808 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
810 Track track
= AxisToTrack(axis
);
812 if (GetTrackBits(tile_cur
) == TrackToTrackBits(track
) && !HasSignalOnTrack(tile_cur
, track
)) {
813 /* Check for trains having a reservation for this tile. */
814 if (HasBit(GetRailReservationTrackBits(tile_cur
), track
)) {
815 Train
*v
= GetTrainForReservation(tile_cur
, track
);
817 *affected_vehicles
.Append() = v
;
820 CommandCost ret
= DoCommand(tile_cur
, 0, track
, flags
, CMD_REMOVE_SINGLE_RAIL
);
821 if (ret
.Failed()) return ret
;
823 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
827 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
828 if (ret
.Failed()) return ret
;
837 * Checks if a road stop can be built at the given tile.
838 * @param tile_area Area to check.
839 * @param flags Operation to perform.
840 * @param invalid_dirs Prohibited directions (set of DiagDirections).
841 * @param is_drive_through True if trying to build a drive-through station.
842 * @param is_truck_stop True when building a truck stop, false otherwise.
843 * @param axis Axis of a drive-through road stop.
844 * @param station StationID to be queried and returned if available.
845 * @param rts Road types to build.
846 * @return The cost in case of success, or an error code if it failed.
848 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
)
850 CommandCost
cost(EXPENSES_CONSTRUCTION
);
853 TILE_AREA_LOOP(cur_tile
, tile_area
) {
854 CommandCost ret
= CheckBuildableTile(cur_tile
, invalid_dirs
, allowed_z
, !is_drive_through
);
855 if (ret
.Failed()) return ret
;
858 /* If station is set, then we have special handling to allow building on top of already existing stations.
859 * Station points to INVALID_STATION if we can build on any station.
860 * Or it points to a station if we're only allowed to build on exactly that station. */
861 if (station
!= NULL
&& IsStationTile(cur_tile
)) {
862 if (!IsRoadStop(cur_tile
)) {
863 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
865 if (is_truck_stop
!= IsTruckStop(cur_tile
) ||
866 is_drive_through
!= IsDriveThroughStopTile(cur_tile
)) {
867 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
869 /* Drive-through station in the wrong direction. */
870 if (is_drive_through
&& IsDriveThroughStopTile(cur_tile
) && GetRoadStopAxis(cur_tile
) != axis
){
871 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
873 StationID st
= GetStationIndex(cur_tile
);
874 if (*station
== INVALID_STATION
) {
876 } else if (*station
!= st
) {
877 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
881 bool build_over_road
= is_drive_through
&& IsNormalRoadTile(cur_tile
);
882 /* Road bits in the wrong direction. */
883 RoadBits rb
= IsRoadTile(cur_tile
) ? GetAllRoadBits(cur_tile
) : ROAD_NONE
;
884 if (build_over_road
&& (rb
& (axis
== AXIS_X
? ROAD_Y
: ROAD_X
)) != 0) {
885 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
886 switch (CountBits(rb
)) {
888 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
891 if (rb
== ROAD_X
|| rb
== ROAD_Y
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
892 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER
);
895 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION
);
899 RoadTypes cur_rts
= IsRoadTile(cur_tile
) ? GetRoadTypes(cur_tile
) : ROADTYPES_NONE
;
900 uint num_roadbits
= 0;
901 if (build_over_road
) {
902 /* There is a road, check if we can build road+tram stop over it. */
903 if (HasBit(cur_rts
, ROADTYPE_ROAD
)) {
904 Owner road_owner
= GetRoadOwner(cur_tile
, ROADTYPE_ROAD
);
905 if (road_owner
== OWNER_TOWN
) {
906 if (!_settings_game
.construction
.road_stop_on_town_road
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD
);
907 } else if (!_settings_game
.construction
.road_stop_on_competitor_road
&& road_owner
!= OWNER_NONE
) {
908 CommandCost ret
= CheckOwnership(road_owner
);
909 if (ret
.Failed()) return ret
;
911 num_roadbits
+= CountBits(GetRoadBits(cur_tile
, ROADTYPE_ROAD
));
914 /* There is a tram, check if we can build road+tram stop over it. */
915 if (HasBit(cur_rts
, ROADTYPE_TRAM
)) {
916 Owner tram_owner
= GetRoadOwner(cur_tile
, ROADTYPE_TRAM
);
917 if (!_settings_game
.construction
.road_stop_on_competitor_road
&& tram_owner
!= OWNER_NONE
) {
918 CommandCost ret
= CheckOwnership(tram_owner
);
919 if (ret
.Failed()) return ret
;
921 num_roadbits
+= CountBits(GetRoadBits(cur_tile
, ROADTYPE_TRAM
));
924 /* Take into account existing roadbits. */
927 ret
= DoCommand(cur_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
928 if (ret
.Failed()) return ret
;
932 uint roadbits_to_build
= CountBits(rts
) * 2 - num_roadbits
;
933 cost
.AddCost(_price
[PR_BUILD_ROAD
] * roadbits_to_build
);
941 * Checks if an airport can be built at the given area.
942 * @param tile_area Area to check.
943 * @param flags Operation to perform.
944 * @param station StationID of airport allowed in search area.
945 * @return The cost in case of success, or an error code if it failed.
947 static CommandCost
CheckFlatLandAirport(TileArea tile_area
, DoCommandFlag flags
, StationID
*station
)
949 CommandCost
cost(EXPENSES_CONSTRUCTION
);
952 TILE_AREA_LOOP(tile_cur
, tile_area
) {
953 CommandCost ret
= CheckBuildableTile(tile_cur
, 0, allowed_z
, true);
954 if (ret
.Failed()) return ret
;
957 /* if station is set, then allow building on top of an already
958 * existing airport, either the one in *station if it is not
959 * INVALID_STATION, or anyone otherwise and store which one
961 if (station
!= NULL
&& IsStationTile(tile_cur
)) {
962 if (!IsAirport(tile_cur
)) {
963 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
965 StationID st
= GetStationIndex(tile_cur
);
966 if (*station
== INVALID_STATION
) {
968 } else if (*station
!= st
) {
969 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
973 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
974 if (ret
.Failed()) return ret
;
983 * Check whether we can expand the rail part of the given station.
984 * @param st the station to expand
985 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
986 * @param axis the axis of the newly build rail
987 * @return Succeeded or failed command.
989 CommandCost
CanExpandRailStation(const BaseStation
*st
, TileArea
&new_ta
, Axis axis
)
991 TileArea cur_ta
= st
->train_station
;
993 /* determine new size of train station region.. */
994 int x
= min(TileX(cur_ta
.tile
), TileX(new_ta
.tile
));
995 int y
= min(TileY(cur_ta
.tile
), TileY(new_ta
.tile
));
996 new_ta
.w
= max(TileX(cur_ta
.tile
) + cur_ta
.w
, TileX(new_ta
.tile
) + new_ta
.w
) - x
;
997 new_ta
.h
= max(TileY(cur_ta
.tile
) + cur_ta
.h
, TileY(new_ta
.tile
) + new_ta
.h
) - y
;
998 new_ta
.tile
= TileXY(x
, y
);
1000 /* make sure the final size is not too big. */
1001 if (new_ta
.w
> _settings_game
.station
.station_spread
|| new_ta
.h
> _settings_game
.station
.station_spread
) {
1002 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1005 return CommandCost();
1008 static inline byte
*CreateSingle(byte
*layout
, int n
)
1011 do *layout
++ = 0; while (--i
);
1012 layout
[((n
- 1) >> 1) - n
] = 2;
1016 static inline byte
*CreateMulti(byte
*layout
, int n
, byte b
)
1019 do *layout
++ = b
; while (--i
);
1022 layout
[n
- 1 - n
] = 0;
1028 * Create the station layout for the given number of tracks and platform length.
1029 * @param layout The layout to write to.
1030 * @param numtracks The number of tracks to write.
1031 * @param plat_len The length of the platforms.
1032 * @param statspec The specification of the station to (possibly) get the layout from.
1034 void GetStationLayout(byte
*layout
, int numtracks
, int plat_len
, const StationSpec
*statspec
)
1036 if (statspec
!= NULL
&& statspec
->lengths
>= plat_len
&&
1037 statspec
->platforms
[plat_len
- 1] >= numtracks
&&
1038 statspec
->layouts
[plat_len
- 1][numtracks
- 1]) {
1039 /* Custom layout defined, follow it. */
1040 memcpy(layout
, statspec
->layouts
[plat_len
- 1][numtracks
- 1],
1041 plat_len
* numtracks
);
1045 if (plat_len
== 1) {
1046 CreateSingle(layout
, numtracks
);
1048 if (numtracks
& 1) layout
= CreateSingle(layout
, plat_len
);
1051 while (--numtracks
>= 0) {
1052 layout
= CreateMulti(layout
, plat_len
, 4);
1053 layout
= CreateMulti(layout
, plat_len
, 6);
1059 * Find a nearby station that joins this station.
1060 * @tparam T the class to find a station for
1061 * @param existing_station an existing station we build over
1062 * @param station_to_join the station to join to
1063 * @param adjacent whether adjacent stations are allowed
1064 * @param ta the area of the newly build station
1065 * @param st 'return' pointer for the found station
1066 * @param error_message the error message when building a station on top of others
1067 * @return command cost with the error or 'okay'
1070 CommandCost
FindJoiningBaseStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, T
**st
, StringID error_message
)
1072 assert(*st
== NULL
);
1074 bool check_surrounding
;
1075 if (!_settings_game
.station
.adjacent_stations
) {
1076 check_surrounding
= true;
1077 } else if (existing_station
== INVALID_STATION
) {
1078 /* There's no station here. Don't check the tiles surrounding this
1079 * one if the company wanted to build an adjacent station. */
1080 check_surrounding
= !adjacent
;
1081 } else if (adjacent
&& existing_station
!= station_to_join
) {
1082 /* You can't build an adjacent station over the top of one that
1083 * already exists. */
1084 return_cmd_error(error_message
);
1086 /* Extend the current station, and don't check whether it will
1087 * be near any other stations. */
1088 *st
= T::GetIfValid(existing_station
);
1089 check_surrounding
= (*st
== NULL
);
1092 if (check_surrounding
) {
1093 /* Make sure there are no similar stations around us. */
1094 ta
.tile
-= TileDiffXY(1, 1);
1098 /* check around to see if there are any stations there */
1099 TILE_AREA_LOOP(tile_cur
, ta
) {
1100 if (IsStationTile(tile_cur
)) {
1101 StationID t
= GetStationIndex(tile_cur
);
1102 if (!T::IsValidID(t
)) continue;
1104 if (existing_station
== INVALID_STATION
) {
1105 existing_station
= t
;
1106 } else if (existing_station
!= t
) {
1107 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
1112 *st
= (existing_station
== INVALID_STATION
) ? NULL
: T::Get(existing_station
);
1116 if (*st
== NULL
&& station_to_join
!= INVALID_STATION
) *st
= T::GetIfValid(station_to_join
);
1118 return CommandCost();
1122 * Find a nearby station that joins this station.
1123 * @param existing_station an existing station we build over
1124 * @param station_to_join the station to join to
1125 * @param adjacent whether adjacent stations are allowed
1126 * @param ta the area of the newly build station
1127 * @param st 'return' pointer for the found station
1128 * @param error_message the error message when building a station on top of others
1129 * @return command cost with the error or 'okay'
1131 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
)
1133 return FindJoiningBaseStation
<Station
>(existing_station
, station_to_join
, adjacent
, ta
, st
, error_message
);
1137 * Find a nearby waypoint that joins this waypoint.
1138 * @param existing_waypoint an existing waypoint we build over
1139 * @param waypoint_to_join the waypoint to join to
1140 * @param adjacent whether adjacent waypoints are allowed
1141 * @param ta the area of the newly build waypoint
1142 * @param wp 'return' pointer for the found waypoint
1143 * @return command cost with the error or 'okay'
1145 CommandCost
FindJoiningWaypoint(StationID existing_waypoint
, StationID waypoint_to_join
, bool adjacent
, TileArea ta
, Waypoint
**wp
)
1147 return FindJoiningBaseStation
<Waypoint
>(existing_waypoint
, waypoint_to_join
, adjacent
, ta
, wp
, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST
);
1150 static void FreeTrainReservation(Train
*v
)
1152 FreeTrainTrackReservation(v
);
1154 const RailPathPos pos
= v
->GetPos();
1155 if (!pos
.in_wormhole() && IsRailStationTile(pos
.tile
)) SetRailStationPlatformReservation(pos
, false);
1157 const RailPathPos rev
= v
->Last()->GetReversePos();
1158 if (!rev
.in_wormhole() && IsRailStationTile(rev
.tile
)) SetRailStationPlatformReservation(rev
, false);
1161 static void RestoreTrainReservation(Train
*v
)
1163 const RailPathPos pos
= v
->GetPos();
1164 if (!pos
.in_wormhole() && IsRailStationTile(pos
.tile
)) SetRailStationPlatformReservation(pos
, true);
1166 TryPathReserve(v
, true, true);
1168 const RailPathPos rev
= v
->Last()->GetReversePos();
1169 if (!rev
.in_wormhole() && IsRailStationTile(rev
.tile
)) SetRailStationPlatformReservation(rev
, true);
1173 * Build rail station
1174 * @param tile_org northern most position of station dragging/placement
1175 * @param flags operation to perform
1176 * @param p1 various bitstuffed elements
1177 * - p1 = (bit 0- 3) - railtype
1178 * - p1 = (bit 4) - orientation (Axis)
1179 * - p1 = (bit 8-15) - number of tracks
1180 * - p1 = (bit 16-23) - platform length
1181 * - p1 = (bit 24) - allow stations directly adjacent to other stations.
1182 * @param p2 various bitstuffed elements
1183 * - p2 = (bit 0- 7) - custom station class
1184 * - p2 = (bit 8-15) - custom station id
1185 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
1186 * @param text unused
1187 * @return the cost of this operation or an error
1189 CommandCost
CmdBuildRailStation(TileIndex tile_org
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1191 /* Unpack parameters */
1192 RailType rt
= Extract
<RailType
, 0, 4>(p1
);
1193 Axis axis
= Extract
<Axis
, 4, 1>(p1
);
1194 byte numtracks
= GB(p1
, 8, 8);
1195 byte plat_len
= GB(p1
, 16, 8);
1196 bool adjacent
= HasBit(p1
, 24);
1198 StationClassID spec_class
= Extract
<StationClassID
, 0, 8>(p2
);
1199 byte spec_index
= GB(p2
, 8, 8);
1200 StationID station_to_join
= GB(p2
, 16, 16);
1202 /* Does the authority allow this? */
1203 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile_org
, flags
);
1204 if (ret
.Failed()) return ret
;
1206 if (!ValParamRailtype(rt
)) return CMD_ERROR
;
1208 /* Check if the given station class is valid */
1209 if ((uint
)spec_class
>= StationClass::GetClassCount() || spec_class
== STAT_CLASS_WAYP
) return CMD_ERROR
;
1210 if (spec_index
>= StationClass::Get(spec_class
)->GetSpecCount()) return CMD_ERROR
;
1211 if (plat_len
== 0 || numtracks
== 0) return CMD_ERROR
;
1214 if (axis
== AXIS_X
) {
1222 bool reuse
= (station_to_join
!= NEW_STATION
);
1223 if (!reuse
) station_to_join
= INVALID_STATION
;
1224 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1226 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1228 if (h_org
> _settings_game
.station
.station_spread
|| w_org
> _settings_game
.station
.station_spread
) return CMD_ERROR
;
1230 /* these values are those that will be stored in train_tile and station_platforms */
1231 TileArea
new_location(tile_org
, w_org
, h_org
);
1233 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1234 StationID est
= INVALID_STATION
;
1235 SmallVector
<Train
*, 4> affected_vehicles
;
1236 /* Clear the land below the station. */
1237 CommandCost cost
= CheckFlatLandRailStation(new_location
, flags
, axis
, &est
, rt
, affected_vehicles
, spec_class
, spec_index
, plat_len
, numtracks
);
1238 if (cost
.Failed()) return cost
;
1239 /* Add construction expenses. */
1240 cost
.AddCost((numtracks
* _price
[PR_BUILD_STATION_RAIL
] + _price
[PR_BUILD_STATION_RAIL_LENGTH
]) * plat_len
);
1241 cost
.AddCost(numtracks
* plat_len
* RailBuildCost(rt
));
1244 ret
= FindJoiningStation(est
, station_to_join
, adjacent
, new_location
, &st
);
1245 if (ret
.Failed()) return ret
;
1247 ret
= BuildStationPart(&st
, flags
, reuse
, new_location
, STATIONNAMING_RAIL
);
1248 if (ret
.Failed()) return ret
;
1250 if (st
!= NULL
&& st
->train_station
.tile
!= INVALID_TILE
) {
1251 CommandCost ret
= CanExpandRailStation(st
, new_location
, axis
);
1252 if (ret
.Failed()) return ret
;
1255 /* Check if we can allocate a custom stationspec to this station */
1256 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
1257 int specindex
= AllocateSpecToStation(statspec
, st
, (flags
& DC_EXEC
) != 0);
1258 if (specindex
== -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS
);
1260 if (statspec
!= NULL
) {
1261 /* Perform NewStation checks */
1263 /* Check if the station size is permitted */
1264 if (HasBit(statspec
->disallowed_platforms
, numtracks
- 1) || HasBit(statspec
->disallowed_lengths
, plat_len
- 1)) {
1268 /* Check if the station is buildable */
1269 if (HasBit(statspec
->callback_mask
, CBM_STATION_AVAIL
)) {
1270 uint16 cb_res
= GetStationCallback(CBID_STATION_AVAILABILITY
, 0, 0, statspec
, NULL
, INVALID_TILE
);
1271 if (cb_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(statspec
->grf_prop
.grffile
, CBID_STATION_AVAILABILITY
, cb_res
)) return CMD_ERROR
;
1275 if (flags
& DC_EXEC
) {
1276 TileIndexDiff tile_delta
;
1278 byte numtracks_orig
;
1281 st
->train_station
= new_location
;
1282 st
->AddFacility(FACIL_TRAIN
, new_location
.tile
);
1284 st
->rect
.BeforeAddRect(tile_org
, w_org
, h_org
, StationRect::ADD_TRY
);
1286 if (statspec
!= NULL
) {
1287 /* Include this station spec's animation trigger bitmask
1288 * in the station's cached copy. */
1289 st
->cached_anim_triggers
|= statspec
->animation
.triggers
;
1292 tile_delta
= (axis
== AXIS_X
? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1293 track
= AxisToTrack(axis
);
1295 layout_ptr
= AllocaM(byte
, numtracks
* plat_len
);
1296 GetStationLayout(layout_ptr
, numtracks
, plat_len
, statspec
);
1298 numtracks_orig
= numtracks
;
1300 Company
*c
= Company::Get(st
->owner
);
1301 TileIndex tile_track
= tile_org
;
1303 TileIndex tile
= tile_track
;
1306 byte layout
= *layout_ptr
++;
1307 if (IsRailStationTile(tile
) && HasStationReservation(tile
)) {
1308 /* Check for trains having a reservation for this tile. */
1309 Train
*v
= GetTrainForReservation(tile
, AxisToTrack(GetRailStationAxis(tile
)));
1311 *affected_vehicles
.Append() = v
;
1312 FreeTrainReservation(v
);
1316 /* Railtype can change when overbuilding. */
1317 if (IsRailStationTile(tile
)) {
1318 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[GetRailType(tile
)]--;
1319 c
->infrastructure
.station
--;
1322 /* Remove animation if overbuilding */
1323 DeleteAnimatedTile(tile
);
1324 byte old_specindex
= HasStationTileRail(tile
) ? GetCustomStationSpecIndex(tile
) : 0;
1325 MakeRailStation(tile
, st
->owner
, st
->index
, axis
, layout
& ~1, rt
);
1326 /* Free the spec if we overbuild something */
1327 DeallocateSpecFromStation(st
, old_specindex
);
1329 SetCustomStationSpecIndex(tile
, specindex
);
1330 SetStationTileRandomBits(tile
, GB(Random(), 0, 4));
1331 SetAnimationFrame(tile
, 0);
1333 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[rt
]++;
1334 c
->infrastructure
.station
++;
1336 if (statspec
!= NULL
) {
1337 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1338 uint32 platinfo
= GetPlatformInfo(AXIS_X
, GetStationGfx(tile
), plat_len
, numtracks_orig
, plat_len
- w
, numtracks_orig
- numtracks
, false);
1340 /* As the station is not yet completely finished, the station does not yet exist. */
1341 uint16 callback
= GetStationCallback(CBID_STATION_TILE_LAYOUT
, platinfo
, 0, statspec
, NULL
, tile
);
1342 if (callback
!= CALLBACK_FAILED
) {
1344 SetStationGfx(tile
, (callback
& ~1) + axis
);
1346 ErrorUnknownCallbackResult(statspec
->grf_prop
.grffile
->grfid
, CBID_STATION_TILE_LAYOUT
, callback
);
1350 /* Trigger station animation -- after building? */
1351 TriggerStationAnimation(st
, tile
, SAT_BUILT
);
1356 AddTrackToSignalBuffer(tile_track
, track
, _current_company
);
1357 YapfNotifyTrackLayoutChange(tile_track
, track
);
1358 tile_track
+= tile_delta
^ TileDiffXY(1, 1); // perpendicular to tile_delta
1359 } while (--numtracks
);
1361 for (uint i
= 0; i
< affected_vehicles
.Length(); ++i
) {
1362 RestoreTrainReservation(affected_vehicles
[i
]);
1365 /* Check whether we need to expand the reservation of trains already on the station. */
1366 TileArea update_reservation_area
;
1367 if (axis
== AXIS_X
) {
1368 update_reservation_area
= TileArea(tile_org
, 1, numtracks_orig
);
1370 update_reservation_area
= TileArea(tile_org
, numtracks_orig
, 1);
1373 TILE_AREA_LOOP(tile
, update_reservation_area
) {
1374 /* Don't even try to make eye candy parts reserved. */
1375 if (IsStationTileBlocked(tile
)) continue;
1377 DiagDirection dir
= AxisToDiagDir(axis
);
1378 TileIndexDiff tile_offset
= TileOffsByDiagDir(dir
);
1379 TileIndex platform_begin
= tile
;
1380 TileIndex platform_end
= tile
;
1382 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1383 for (TileIndex next_tile
= platform_begin
- tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_begin
); next_tile
-= tile_offset
) {
1384 platform_begin
= next_tile
;
1386 for (TileIndex next_tile
= platform_end
+ tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_end
); next_tile
+= tile_offset
) {
1387 platform_end
= next_tile
;
1390 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1391 bool reservation
= false;
1392 for (TileIndex t
= platform_begin
; !reservation
&& t
<= platform_end
; t
+= tile_offset
) {
1393 reservation
= HasStationReservation(t
);
1397 SetRailStationPlatformReservation(platform_begin
, dir
, true);
1401 st
->MarkTilesDirty(false);
1402 st
->UpdateVirtCoord();
1403 UpdateStationAcceptance(st
, false);
1404 st
->RecomputeIndustriesNear();
1405 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
1406 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
1407 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1408 DirtyCompanyInfrastructureWindows(st
->owner
);
1414 static void MakeRailStationAreaSmaller(BaseStation
*st
)
1416 TileArea ta
= st
->train_station
;
1421 if (ta
.w
!= 0 && ta
.h
!= 0) {
1422 /* check the left side, x = constant, y changes */
1423 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(0, i
));) {
1424 /* the left side is unused? */
1426 ta
.tile
+= TileDiffXY(1, 0);
1432 /* check the right side, x = constant, y changes */
1433 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(ta
.w
- 1, i
));) {
1434 /* the right side is unused? */
1441 /* check the upper side, y = constant, x changes */
1442 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(i
, 0));) {
1443 /* the left side is unused? */
1445 ta
.tile
+= TileDiffXY(0, 1);
1451 /* check the lower side, y = constant, x changes */
1452 for (uint i
= 0; !st
->TileBelongsToRailStation(ta
.tile
+ TileDiffXY(i
, ta
.h
- 1));) {
1453 /* the left side is unused? */
1463 st
->train_station
= ta
;
1467 * Remove a number of tiles from any rail station within the area.
1468 * @param ta the area to clear station tile from.
1469 * @param affected_stations the stations affected.
1470 * @param flags the command flags.
1471 * @param removal_cost the cost for removing the tile, including the rail.
1472 * @param keep_rail whether to keep the rail of the station.
1473 * @tparam T the type of station to remove.
1474 * @return the number of cleared tiles or an error.
1477 CommandCost
RemoveFromRailBaseStation(TileArea ta
, SmallVector
<T
*, 4> &affected_stations
, DoCommandFlag flags
, Money removal_cost
, bool keep_rail
)
1479 /* Count of the number of tiles removed */
1481 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
1482 /* Accumulator for the errors seen during clearing. If no errors happen,
1483 * and the quantity is 0 there is no station. Otherwise it will be one
1484 * of the other error that got accumulated. */
1487 /* Do the action for every tile into the area */
1488 TILE_AREA_LOOP(tile
, ta
) {
1489 /* Make sure the specified tile is a rail station */
1490 if (!HasStationTileRail(tile
)) continue;
1492 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1493 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1495 if (ret
.Failed()) continue;
1497 /* Check ownership of station */
1498 T
*st
= T::GetByTile(tile
);
1499 if (st
== NULL
) continue;
1501 if (_current_company
!= OWNER_WATER
) {
1502 CommandCost ret
= CheckOwnership(st
->owner
);
1504 if (ret
.Failed()) continue;
1507 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1510 if (keep_rail
|| IsStationTileBlocked(tile
)) {
1511 /* Don't refund the 'steel' of the track when we keep the
1512 * rail, or when the tile didn't have any rail at all. */
1513 total_cost
.AddCost(-_price
[PR_CLEAR_RAIL
]);
1516 if (flags
& DC_EXEC
) {
1517 /* read variables before the station tile is removed */
1518 uint specindex
= GetCustomStationSpecIndex(tile
);
1519 Track track
= GetRailStationTrack(tile
);
1520 Owner owner
= GetTileOwner(tile
);
1521 RailType rt
= GetRailType(tile
);
1524 if (HasStationReservation(tile
)) {
1525 v
= GetTrainForReservation(tile
, track
);
1526 if (v
!= NULL
) FreeTrainReservation(v
);
1529 bool build_rail
= keep_rail
&& !IsStationTileBlocked(tile
);
1530 if (!build_rail
&& !IsStationTileBlocked(tile
)) Company::Get(owner
)->infrastructure
.rail
[rt
]--;
1532 DoClearSquare(tile
);
1533 DeleteNewGRFInspectWindow(GSF_STATIONS
, tile
);
1534 if (build_rail
) MakeRailNormal(tile
, owner
, TrackToTrackBits(track
), rt
);
1535 Company::Get(owner
)->infrastructure
.station
--;
1536 DirtyCompanyInfrastructureWindows(owner
);
1538 st
->rect
.AfterRemoveTile(st
, tile
);
1539 AddTrackToSignalBuffer(tile
, track
, owner
);
1540 YapfNotifyTrackLayoutChange(tile
, track
);
1542 DeallocateSpecFromStation(st
, specindex
);
1544 affected_stations
.Include(st
);
1546 if (v
!= NULL
) RestoreTrainReservation(v
);
1550 if (quantity
== 0) return error
.Failed() ? error
: CommandCost(STR_ERROR_THERE_IS_NO_STATION
);
1552 for (T
**stp
= affected_stations
.Begin(); stp
!= affected_stations
.End(); stp
++) {
1555 /* now we need to make the "spanned" area of the railway station smaller
1556 * if we deleted something at the edges.
1557 * we also need to adjust train_tile. */
1558 MakeRailStationAreaSmaller(st
);
1559 UpdateStationSignCoord(st
);
1561 /* if we deleted the whole station, delete the train facility. */
1562 if (st
->train_station
.tile
== INVALID_TILE
) {
1563 st
->facilities
&= ~FACIL_TRAIN
;
1564 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1565 st
->UpdateVirtCoord();
1566 DeleteStationIfEmpty(st
);
1570 total_cost
.AddCost(quantity
* removal_cost
);
1575 * Remove a single tile from a rail station.
1576 * This allows for custom-built station with holes and weird layouts
1577 * @param start tile of station piece to remove
1578 * @param flags operation to perform
1579 * @param p1 start_tile
1580 * @param p2 various bitstuffed elements
1581 * - p2 = bit 0 - if set keep the rail
1582 * @param text unused
1583 * @return the cost of this operation or an error
1585 CommandCost
CmdRemoveFromRailStation(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1587 TileIndex end
= p1
== 0 ? start
: p1
;
1588 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1590 TileArea
ta(start
, end
);
1591 SmallVector
<Station
*, 4> affected_stations
;
1593 CommandCost ret
= RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_STATION_RAIL
], HasBit(p2
, 0));
1594 if (ret
.Failed()) return ret
;
1596 /* Do all station specific functions here. */
1597 for (Station
**stp
= affected_stations
.Begin(); stp
!= affected_stations
.End(); stp
++) {
1600 if (st
->train_station
.tile
== INVALID_TILE
) SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1601 st
->MarkTilesDirty(false);
1602 st
->RecomputeIndustriesNear();
1605 /* Now apply the rail cost to the number that we deleted */
1610 * Remove a single tile from a waypoint.
1611 * This allows for custom-built waypoint with holes and weird layouts
1612 * @param start tile of waypoint piece to remove
1613 * @param flags operation to perform
1614 * @param p1 start_tile
1615 * @param p2 various bitstuffed elements
1616 * - p2 = bit 0 - if set keep the rail
1617 * @param text unused
1618 * @return the cost of this operation or an error
1620 CommandCost
CmdRemoveFromRailWaypoint(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1622 TileIndex end
= p1
== 0 ? start
: p1
;
1623 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1625 TileArea
ta(start
, end
);
1626 SmallVector
<Waypoint
*, 4> affected_stations
;
1628 return RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
], HasBit(p2
, 0));
1633 * Remove a rail station/waypoint
1634 * @param st The station/waypoint to remove the rail part from
1635 * @param flags operation to perform
1636 * @tparam T the type of station to remove
1637 * @return cost or failure of operation
1640 CommandCost
RemoveRailStation(T
*st
, DoCommandFlag flags
)
1642 /* Current company owns the station? */
1643 if (_current_company
!= OWNER_WATER
) {
1644 CommandCost ret
= CheckOwnership(st
->owner
);
1645 if (ret
.Failed()) return ret
;
1648 /* determine width and height of platforms */
1649 TileArea ta
= st
->train_station
;
1651 assert(ta
.w
!= 0 && ta
.h
!= 0);
1653 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1654 /* clear all areas of the station */
1655 TILE_AREA_LOOP(tile
, ta
) {
1656 /* only remove tiles that are actually train station tiles */
1657 if (!st
->TileBelongsToRailStation(tile
)) continue;
1659 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1660 if (ret
.Failed()) return ret
;
1662 cost
.AddCost(_price
[PR_CLEAR_STATION_RAIL
]);
1663 if (flags
& DC_EXEC
) {
1664 /* read variables before the station tile is removed */
1665 Track track
= GetRailStationTrack(tile
);
1666 Owner owner
= GetTileOwner(tile
); // _current_company can be OWNER_WATER
1668 if (HasStationReservation(tile
)) {
1669 v
= GetTrainForReservation(tile
, track
);
1670 if (v
!= NULL
) FreeTrainTrackReservation(v
);
1672 if (!IsStationTileBlocked(tile
)) Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)]--;
1673 Company::Get(owner
)->infrastructure
.station
--;
1674 DoClearSquare(tile
);
1675 DeleteNewGRFInspectWindow(GSF_STATIONS
, tile
);
1676 AddTrackToSignalBuffer(tile
, track
, owner
);
1677 YapfNotifyTrackLayoutChange(tile
, track
);
1678 if (v
!= NULL
) TryPathReserve(v
, true);
1682 if (flags
& DC_EXEC
) {
1683 st
->rect
.AfterRemoveRect(st
, st
->train_station
);
1685 st
->train_station
.Clear();
1687 st
->facilities
&= ~FACIL_TRAIN
;
1691 st
->speclist
= NULL
;
1692 st
->cached_anim_triggers
= 0;
1694 DirtyCompanyInfrastructureWindows(st
->owner
);
1695 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1696 st
->UpdateVirtCoord();
1697 DeleteStationIfEmpty(st
);
1704 * Remove a rail station
1705 * @param tile Tile of the station.
1706 * @param flags operation to perform
1707 * @return cost or failure of operation
1709 static CommandCost
RemoveRailStation(TileIndex tile
, DoCommandFlag flags
)
1711 /* if there is flooding, remove platforms tile by tile */
1712 if (_current_company
== OWNER_WATER
) {
1713 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_STATION
);
1716 Station
*st
= Station::GetByTile(tile
);
1717 CommandCost cost
= RemoveRailStation(st
, flags
);
1719 if (flags
& DC_EXEC
) st
->RecomputeIndustriesNear();
1725 * Remove a rail waypoint
1726 * @param tile Tile of the waypoint.
1727 * @param flags operation to perform
1728 * @return cost or failure of operation
1730 static CommandCost
RemoveRailWaypoint(TileIndex tile
, DoCommandFlag flags
)
1732 /* if there is flooding, remove waypoints tile by tile */
1733 if (_current_company
== OWNER_WATER
) {
1734 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_WAYPOINT
);
1737 return RemoveRailStation(Waypoint::GetByTile(tile
), flags
);
1742 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1743 * @param st The Station to do the whole procedure for
1744 * @return a pointer to where to link a new RoadStop*
1746 static RoadStop
**FindRoadStopSpot(bool truck_station
, Station
*st
)
1748 RoadStop
**primary_stop
= (truck_station
) ? &st
->truck_stops
: &st
->bus_stops
;
1750 if (*primary_stop
== NULL
) {
1751 /* we have no roadstop of the type yet, so write a "primary stop" */
1752 return primary_stop
;
1754 /* there are stops already, so append to the end of the list */
1755 RoadStop
*stop
= *primary_stop
;
1756 while (stop
->next
!= NULL
) stop
= stop
->next
;
1761 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
);
1764 * Build a bus or truck stop.
1765 * @param tile Northernmost tile of the stop.
1766 * @param flags Operation to perform.
1767 * @param p1 bit 0..7: Width of the road stop.
1768 * bit 8..15: Length of the road stop.
1769 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1770 * bit 1: 0 For normal stops, 1 for drive-through.
1771 * bit 2..3: The roadtypes.
1772 * bit 5: Allow stations directly adjacent to other stations.
1773 * bit 6..7: Entrance direction (#DiagDirection).
1774 * bit 16..31: Station ID to join (NEW_STATION if build new one).
1775 * @param text Unused.
1776 * @return The cost of this operation or an error.
1778 CommandCost
CmdBuildRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1780 bool type
= HasBit(p2
, 0);
1781 bool is_drive_through
= HasBit(p2
, 1);
1782 RoadTypes rts
= Extract
<RoadTypes
, 2, 2>(p2
);
1783 StationID station_to_join
= GB(p2
, 16, 16);
1784 bool reuse
= (station_to_join
!= NEW_STATION
);
1785 if (!reuse
) station_to_join
= INVALID_STATION
;
1786 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1788 uint8 width
= (uint8
)GB(p1
, 0, 8);
1789 uint8 lenght
= (uint8
)GB(p1
, 8, 8);
1791 /* Check if the requested road stop is too big */
1792 if (width
> _settings_game
.station
.station_spread
|| lenght
> _settings_game
.station
.station_spread
) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1793 /* Check for incorrect width / length. */
1794 if (width
== 0 || lenght
== 0) return CMD_ERROR
;
1795 /* Check if the first tile and the last tile are valid */
1796 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, lenght
- 1) == INVALID_TILE
) return CMD_ERROR
;
1798 TileArea
roadstop_area(tile
, width
, lenght
);
1800 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1802 if (!HasExactlyOneBit(rts
) || !HasRoadTypesAvail(_current_company
, rts
)) return CMD_ERROR
;
1804 /* Trams only have drive through stops */
1805 if (!is_drive_through
&& HasBit(rts
, ROADTYPE_TRAM
)) return CMD_ERROR
;
1807 DiagDirection ddir
= Extract
<DiagDirection
, 6, 2>(p2
);
1809 /* Safeguard the parameters. */
1810 if (!IsValidDiagDirection(ddir
)) return CMD_ERROR
;
1811 /* If it is a drive-through stop, check for valid axis. */
1812 if (is_drive_through
&& !IsValidAxis((Axis
)ddir
)) return CMD_ERROR
;
1814 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
1815 if (ret
.Failed()) return ret
;
1817 /* Total road stop cost. */
1818 CommandCost
cost(EXPENSES_CONSTRUCTION
, roadstop_area
.w
* roadstop_area
.h
* _price
[type
? PR_BUILD_STATION_TRUCK
: PR_BUILD_STATION_BUS
]);
1819 StationID est
= INVALID_STATION
;
1820 ret
= CheckFlatLandRoadStop(roadstop_area
, flags
, is_drive_through
? 5 << ddir
: 1 << ddir
, is_drive_through
, type
, DiagDirToAxis(ddir
), &est
, rts
);
1821 if (ret
.Failed()) return ret
;
1825 ret
= FindJoiningStation(est
, station_to_join
, HasBit(p2
, 5), roadstop_area
, &st
, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST
);
1826 if (ret
.Failed()) return ret
;
1828 /* Check if this number of road stops can be allocated. */
1829 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
);
1831 ret
= BuildStationPart(&st
, flags
, reuse
, roadstop_area
, STATIONNAMING_ROAD
);
1832 if (ret
.Failed()) return ret
;
1834 if (flags
& DC_EXEC
) {
1835 /* Check every tile in the area. */
1836 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
1837 RoadTypes cur_rts
= (IsRoadTile(cur_tile
) || IsStationTile(cur_tile
)) ? GetRoadTypes(cur_tile
) : ROADTYPES_NONE
;
1838 Owner road_owner
= HasBit(cur_rts
, ROADTYPE_ROAD
) ? GetRoadOwner(cur_tile
, ROADTYPE_ROAD
) : _current_company
;
1839 Owner tram_owner
= HasBit(cur_rts
, ROADTYPE_TRAM
) ? GetRoadOwner(cur_tile
, ROADTYPE_TRAM
) : _current_company
;
1841 if (IsStationTile(cur_tile
) && IsRoadStop(cur_tile
)) {
1842 RemoveRoadStop(cur_tile
, flags
);
1845 RoadStop
*road_stop
= new RoadStop(cur_tile
);
1846 /* Insert into linked list of RoadStops. */
1847 RoadStop
**currstop
= FindRoadStopSpot(type
, st
);
1848 *currstop
= road_stop
;
1851 st
->truck_station
.Add(cur_tile
);
1853 st
->bus_station
.Add(cur_tile
);
1856 /* Initialize an empty station. */
1857 st
->AddFacility((type
) ? FACIL_TRUCK_STOP
: FACIL_BUS_STOP
, cur_tile
);
1859 st
->rect
.BeforeAddTile(cur_tile
, StationRect::ADD_TRY
);
1861 RoadStopType rs_type
= type
? ROADSTOP_TRUCK
: ROADSTOP_BUS
;
1862 if (is_drive_through
) {
1863 /* Update company infrastructure counts. If the current tile is a normal
1864 * road tile, count only the new road bits needed to get a full diagonal road. */
1866 FOR_EACH_SET_ROADTYPE(rt
, cur_rts
| rts
) {
1867 Company
*c
= Company::GetIfValid(rt
== ROADTYPE_ROAD
? road_owner
: tram_owner
);
1869 c
->infrastructure
.road
[rt
] += 2 - (IsRoadTile(cur_tile
) && HasBit(cur_rts
, rt
) ? CountBits(GetRoadBits(cur_tile
, rt
)) : 0);
1870 DirtyCompanyInfrastructureWindows(c
->index
);
1874 MakeDriveThroughRoadStop(cur_tile
, st
->owner
, road_owner
, tram_owner
, st
->index
, rs_type
, rts
| cur_rts
, DiagDirToAxis(ddir
));
1875 road_stop
->MakeDriveThrough();
1877 /* Non-drive-through stop never overbuild and always count as two road bits. */
1878 Company::Get(st
->owner
)->infrastructure
.road
[FIND_FIRST_BIT(rts
)] += 2;
1879 MakeRoadStop(cur_tile
, st
->owner
, st
->index
, rs_type
, rts
, ddir
);
1881 Company::Get(st
->owner
)->infrastructure
.station
++;
1882 DirtyCompanyInfrastructureWindows(st
->owner
);
1884 MarkTileDirtyByTile(cur_tile
);
1889 st
->UpdateVirtCoord();
1890 UpdateStationAcceptance(st
, false);
1891 st
->RecomputeIndustriesNear();
1892 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
1893 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
1894 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ROADVEHS
);
1901 * Remove a bus station/truck stop
1902 * @param tile TileIndex been queried
1903 * @param flags operation to perform
1904 * @return cost or failure of operation
1906 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
)
1908 Station
*st
= Station::GetByTile(tile
);
1910 if (_current_company
!= OWNER_WATER
) {
1911 CommandCost ret
= CheckOwnership(st
->owner
);
1912 if (ret
.Failed()) return ret
;
1915 bool is_truck
= IsTruckStop(tile
);
1917 RoadStop
**primary_stop
;
1919 if (is_truck
) { // truck stop
1920 primary_stop
= &st
->truck_stops
;
1921 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_TRUCK
);
1923 primary_stop
= &st
->bus_stops
;
1924 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_BUS
);
1927 assert(cur_stop
!= NULL
);
1929 /* don't do the check for drive-through road stops when company bankrupts */
1930 if (IsDriveThroughStopTile(tile
) && (flags
& DC_BANKRUPT
)) {
1931 /* remove the 'going through road stop' status from all vehicles on that tile */
1932 VehicleTileIterator
iter (tile
);
1933 while (!iter
.finished()) {
1934 Vehicle
*v
= iter
.next();
1935 if (v
->type
== VEH_ROAD
) {
1936 /* Okay... we are a road vehicle on a drive through road stop.
1937 * But that road stop has just been removed, so we need to make
1938 * sure we are in a valid state... however, vehicles can also
1939 * turn on road stop tiles, so only clear the 'road stop' state
1940 * bits and only when the state was 'in road stop', otherwise
1941 * we'll end up clearing the turn around bits. */
1942 RoadVehicle
*rv
= RoadVehicle::From(v
);
1943 if (HasBit(rv
->state
, RVS_IN_DT_ROAD_STOP
)) rv
->state
&= RVSB_ROAD_STOP_TRACKDIR_MASK
;
1947 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1948 if (ret
.Failed()) return ret
;
1951 if (flags
& DC_EXEC
) {
1952 if (*primary_stop
== cur_stop
) {
1953 /* removed the first stop in the list */
1954 *primary_stop
= cur_stop
->next
;
1955 /* removed the only stop? */
1956 if (*primary_stop
== NULL
) {
1957 st
->facilities
&= (is_truck
? ~FACIL_TRUCK_STOP
: ~FACIL_BUS_STOP
);
1960 /* tell the predecessor in the list to skip this stop */
1961 RoadStop
*pred
= *primary_stop
;
1962 while (pred
->next
!= cur_stop
) pred
= pred
->next
;
1963 pred
->next
= cur_stop
->next
;
1966 /* Update company infrastructure counts. */
1968 FOR_EACH_SET_ROADTYPE(rt
, GetRoadTypes(tile
)) {
1969 Company
*c
= Company::GetIfValid(GetRoadOwner(tile
, rt
));
1971 c
->infrastructure
.road
[rt
] -= 2;
1972 DirtyCompanyInfrastructureWindows(c
->index
);
1975 Company::Get(st
->owner
)->infrastructure
.station
--;
1977 if (IsDriveThroughStopTile(tile
)) {
1978 /* Clears the tile for us */
1979 cur_stop
->ClearDriveThrough();
1981 DoClearSquare(tile
);
1984 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ROADVEHS
);
1987 /* Make sure no vehicle is going to the old roadstop */
1989 FOR_ALL_ROADVEHICLES(v
) {
1990 if (v
->First() == v
&& v
->current_order
.IsType(OT_GOTO_STATION
) &&
1991 v
->dest_tile
== tile
) {
1992 v
->dest_tile
= v
->GetOrderStationLocation(st
->index
);
1996 st
->rect
.AfterRemoveTile(st
, tile
);
1998 st
->UpdateVirtCoord();
1999 st
->RecomputeIndustriesNear();
2000 DeleteStationIfEmpty(st
);
2002 /* Update the tile area of the truck/bus stop */
2004 st
->truck_station
.Clear();
2005 for (const RoadStop
*rs
= st
->truck_stops
; rs
!= NULL
; rs
= rs
->next
) st
->truck_station
.Add(rs
->xy
);
2007 st
->bus_station
.Clear();
2008 for (const RoadStop
*rs
= st
->bus_stops
; rs
!= NULL
; rs
= rs
->next
) st
->bus_station
.Add(rs
->xy
);
2012 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[is_truck
? PR_CLEAR_STATION_TRUCK
: PR_CLEAR_STATION_BUS
]);
2016 * Remove bus or truck stops.
2017 * @param tile Northernmost tile of the removal area.
2018 * @param flags Operation to perform.
2019 * @param p1 bit 0..7: Width of the removal area.
2020 * bit 8..15: Height of the removal area.
2021 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
2022 * @param text Unused.
2023 * @return The cost of this operation or an error.
2025 CommandCost
CmdRemoveRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2027 uint8 width
= (uint8
)GB(p1
, 0, 8);
2028 uint8 height
= (uint8
)GB(p1
, 8, 8);
2030 /* Check for incorrect width / height. */
2031 if (width
== 0 || height
== 0) return CMD_ERROR
;
2032 /* Check if the first tile and the last tile are valid */
2033 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, height
- 1) == INVALID_TILE
) return CMD_ERROR
;
2035 TileArea
roadstop_area(tile
, width
, height
);
2038 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2039 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
2040 /* Make sure the specified tile is a road stop of the correct type */
2041 if (!IsStationTile(cur_tile
) || !IsRoadStop(cur_tile
) || (uint32
)GetRoadStopType(cur_tile
) != GB(p2
, 0, 1)) continue;
2043 /* Save the stop info before it is removed */
2044 bool is_drive_through
= IsDriveThroughStopTile(cur_tile
);
2045 RoadTypes rts
= GetRoadTypes(cur_tile
);
2046 RoadBits road_bits
= IsDriveThroughStopTile(cur_tile
) ?
2047 AxisToRoadBits(GetRoadStopAxis(cur_tile
)) :
2048 DiagDirToRoadBits(GetRoadStopDir(cur_tile
));
2050 Owner road_owner
= GetRoadOwner(cur_tile
, ROADTYPE_ROAD
);
2051 Owner tram_owner
= GetRoadOwner(cur_tile
, ROADTYPE_TRAM
);
2052 CommandCost ret
= RemoveRoadStop(cur_tile
, flags
);
2053 if (ret
.Failed()) return ret
;
2057 /* If the stop was a drive-through stop replace the road */
2058 if ((flags
& DC_EXEC
) && is_drive_through
) {
2059 MakeRoadNormal(cur_tile
, road_bits
, rts
, ClosestTownFromTile(cur_tile
, UINT_MAX
)->index
,
2060 road_owner
, tram_owner
);
2062 /* Update company infrastructure counts. */
2064 FOR_EACH_SET_ROADTYPE(rt
, rts
) {
2065 Company
*c
= Company::GetIfValid(GetRoadOwner(cur_tile
, rt
));
2067 c
->infrastructure
.road
[rt
] += CountBits(road_bits
);
2068 DirtyCompanyInfrastructureWindows(c
->index
);
2074 if (quantity
== 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION
);
2080 * Computes the minimal distance from town's xy to any airport's tile.
2081 * @param it An iterator over all airport tiles.
2082 * @param town_tile town's tile (t->xy)
2083 * @return minimal manhattan distance from town_tile to any airport's tile
2085 static uint
GetMinimalAirportDistanceToTile(TileIterator
&it
, TileIndex town_tile
)
2087 uint mindist
= UINT_MAX
;
2089 for (TileIndex cur_tile
= it
; cur_tile
!= INVALID_TILE
; cur_tile
= ++it
) {
2090 mindist
= min(mindist
, DistanceManhattan(town_tile
, cur_tile
));
2097 * Get a possible noise reduction factor based on distance from town center.
2098 * The further you get, the less noise you generate.
2099 * So all those folks at city council can now happily slee... work in their offices
2100 * @param as airport information
2101 * @param it An iterator over all airport tiles.
2102 * @param town_tile TileIndex of town's center, the one who will receive the airport's candidature
2103 * @return the noise that will be generated, according to distance
2105 uint8
GetAirportNoiseLevelForTown(const AirportSpec
*as
, TileIterator
&it
, TileIndex town_tile
)
2107 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2108 * So no need to go any further*/
2109 if (as
->noise_level
< 2) return as
->noise_level
;
2111 uint distance
= GetMinimalAirportDistanceToTile(it
, town_tile
);
2113 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2114 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2115 * Basically, it says that the less tolerant a town is, the bigger the distance before
2116 * an actual decrease can be granted */
2117 uint8 town_tolerance_distance
= 8 + (_settings_game
.difficulty
.town_council_tolerance
* 4);
2119 /* now, we want to have the distance segmented using the distance judged bareable by town
2120 * This will give us the coefficient of reduction the distance provides. */
2121 uint noise_reduction
= distance
/ town_tolerance_distance
;
2123 /* If the noise reduction equals the airport noise itself, don't give it for free.
2124 * Otherwise, simply reduce the airport's level. */
2125 return noise_reduction
>= as
->noise_level
? 1 : as
->noise_level
- noise_reduction
;
2129 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2130 * If two towns have the same distance, town with lower index is returned.
2131 * @param as airport's description
2132 * @param it An iterator over all airport tiles
2133 * @return nearest town to airport
2135 Town
*AirportGetNearestTown(const AirportSpec
*as
, const TileIterator
&it
)
2137 Town
*t
, *nearest
= NULL
;
2138 uint add
= as
->size_x
+ as
->size_y
- 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2139 uint mindist
= UINT_MAX
- add
; // prevent overflow
2141 if (DistanceManhattan(t
->xy
, it
) < mindist
+ add
) { // avoid calling GetMinimalAirportDistanceToTile too often
2142 TileIterator
*copy
= it
.Clone();
2143 uint dist
= GetMinimalAirportDistanceToTile(*copy
, t
->xy
);
2145 if (dist
< mindist
) {
2156 /** Recalculate the noise generated by the airports of each town */
2157 void UpdateAirportsNoise()
2162 FOR_ALL_TOWNS(t
) t
->noise_reached
= 0;
2164 FOR_ALL_STATIONS(st
) {
2165 if (st
->airport
.tile
!= INVALID_TILE
&& st
->airport
.type
!= AT_OILRIG
) {
2166 const AirportSpec
*as
= st
->airport
.GetSpec();
2167 AirportTileIterator
it(st
);
2168 Town
*nearest
= AirportGetNearestTown(as
, it
);
2169 nearest
->noise_reached
+= GetAirportNoiseLevelForTown(as
, it
, nearest
->xy
);
2176 * Checks if an airport can be removed (no aircraft on it or landing)
2177 * @param st Station whose airport is to be removed
2178 * @param flags Operation to perform
2179 * @return Cost or failure of operation
2181 static CommandCost
CanRemoveAirport(Station
*st
, DoCommandFlag flags
)
2184 FOR_ALL_AIRCRAFT(a
) {
2185 if (!a
->IsNormalAircraft()) continue;
2186 if (a
->targetairport
== st
->index
&& a
->state
!= FLYING
)
2187 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY
);
2190 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2192 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2193 if (!st
->TileBelongsToAirport(tile_cur
)) continue;
2195 CommandCost ret
= EnsureNoVehicleOnGround(tile_cur
);
2196 if (ret
.Failed()) return ret
;
2198 cost
.AddCost(_price
[PR_CLEAR_STATION_AIRPORT
]);
2207 * @param tile tile where airport will be built
2208 * @param flags operation to perform
2210 * - p1 = (bit 0- 7) - airport type, @see airport.h
2211 * - p1 = (bit 8-15) - airport layout
2212 * @param p2 various bitstuffed elements
2213 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2214 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2215 * @param text unused
2216 * @return the cost of this operation or an error
2218 CommandCost
CmdBuildAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2220 StationID station_to_join
= GB(p2
, 16, 16);
2221 bool reuse
= (station_to_join
!= NEW_STATION
);
2222 if (!reuse
) station_to_join
= INVALID_STATION
;
2223 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2224 byte airport_type
= GB(p1
, 0, 8);
2225 byte layout
= GB(p1
, 8, 8);
2227 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2229 if (airport_type
>= NUM_AIRPORTS
) return CMD_ERROR
;
2231 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2232 if (ret
.Failed()) return ret
;
2234 /* Check if a valid, buildable airport was chosen for construction */
2235 const AirportSpec
*as
= AirportSpec::Get(airport_type
);
2236 if (!as
->IsAvailable() || layout
>= as
->num_table
) return CMD_ERROR
;
2238 Direction rotation
= as
->rotation
[layout
];
2241 if (rotation
== DIR_E
|| rotation
== DIR_W
) Swap(w
, h
);
2242 TileArea airport_area
= TileArea(tile
, w
, h
);
2244 if (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
) {
2245 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
2248 StationID est
= INVALID_STATION
;
2249 CommandCost cost
= CheckFlatLandAirport(airport_area
, flags
, &est
);
2250 if (cost
.Failed()) return cost
;
2253 ret
= FindJoiningStation(est
, station_to_join
, HasBit(p2
, 0), airport_area
, &st
, STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
2254 if (ret
.Failed()) return ret
;
2257 if (st
== NULL
&& distant_join
) st
= Station::GetIfValid(station_to_join
);
2259 ret
= BuildStationPart(&st
, flags
, reuse
, airport_area
, (GetAirport(airport_type
)->flags
& AirportFTAClass::AIRPLANES
) ? STATIONNAMING_AIRPORT
: STATIONNAMING_HELIPORT
);
2260 if (ret
.Failed()) return ret
;
2262 /* action to be performed */
2264 AIRPORT_NEW
, // airport is a new station
2265 AIRPORT_ADD
, // add an airport to an existing station
2266 AIRPORT_UPGRADE
, // upgrade the airport in a station
2268 (est
!= INVALID_STATION
) ? AIRPORT_UPGRADE
:
2269 (st
!= NULL
) ? AIRPORT_ADD
: AIRPORT_NEW
;
2271 if (action
== AIRPORT_ADD
&& st
->airport
.tile
!= INVALID_TILE
) {
2272 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT
);
2275 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2276 AirportTileTableIterator
iter(as
->table
[layout
], tile
);
2277 Town
*nearest
= AirportGetNearestTown(as
, iter
);
2278 uint newnoise_level
= nearest
->noise_reached
+ GetAirportNoiseLevelForTown(as
, iter
, nearest
->xy
);
2280 if (action
== AIRPORT_UPGRADE
) {
2281 const AirportSpec
*old_as
= st
->airport
.GetSpec();
2282 AirportTileTableIterator
old_iter(old_as
->table
[st
->airport
.layout
], st
->airport
.tile
);
2283 Town
*old_nearest
= AirportGetNearestTown(old_as
, old_iter
);
2284 if (old_nearest
== nearest
) {
2285 newnoise_level
-= GetAirportNoiseLevelForTown(old_as
, old_iter
, nearest
->xy
);
2289 /* Check if local auth would allow a new airport */
2290 StringID authority_refuse_message
= STR_NULL
;
2291 Town
*authority_refuse_town
= NULL
;
2293 if (_settings_game
.economy
.station_noise_level
) {
2294 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2295 if (newnoise_level
> nearest
->MaxTownNoise()) {
2296 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE
;
2297 authority_refuse_town
= nearest
;
2299 } else if (action
!= AIRPORT_UPGRADE
) {
2300 Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
2303 FOR_ALL_STATIONS(st
) {
2304 if (st
->town
== t
&& (st
->facilities
& FACIL_AIRPORT
) && st
->airport
.type
!= AT_OILRIG
) num
++;
2307 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT
;
2308 authority_refuse_town
= t
;
2312 if (authority_refuse_message
!= STR_NULL
) {
2313 SetDParam(0, authority_refuse_town
->index
);
2314 return_cmd_error(authority_refuse_message
);
2317 if (action
== AIRPORT_UPGRADE
) {
2318 /* check that the old airport can be removed */
2319 CommandCost r
= CanRemoveAirport(st
, flags
);
2320 if (r
.Failed()) return r
;
2324 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2325 cost
.AddCost(_price
[PR_BUILD_STATION_AIRPORT
]);
2328 if (flags
& DC_EXEC
) {
2329 if (action
== AIRPORT_UPGRADE
) {
2330 /* delete old airport if upgrading */
2331 const AirportSpec
*old_as
= st
->airport
.GetSpec();
2332 AirportTileTableIterator
old_iter(old_as
->table
[st
->airport
.layout
], st
->airport
.tile
);
2333 Town
*old_nearest
= AirportGetNearestTown(old_as
, old_iter
);
2335 if (old_nearest
!= nearest
) {
2336 old_nearest
->noise_reached
-= GetAirportNoiseLevelForTown(old_as
, old_iter
, old_nearest
->xy
);
2337 if (_settings_game
.economy
.station_noise_level
) {
2338 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2342 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2343 if (IsHangarTile(tile_cur
)) OrderBackup::Reset(tile_cur
, false);
2344 DeleteAnimatedTile(tile_cur
);
2345 DoClearSquare(tile_cur
);
2346 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
);
2349 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2351 WC_VEHICLE_DEPOT
, st
->airport
.GetHangarTile(i
)
2355 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2356 st
->airport
.Clear();
2359 /* Always add the noise, so there will be no need to recalculate when option toggles */
2360 nearest
->noise_reached
= newnoise_level
;
2362 st
->AddFacility(FACIL_AIRPORT
, tile
);
2363 st
->airport
.type
= airport_type
;
2364 st
->airport
.layout
= layout
;
2365 st
->airport
.flags
= 0;
2366 st
->airport
.rotation
= rotation
;
2368 st
->rect
.BeforeAddRect(tile
, w
, h
, StationRect::ADD_TRY
);
2370 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2371 MakeAirport(iter
, st
->owner
, st
->index
, iter
.GetStationGfx(), WATER_CLASS_INVALID
);
2372 SetStationTileRandomBits(iter
, GB(Random(), 0, 4));
2373 st
->airport
.Add(iter
);
2375 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter
.GetStationGfx()))->animation
.status
!= ANIM_STATUS_NO_ANIMATION
) AddAnimatedTile(iter
);
2378 /* Only call the animation trigger after all tiles have been built */
2379 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2380 AirportTileAnimationTrigger(st
, iter
, AAT_BUILT
);
2383 if (action
!= AIRPORT_NEW
) UpdateAirplanesOnNewStation(st
);
2385 if (action
== AIRPORT_UPGRADE
) {
2386 UpdateStationSignCoord(st
);
2388 Company::Get(st
->owner
)->infrastructure
.airport
++;
2389 DirtyCompanyInfrastructureWindows(st
->owner
);
2390 st
->UpdateVirtCoord();
2393 UpdateStationAcceptance(st
, false);
2394 st
->RecomputeIndustriesNear();
2395 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2396 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2397 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2399 if (_settings_game
.economy
.station_noise_level
) {
2400 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2409 * @param tile TileIndex been queried
2410 * @param flags operation to perform
2411 * @return cost or failure of operation
2413 static CommandCost
RemoveAirport(TileIndex tile
, DoCommandFlag flags
)
2415 Station
*st
= Station::GetByTile(tile
);
2417 if (_current_company
!= OWNER_WATER
) {
2418 CommandCost ret
= CheckOwnership(st
->owner
);
2419 if (ret
.Failed()) return ret
;
2422 CommandCost cost
= CanRemoveAirport(st
, flags
);
2423 if (cost
.Failed()) return cost
;
2425 if (flags
& DC_EXEC
) {
2426 const AirportSpec
*as
= st
->airport
.GetSpec();
2427 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2428 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2429 * need of recalculation */
2430 AirportTileIterator
it(st
);
2431 Town
*nearest
= AirportGetNearestTown(as
, it
);
2432 nearest
->noise_reached
-= GetAirportNoiseLevelForTown(as
, it
, nearest
->xy
);
2434 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2435 if (IsHangarTile(tile_cur
)) OrderBackup::Reset(tile_cur
, false);
2436 DeleteAnimatedTile(tile_cur
);
2437 DoClearSquare(tile_cur
);
2438 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
);
2441 /* Clear the persistent storage. */
2442 delete st
->airport
.psa
;
2444 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2446 WC_VEHICLE_DEPOT
, st
->airport
.GetHangarTile(i
)
2450 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2452 st
->airport
.Clear();
2453 st
->facilities
&= ~FACIL_AIRPORT
;
2455 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2457 if (_settings_game
.economy
.station_noise_level
) {
2458 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2461 Company::Get(st
->owner
)->infrastructure
.airport
--;
2462 DirtyCompanyInfrastructureWindows(st
->owner
);
2464 st
->UpdateVirtCoord();
2465 st
->RecomputeIndustriesNear();
2466 DeleteStationIfEmpty(st
);
2467 DeleteNewGRFInspectWindow(GSF_AIRPORTS
, st
->index
);
2474 * Open/close an airport to incoming aircraft.
2475 * @param tile Unused.
2476 * @param flags Operation to perform.
2477 * @param p1 Station ID of the airport.
2479 * @param text unused
2480 * @return the cost of this operation or an error
2482 CommandCost
CmdOpenCloseAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2484 if (!Station::IsValidID(p1
)) return CMD_ERROR
;
2485 Station
*st
= Station::Get(p1
);
2487 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->owner
== OWNER_NONE
) return CMD_ERROR
;
2489 CommandCost ret
= CheckOwnership(st
->owner
);
2490 if (ret
.Failed()) return ret
;
2492 if (flags
& DC_EXEC
) {
2493 st
->airport
.flags
^= AIRPORT_CLOSED_block
;
2494 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_CLOSE_AIRPORT
);
2496 return CommandCost();
2500 * Tests whether the company's vehicles have this station in orders
2501 * @param station station ID
2502 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2503 * @param company company ID
2505 bool HasStationInUse(StationID station
, bool include_company
, CompanyID company
)
2508 FOR_ALL_VEHICLES(v
) {
2509 if ((v
->owner
== company
) == include_company
) {
2511 FOR_VEHICLE_ORDERS(v
, order
) {
2512 if ((order
->IsType(OT_GOTO_STATION
) || order
->IsType(OT_GOTO_WAYPOINT
)) && order
->GetDestination() == station
) {
2521 /** Information about dock tile area for a given direction. */
2522 struct DockTileArea
{
2523 CoordDiff offset
; ///< offset to northern tile
2524 byte width
; ///< width of dock area
2525 byte height
; ///< height of dock area
2529 * Build a dock/haven.
2530 * @param tile tile where dock will be built
2531 * @param flags operation to perform
2532 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
2533 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
2534 * @param text unused
2535 * @return the cost of this operation or an error
2537 CommandCost
CmdBuildDock(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2539 static const DockTileArea dock_tilearea
[DIAGDIR_END
] = {
2540 { { -1, 0 }, 2, 1 },
2543 { { 0, -1 }, 1, 2 },
2546 StationID station_to_join
= GB(p2
, 16, 16);
2547 bool reuse
= (station_to_join
!= NEW_STATION
);
2548 if (!reuse
) station_to_join
= INVALID_STATION
;
2549 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2551 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2553 DiagDirection direction
= GetInclinedSlopeDirection(GetTileSlope(tile
));
2554 if (direction
== INVALID_DIAGDIR
) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2555 direction
= ReverseDiagDir(direction
);
2557 /* Docks cannot be placed on rapids */
2558 if (HasTileWaterGround(tile
)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2560 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2561 if (ret
.Failed()) return ret
;
2563 if (HasBridgeAbove(tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2565 ret
= DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2566 if (ret
.Failed()) return ret
;
2568 TileIndex tile_cur
= tile
+ TileOffsByDiagDir(direction
);
2570 if (!IsWaterTile(tile_cur
) || !IsTileFlat(tile_cur
)) {
2571 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2574 if (HasBridgeAbove(tile_cur
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2576 /* Get the water class of the water tile before it is cleared.*/
2577 WaterClass wc
= GetWaterClass(tile_cur
);
2579 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2580 if (ret
.Failed()) return ret
;
2582 tile_cur
+= TileOffsByDiagDir(direction
);
2583 if (!IsWaterTile(tile_cur
) || !IsTileFlat(tile_cur
)) {
2584 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2587 TileArea dock_area
= TileArea(tile
+ ToTileIndexDiff(dock_tilearea
[direction
].offset
),
2588 dock_tilearea
[direction
].width
, dock_tilearea
[direction
].height
);
2592 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, HasBit(p1
, 0), dock_area
, &st
);
2593 if (ret
.Failed()) return ret
;
2596 if (st
== NULL
&& distant_join
) st
= Station::GetIfValid(station_to_join
);
2598 /* Check if we can allocate a new dock. */
2599 if (!Dock::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_DOCKS
);
2601 ret
= BuildStationPart(&st
, flags
, reuse
, dock_area
, STATIONNAMING_DOCK
);
2602 if (ret
.Failed()) return ret
;
2604 if (flags
& DC_EXEC
) {
2605 Dock
**dl
= &st
->docks
;
2606 while (*dl
!= NULL
) dl
= &(*dl
)->next
;
2608 *dl
= new Dock(tile
);
2609 st
->dock_area
.Add(dock_area
);
2611 st
->AddFacility(FACIL_DOCK
, tile
);
2613 st
->rect
.BeforeAddRect(dock_area
.tile
, dock_area
.w
, dock_area
.h
, StationRect::ADD_TRY
);
2615 /* If the water part of the dock is on a canal, update infrastructure counts.
2616 * This is needed as we've unconditionally cleared that tile before. */
2617 if (wc
== WATER_CLASS_CANAL
) {
2618 Company::Get(st
->owner
)->infrastructure
.water
++;
2620 Company::Get(st
->owner
)->infrastructure
.station
+= 2;
2621 DirtyCompanyInfrastructureWindows(st
->owner
);
2623 MakeDock(tile
, st
->owner
, st
->index
, direction
, wc
);
2625 st
->UpdateVirtCoord();
2626 UpdateStationAcceptance(st
, false);
2627 st
->RecomputeIndustriesNear();
2628 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
2629 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
2630 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_SHIPS
);
2633 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_STATION_DOCK
]);
2638 * @param tile TileIndex been queried
2639 * @param flags operation to perform
2640 * @return cost or failure of operation
2642 static CommandCost
RemoveDock(TileIndex tile
, DoCommandFlag flags
)
2644 assert(IsDock(tile
));
2646 Station
*st
= Station::GetByTile(tile
);
2647 CommandCost ret
= CheckOwnership(st
->owner
);
2648 if (ret
.Failed()) return ret
;
2650 Dock
**d
= &st
->docks
;
2651 TileIndex tile1
, tile2
;
2652 while ( tile1
= (*d
)->xy
, tile2
= tile1
+ TileOffsByDiagDir(GetDockDirection(tile1
)),
2653 tile
!= tile1
&& tile
!= tile2
) {
2654 /* the dock should really be there, so no check for NULL */
2658 ret
= EnsureNoVehicleOnGround(tile1
);
2659 if (ret
.Succeeded()) ret
= EnsureNoVehicleOnGround(tile2
);
2660 if (ret
.Failed()) return ret
;
2662 if (flags
& DC_EXEC
) {
2663 TileIndex docking_location
= GetDockingTile(tile1
);
2665 DoClearSquare(tile1
);
2666 MarkTileDirtyByTile(tile1
);
2667 MakeWaterKeepingClass(tile2
, st
->owner
);
2669 st
->rect
.AfterRemoveTile(st
, tile1
);
2670 st
->rect
.AfterRemoveTile(st
, tile2
);
2672 Dock
*next
= (*d
)->next
;
2675 if (next
== NULL
&& d
== &st
->docks
) st
->facilities
&= ~FACIL_DOCK
;
2677 Company::Get(st
->owner
)->infrastructure
.station
-= 2;
2678 DirtyCompanyInfrastructureWindows(st
->owner
);
2680 /* Update the tile area of the docks */
2681 st
->dock_area
.Clear();
2682 for (const Dock
*dock
= st
->docks
; dock
!= NULL
; dock
= dock
->next
) {
2683 st
->dock_area
.Add(dock
->xy
);
2684 st
->dock_area
.Add(dock
->xy
+ TileOffsByDiagDir(GetDockDirection(dock
->xy
)));
2687 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_SHIPS
);
2688 st
->UpdateVirtCoord();
2689 st
->RecomputeIndustriesNear();
2690 DeleteStationIfEmpty(st
);
2692 /* All ships that were going to our station, can't go to it anymore.
2693 * Just clear the order, then automatically the next appropriate order
2694 * will be selected and in case of no appropriate order it will just
2695 * wander around the world. */
2698 if (s
->current_order
.IsType(OT_LOADING
) && s
->tile
== docking_location
) {
2702 if (s
->dest_tile
== docking_location
) {
2704 s
->current_order
.Free();
2709 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_STATION_DOCK
]);
2712 #include "table/station_land.h"
2714 const DrawTileSprites
*GetStationTileLayout(StationType st
, byte gfx
)
2716 return &_station_display_datas
[st
][gfx
];
2720 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
2721 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
2722 * is set to the overlay to draw.
2723 * @param ti Positional info for the tile to decide snowyness etc. May be NULL.
2724 * @param [in,out] ground Groundsprite to draw.
2725 * @param [out] overlay_offset Overlay to draw.
2726 * @return true if overlay can be drawn.
2728 bool SplitGroundSpriteForOverlay(const TileInfo
*ti
, SpriteID
*ground
, RailTrackOffset
*overlay_offset
)
2732 case SPR_RAIL_TRACK_X
:
2733 snow_desert
= false;
2734 *overlay_offset
= RTO_X
;
2737 case SPR_RAIL_TRACK_Y
:
2738 snow_desert
= false;
2739 *overlay_offset
= RTO_Y
;
2742 case SPR_RAIL_TRACK_X_SNOW
:
2744 *overlay_offset
= RTO_X
;
2747 case SPR_RAIL_TRACK_Y_SNOW
:
2749 *overlay_offset
= RTO_Y
;
2757 /* Decide snow/desert from tile */
2758 switch (_settings_game
.game_creation
.landscape
) {
2760 snow_desert
= (uint
)ti
->z
> GetSnowLine() * TILE_HEIGHT
;
2764 snow_desert
= GetTropicZone(ti
->tile
) == TROPICZONE_DESERT
;
2772 *ground
= snow_desert
? SPR_FLAT_SNOW_DESERT_TILE
: SPR_FLAT_GRASS_TILE
;
2776 static void DrawTile_Station(TileInfo
*ti
)
2778 const NewGRFSpriteLayout
*layout
= NULL
;
2779 DrawTileSprites tmp_rail_layout
;
2780 const DrawTileSprites
*t
= NULL
;
2781 RoadTypes roadtypes
;
2783 const RailtypeInfo
*rti
= NULL
;
2784 uint32 relocation
= 0;
2785 uint32 ground_relocation
= 0;
2786 BaseStation
*st
= NULL
;
2787 const StationSpec
*statspec
= NULL
;
2788 uint tile_layout
= 0;
2790 if (HasStationRail(ti
->tile
)) {
2791 rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
2792 roadtypes
= ROADTYPES_NONE
;
2793 total_offset
= rti
->GetRailtypeSpriteOffset();
2795 if (IsCustomStationSpecIndex(ti
->tile
)) {
2796 /* look for customization */
2797 st
= BaseStation::GetByTile(ti
->tile
);
2798 statspec
= st
->speclist
[GetCustomStationSpecIndex(ti
->tile
)].spec
;
2800 if (statspec
!= NULL
) {
2801 tile_layout
= GetStationGfx(ti
->tile
);
2803 if (HasBit(statspec
->callback_mask
, CBM_STATION_SPRITE_LAYOUT
)) {
2804 uint16 callback
= GetStationCallback(CBID_STATION_SPRITE_LAYOUT
, 0, 0, statspec
, st
, ti
->tile
);
2805 if (callback
!= CALLBACK_FAILED
) tile_layout
= (callback
& ~1) + GetRailStationAxis(ti
->tile
);
2808 /* Ensure the chosen tile layout is valid for this custom station */
2809 if (statspec
->renderdata
!= NULL
) {
2810 layout
= &statspec
->renderdata
[tile_layout
< statspec
->tiles
? tile_layout
: (uint
)GetRailStationAxis(ti
->tile
)];
2811 if (!layout
->NeedsPreprocessing()) {
2819 roadtypes
= IsRoadStop(ti
->tile
) ? GetRoadTypes(ti
->tile
) : ROADTYPES_NONE
;
2823 StationGfx gfx
= GetStationGfx(ti
->tile
);
2824 if (IsAirport(ti
->tile
)) {
2825 gfx
= GetAirportGfx(ti
->tile
);
2826 if (gfx
>= NEW_AIRPORTTILE_OFFSET
) {
2827 const AirportTileSpec
*ats
= AirportTileSpec::Get(gfx
);
2828 if (ats
->grf_prop
.spritegroup
[0] != NULL
&& DrawNewAirportTile(ti
, Station::GetByTile(ti
->tile
), gfx
, ats
)) {
2831 /* No sprite group (or no valid one) found, meaning no graphics associated.
2832 * Use the substitute one instead */
2833 assert(ats
->grf_prop
.subst_id
!= INVALID_AIRPORTTILE
);
2834 gfx
= ats
->grf_prop
.subst_id
;
2837 case APT_RADAR_GRASS_FENCE_SW
:
2838 t
= &_station_display_datas_airport_radar_grass_fence_sw
[GetAnimationFrame(ti
->tile
)];
2840 case APT_GRASS_FENCE_NE_FLAG
:
2841 t
= &_station_display_datas_airport_flag_grass_fence_ne
[GetAnimationFrame(ti
->tile
)];
2843 case APT_RADAR_FENCE_SW
:
2844 t
= &_station_display_datas_airport_radar_fence_sw
[GetAnimationFrame(ti
->tile
)];
2846 case APT_RADAR_FENCE_NE
:
2847 t
= &_station_display_datas_airport_radar_fence_ne
[GetAnimationFrame(ti
->tile
)];
2849 case APT_GRASS_FENCE_NE_FLAG_2
:
2850 t
= &_station_display_datas_airport_flag_grass_fence_ne_2
[GetAnimationFrame(ti
->tile
)];
2855 Owner owner
= GetTileOwner(ti
->tile
);
2858 if (Company::IsValidID(owner
)) {
2859 palette
= COMPANY_SPRITE_COLOUR(owner
);
2861 /* Some stations are not owner by a company, namely oil rigs */
2862 palette
= PALETTE_TO_GREY
;
2865 if (layout
== NULL
&& (t
== NULL
|| t
->seq
== NULL
)) t
= GetStationTileLayout(GetStationType(ti
->tile
), gfx
);
2867 /* don't show foundation for docks */
2868 if (ti
->tileh
!= SLOPE_FLAT
&& !IsDock(ti
->tile
)) {
2869 if (statspec
!= NULL
&& HasBit(statspec
->flags
, SSF_CUSTOM_FOUNDATIONS
)) {
2870 /* Station has custom foundations.
2871 * Check whether the foundation continues beyond the tile's upper sides. */
2874 Slope slope
= GetFoundationPixelSlope(ti
->tile
, &z
);
2875 if (!HasFoundationNW(ti
->tile
, slope
, z
)) SetBit(edge_info
, 0);
2876 if (!HasFoundationNE(ti
->tile
, slope
, z
)) SetBit(edge_info
, 1);
2877 SpriteID image
= GetCustomStationFoundationRelocation(statspec
, st
, ti
->tile
, tile_layout
, edge_info
);
2878 if (image
== 0) goto draw_default_foundation
;
2880 if (HasBit(statspec
->flags
, SSF_EXTENDED_FOUNDATIONS
)) {
2881 /* Station provides extended foundations. */
2883 static const uint8 foundation_parts
[] = {
2884 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2885 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2886 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2887 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2890 AddSortableSpriteToDraw(image
+ foundation_parts
[ti
->tileh
], PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
2892 /* Draw simple foundations, built up from 8 possible foundation sprites. */
2894 /* Each set bit represents one of the eight composite sprites to be drawn.
2895 * 'Invalid' entries will not drawn but are included for completeness. */
2896 static const uint8 composite_foundation_parts
[] = {
2897 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2898 0x00, 0xD1, 0xE4, 0xE0,
2899 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2900 0xCA, 0xC9, 0xC4, 0xC0,
2901 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2902 0xD2, 0x91, 0xE4, 0xA0,
2903 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2907 uint8 parts
= composite_foundation_parts
[ti
->tileh
];
2909 /* If foundations continue beyond the tile's upper sides then
2910 * mask out the last two pieces. */
2911 if (HasBit(edge_info
, 0)) ClrBit(parts
, 6);
2912 if (HasBit(edge_info
, 1)) ClrBit(parts
, 7);
2915 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2916 * correct offset for the childsprites.
2917 * So, draw the (completely empty) sprite of the default foundations. */
2918 goto draw_default_foundation
;
2921 StartSpriteCombine();
2922 for (int i
= 0; i
< 8; i
++) {
2923 if (HasBit(parts
, i
)) {
2924 AddSortableSpriteToDraw(image
+ i
, PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
2930 OffsetGroundSprite(31, 1);
2931 ti
->z
+= ApplyPixelFoundationToSlope(FOUNDATION_LEVELED
, &ti
->tileh
);
2933 draw_default_foundation
:
2934 DrawFoundation(ti
, FOUNDATION_LEVELED
);
2938 if (IsBuoy(ti
->tile
)) {
2939 DrawWaterClassGround(ti
);
2940 SpriteID sprite
= GetCanalSprite(CF_BUOY
, ti
->tile
);
2941 if (sprite
!= 0) total_offset
= sprite
- SPR_IMG_BUOY
;
2942 } else if (IsDock(ti
->tile
) || (IsOilRig(ti
->tile
) && IsTileOnWater(ti
->tile
))) {
2943 if (ti
->tileh
== SLOPE_FLAT
) {
2944 DrawWaterClassGround(ti
);
2946 assert(IsDock(ti
->tile
));
2947 TileIndex water_tile
= ti
->tile
+ TileOffsByDiagDir(GetDockDirection(ti
->tile
));
2948 WaterClass wc
= GetWaterClass(water_tile
);
2949 if (wc
== WATER_CLASS_SEA
) {
2950 DrawShoreTile(ti
->tileh
);
2952 DrawClearLandTile(ti
, 3);
2956 if (layout
!= NULL
) {
2957 /* Sprite layout which needs preprocessing */
2958 bool separate_ground
= HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
);
2959 uint32 var10_values
= layout
->PrepareLayout(total_offset
, rti
->fallback_railtype
, 0, 0, separate_ground
);
2961 FOR_EACH_SET_BIT(var10
, var10_values
) {
2962 uint32 var10_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, var10
);
2963 layout
->ProcessRegisters(var10
, var10_relocation
, separate_ground
);
2965 tmp_rail_layout
.seq
= layout
->GetLayout(&tmp_rail_layout
.ground
);
2966 t
= &tmp_rail_layout
;
2968 } else if (statspec
!= NULL
) {
2969 /* Simple sprite layout */
2970 ground_relocation
= relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 0);
2971 if (HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
)) {
2972 ground_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 1);
2974 ground_relocation
+= rti
->fallback_railtype
;
2977 SpriteID image
= t
->ground
.sprite
;
2978 PaletteID pal
= t
->ground
.pal
;
2979 RailTrackOffset overlay_offset
;
2980 if (rti
!= NULL
&& rti
->UsesOverlay() && SplitGroundSpriteForOverlay(ti
, &image
, &overlay_offset
)) {
2981 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
);
2982 DrawGroundSprite(image
, PAL_NONE
);
2983 DrawGroundSprite(ground
+ overlay_offset
, PAL_NONE
);
2985 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationReservation(ti
->tile
)) {
2986 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
2987 DrawGroundSprite(overlay
+ overlay_offset
, PALETTE_CRASH
);
2990 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
2991 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
2992 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
));
2994 /* PBS debugging, draw reserved tracks darker */
2995 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationRail(ti
->tile
) && HasStationReservation(ti
->tile
)) {
2996 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
2997 DrawGroundSprite(GetRailStationAxis(ti
->tile
) == AXIS_X
? rti
->base_sprites
.single_x
: rti
->base_sprites
.single_y
, PALETTE_CRASH
);
3002 if (HasStationRail(ti
->tile
) && HasCatenaryDrawn(GetRailType(ti
->tile
))) DrawCatenary(ti
);
3004 if (HasBit(roadtypes
, ROADTYPE_TRAM
)) {
3005 Axis axis
= GetRoadStopAxis(ti
->tile
); // tram stops are always drive-through
3006 DrawGroundSprite((HasBit(roadtypes
, ROADTYPE_ROAD
) ? SPR_TRAMWAY_OVERLAY
: SPR_TRAMWAY_TRAM
) + (axis
^ 1), PAL_NONE
);
3007 DrawTramCatenary(ti
, axis
== AXIS_X
? ROAD_X
: ROAD_Y
);
3010 if (IsRailWaypoint(ti
->tile
)) {
3011 /* Don't offset the waypoint graphics; they're always the same. */
3015 DrawRailTileSeq(ti
, t
, TO_BUILDINGS
, total_offset
, relocation
, palette
);
3018 void StationPickerDrawSprite(int x
, int y
, StationType st
, RailType railtype
, RoadType roadtype
, int image
)
3020 int32 total_offset
= 0;
3021 PaletteID pal
= COMPANY_SPRITE_COLOUR(_local_company
);
3022 const DrawTileSprites
*t
= GetStationTileLayout(st
, image
);
3023 const RailtypeInfo
*rti
= NULL
;
3025 if (railtype
!= INVALID_RAILTYPE
) {
3026 rti
= GetRailTypeInfo(railtype
);
3027 total_offset
= rti
->GetRailtypeSpriteOffset();
3030 SpriteID img
= t
->ground
.sprite
;
3031 RailTrackOffset overlay_offset
;
3032 if (rti
!= NULL
&& rti
->UsesOverlay() && SplitGroundSpriteForOverlay(NULL
, &img
, &overlay_offset
)) {
3033 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
3034 DrawSprite(img
, PAL_NONE
, x
, y
);
3035 DrawSprite(ground
+ overlay_offset
, PAL_NONE
, x
, y
);
3037 DrawSprite(img
+ total_offset
, HasBit(img
, PALETTE_MODIFIER_COLOUR
) ? pal
: PAL_NONE
, x
, y
);
3040 if (roadtype
== ROADTYPE_TRAM
) {
3041 DrawSprite(SPR_TRAMWAY_TRAM
+ (t
->ground
.sprite
== SPR_ROAD_PAVED_STRAIGHT_X
? 1 : 0), PAL_NONE
, x
, y
);
3044 /* Default waypoint has no railtype specific sprites */
3045 DrawRailTileSeqInGUI(x
, y
, t
, st
== STATION_WAYPOINT
? 0 : total_offset
, 0, pal
);
3048 static int GetSlopePixelZ_Station(TileIndex tile
, uint x
, uint y
)
3050 return GetTileMaxPixelZ(tile
);
3053 static Foundation
GetFoundation_Station(TileIndex tile
, Slope tileh
)
3055 return FlatteningFoundation(tileh
);
3058 static void GetTileDesc_Station(TileIndex tile
, TileDesc
*td
)
3060 td
->owner
[0] = GetTileOwner(tile
);
3061 if (IsDriveThroughStopTile(tile
)) {
3062 Owner road_owner
= INVALID_OWNER
;
3063 Owner tram_owner
= INVALID_OWNER
;
3064 RoadTypes rts
= GetRoadTypes(tile
);
3065 if (HasBit(rts
, ROADTYPE_ROAD
)) road_owner
= GetRoadOwner(tile
, ROADTYPE_ROAD
);
3066 if (HasBit(rts
, ROADTYPE_TRAM
)) tram_owner
= GetRoadOwner(tile
, ROADTYPE_TRAM
);
3068 /* Is there a mix of owners? */
3069 if ((tram_owner
!= INVALID_OWNER
&& tram_owner
!= td
->owner
[0]) ||
3070 (road_owner
!= INVALID_OWNER
&& road_owner
!= td
->owner
[0])) {
3072 if (road_owner
!= INVALID_OWNER
) {
3073 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_ROAD_OWNER
;
3074 td
->owner
[i
] = road_owner
;
3077 if (tram_owner
!= INVALID_OWNER
) {
3078 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_TRAM_OWNER
;
3079 td
->owner
[i
] = tram_owner
;
3083 td
->build_date
= BaseStation::GetByTile(tile
)->build_date
;
3085 if (HasStationTileRail(tile
)) {
3086 const StationSpec
*spec
= GetStationSpec(tile
);
3089 td
->station_class
= StationClass::Get(spec
->cls_id
)->name
;
3090 td
->station_name
= spec
->name
;
3092 if (spec
->grf_prop
.grffile
!= NULL
) {
3093 const GRFConfig
*gc
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
);
3094 td
->grf
= gc
->GetName();
3098 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(tile
));
3099 td
->rail_speed
= rti
->max_speed
;
3102 if (IsAirport(tile
)) {
3103 const AirportSpec
*as
= Station::GetByTile(tile
)->airport
.GetSpec();
3104 td
->airport_class
= AirportClass::Get(as
->cls_id
)->name
;
3105 td
->airport_name
= as
->name
;
3107 const AirportTileSpec
*ats
= AirportTileSpec::GetByTile(tile
);
3108 td
->airport_tile_name
= ats
->name
;
3110 if (as
->grf_prop
.grffile
!= NULL
) {
3111 const GRFConfig
*gc
= GetGRFConfig(as
->grf_prop
.grffile
->grfid
);
3112 td
->grf
= gc
->GetName();
3113 } else if (ats
->grf_prop
.grffile
!= NULL
) {
3114 const GRFConfig
*gc
= GetGRFConfig(ats
->grf_prop
.grffile
->grfid
);
3115 td
->grf
= gc
->GetName();
3120 switch (GetStationType(tile
)) {
3121 default: NOT_REACHED();
3122 case STATION_RAIL
: str
= STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION
; break;
3123 case STATION_AIRPORT
:
3124 str
= (IsHangar(tile
) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR
: STR_LAI_STATION_DESCRIPTION_AIRPORT
);
3126 case STATION_TRUCK
: str
= STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA
; break;
3127 case STATION_BUS
: str
= STR_LAI_STATION_DESCRIPTION_BUS_STATION
; break;
3128 case STATION_OILRIG
: str
= STR_INDUSTRY_NAME_OIL_RIG
; break;
3129 case STATION_DOCK
: str
= STR_LAI_STATION_DESCRIPTION_SHIP_DOCK
; break;
3130 case STATION_BUOY
: str
= STR_LAI_STATION_DESCRIPTION_BUOY
; break;
3131 case STATION_WAYPOINT
: str
= STR_LAI_STATION_DESCRIPTION_WAYPOINT
; break;
3137 static TrackStatus
GetTileRailwayStatus_Station(TileIndex tile
, DiagDirection side
)
3139 if (!HasStationRail(tile
) || IsStationTileBlocked(tile
)) return 0;
3141 return CombineTrackStatus(TrackBitsToTrackdirBits(GetRailStationTrackBits(tile
)), TRACKDIR_BIT_NONE
);
3144 static TrackStatus
GetTileRoadStatus_Station(TileIndex tile
, uint sub_mode
, DiagDirection side
)
3146 if (!IsRoadStop(tile
) || (GetRoadTypes(tile
) & sub_mode
) == 0) return 0;
3148 TrackBits trackbits
;
3150 if (IsStandardRoadStopTile(tile
)) {
3151 DiagDirection dir
= GetRoadStopDir(tile
);
3153 if (side
!= INVALID_DIAGDIR
&& dir
!= side
) return 0;
3155 trackbits
= DiagDirToDiagTrackBits(dir
);
3157 Axis axis
= GetRoadStopAxis(tile
);
3159 if (side
!= INVALID_DIAGDIR
&& axis
!= DiagDirToAxis(side
)) return 0;
3161 trackbits
= AxisToTrackBits(axis
);
3164 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits
), TRACKDIR_BIT_NONE
);
3167 static TrackdirBits
GetTileWaterwayStatus_Station(TileIndex tile
, DiagDirection side
)
3169 if (!IsBuoy(tile
)) return TRACKDIR_BIT_NONE
;
3171 /* buoy is coded as a station, it is always on open water */
3172 TrackBits trackbits
= TRACK_BIT_ALL
;
3173 /* remove tracks that connect NE map edge */
3174 if (TileX(tile
) == 0) trackbits
&= ~(TRACK_BIT_X
| TRACK_BIT_UPPER
| TRACK_BIT_RIGHT
);
3175 /* remove tracks that connect NW map edge */
3176 if (TileY(tile
) == 0) trackbits
&= ~(TRACK_BIT_Y
| TRACK_BIT_LEFT
| TRACK_BIT_UPPER
);
3178 return TrackBitsToTrackdirBits(trackbits
);
3182 static void TileLoop_Station(TileIndex tile
)
3184 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3185 * hardcoded.....not good */
3186 switch (GetStationType(tile
)) {
3187 case STATION_AIRPORT
:
3188 AirportTileAnimationTrigger(Station::GetByTile(tile
), tile
, AAT_TILELOOP
);
3192 if (!IsTileFlat(tile
)) break; // only handle water part
3194 case STATION_OILRIG
: //(station part)
3196 TileLoop_Water(tile
);
3204 static void AnimateTile_Station(TileIndex tile
)
3206 if (HasStationRail(tile
)) {
3207 AnimateStationTile(tile
);
3211 if (IsAirport(tile
)) {
3212 AnimateAirportTile(tile
);
3217 static bool ClickTile_Station(TileIndex tile
)
3219 const BaseStation
*bst
= BaseStation::GetByTile(tile
);
3221 if (bst
->facilities
& FACIL_WAYPOINT
) {
3222 ShowWaypointWindow(Waypoint::From(bst
));
3223 } else if (IsHangar(tile
)) {
3224 const Station
*st
= Station::From(bst
);
3225 ShowDepotWindow(st
->airport
.GetHangarTile(st
->airport
.GetHangarNum(tile
)), VEH_AIRCRAFT
);
3227 ShowStationViewWindow(bst
->index
);
3233 * Run the watched cargo callback for all houses in the catchment area.
3234 * @param st Station.
3236 void TriggerWatchedCargoCallbacks(Station
*st
)
3238 /* Collect cargoes accepted since the last big tick. */
3240 for (CargoID cid
= 0; cid
< NUM_CARGO
; cid
++) {
3241 if (HasBit(st
->goods
[cid
].acceptance_pickup
, GoodsEntry::GES_ACCEPTED_BIGTICK
)) SetBit(cargoes
, cid
);
3244 /* Anything to do? */
3245 if (cargoes
== 0) return;
3247 /* Loop over all houses in the catchment. */
3248 Rect r
= st
->GetCatchmentRect();
3249 TileArea
ta(TileXY(r
.left
, r
.top
), TileXY(r
.right
, r
.bottom
));
3250 TILE_AREA_LOOP(tile
, ta
) {
3251 if (IsHouseTile(tile
)) {
3252 WatchedCargoCallback(tile
, cargoes
);
3258 * This function is called for each station once every 250 ticks.
3259 * Not all stations will get the tick at the same time.
3260 * @param st the station receiving the tick.
3261 * @return true if the station is still valid (wasn't deleted)
3263 static bool StationHandleBigTick(BaseStation
*st
)
3265 if (!st
->IsInUse()) {
3266 if (++st
->delete_ctr
>= 8) delete st
;
3270 if (Station::IsExpected(st
)) {
3271 TriggerWatchedCargoCallbacks(Station::From(st
));
3273 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3274 ClrBit(Station::From(st
)->goods
[i
].acceptance_pickup
, GoodsEntry::GES_ACCEPTED_BIGTICK
);
3279 if ((st
->facilities
& FACIL_WAYPOINT
) == 0) UpdateStationAcceptance(Station::From(st
), true);
3284 static inline void byte_inc_sat(byte
*p
)
3290 static void UpdateStationRating(Station
*st
)
3292 bool waiting_changed
= false;
3294 byte_inc_sat(&st
->time_since_load
);
3295 byte_inc_sat(&st
->time_since_unload
);
3297 const CargoSpec
*cs
;
3298 FOR_ALL_CARGOSPECS(cs
) {
3299 GoodsEntry
*ge
= &st
->goods
[cs
->Index()];
3300 /* Slowly increase the rating back to his original level in the case we
3301 * didn't deliver cargo yet to this station. This happens when a bribe
3302 * failed while you didn't moved that cargo yet to a station. */
3303 if (!ge
->HasRating() && ge
->rating
< INITIAL_STATION_RATING
) {
3307 /* Only change the rating if we are moving this cargo */
3308 if (ge
->HasRating()) {
3309 byte_inc_sat(&ge
->time_since_pickup
);
3313 uint waiting
= ge
->cargo
.TotalCount();
3315 /* num_dests is at least 1 if there is any cargo as
3316 * INVALID_STATION is also a destination.
3318 uint num_dests
= (uint
)ge
->cargo
.Packets()->MapSize();
3320 /* Average amount of cargo per next hop, but prefer solitary stations
3321 * with only one or two next hops. They are allowed to have more
3322 * cargo waiting per next hop.
3323 * With manual cargo distribution waiting_avg = waiting / 2 as then
3324 * INVALID_STATION is the only destination.
3326 uint waiting_avg
= waiting
/ (num_dests
+ 1);
3328 if (HasBit(cs
->callback_mask
, CBM_CARGO_STATION_RATING_CALC
)) {
3329 /* Perform custom station rating. If it succeeds the speed, days in transit and
3330 * waiting cargo ratings must not be executed. */
3332 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3333 uint last_speed
= ge
->HasVehicleEverTriedLoading() ? ge
->last_speed
: 0xFF;
3335 uint32 var18
= min(ge
->time_since_pickup
, 0xFF) | (min(ge
->max_waiting_cargo
, 0xFFFF) << 8) | (min(last_speed
, 0xFF) << 24);
3336 /* Convert to the 'old' vehicle types */
3337 uint32 var10
= (st
->last_vehicle_type
== VEH_INVALID
) ? 0x0 : (st
->last_vehicle_type
+ 0x10);
3338 uint16 callback
= GetCargoCallback(CBID_CARGO_STATION_RATING_CALC
, var10
, var18
, cs
);
3339 if (callback
!= CALLBACK_FAILED
) {
3341 rating
= GB(callback
, 0, 14);
3343 /* Simulate a 15 bit signed value */
3344 if (HasBit(callback
, 14)) rating
-= 0x4000;
3349 int b
= ge
->last_speed
- 85;
3350 if (b
>= 0) rating
+= b
>> 2;
3352 byte waittime
= ge
->time_since_pickup
;
3353 if (st
->last_vehicle_type
== VEH_SHIP
) waittime
>>= 2;
3355 (rating
+= 25, waittime
> 12) ||
3356 (rating
+= 25, waittime
> 6) ||
3357 (rating
+= 45, waittime
> 3) ||
3358 (rating
+= 35, true);
3360 (rating
-= 90, ge
->max_waiting_cargo
> 1500) ||
3361 (rating
+= 55, ge
->max_waiting_cargo
> 1000) ||
3362 (rating
+= 35, ge
->max_waiting_cargo
> 600) ||
3363 (rating
+= 10, ge
->max_waiting_cargo
> 300) ||
3364 (rating
+= 20, ge
->max_waiting_cargo
> 100) ||
3365 (rating
+= 10, true);
3368 if (Company::IsValidID(st
->owner
) && HasBit(st
->town
->statues
, st
->owner
)) rating
+= 26;
3370 byte age
= ge
->last_age
;
3372 (rating
+= 10, age
>= 2) ||
3373 (rating
+= 10, age
>= 1) ||
3374 (rating
+= 13, true);
3377 int or_
= ge
->rating
; // old rating
3379 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3380 ge
->rating
= rating
= or_
+ Clamp(Clamp(rating
, 0, 255) - or_
, -2, 2);
3382 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3383 * remove some random amount of goods from the station */
3384 if (rating
<= 64 && waiting_avg
>= 100) {
3385 int dec
= Random() & 0x1F;
3386 if (waiting_avg
< 200) dec
&= 7;
3387 waiting
-= (dec
+ 1) * num_dests
;
3388 waiting_changed
= true;
3391 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3392 if (rating
<= 127 && waiting
!= 0) {
3393 uint32 r
= Random();
3394 if (rating
<= (int)GB(r
, 0, 7)) {
3395 /* Need to have int, otherwise it will just overflow etc. */
3396 waiting
= max((int)waiting
- (int)((GB(r
, 8, 2) - 1) * num_dests
), 0);
3397 waiting_changed
= true;
3401 /* At some point we really must cap the cargo. Previously this
3402 * was a strict 4095, but now we'll have a less strict, but
3403 * increasingly aggressive truncation of the amount of cargo. */
3404 static const uint WAITING_CARGO_THRESHOLD
= 1 << 12;
3405 static const uint WAITING_CARGO_CUT_FACTOR
= 1 << 6;
3406 static const uint MAX_WAITING_CARGO
= 1 << 15;
3408 if (waiting
> WAITING_CARGO_THRESHOLD
) {
3409 uint difference
= waiting
- WAITING_CARGO_THRESHOLD
;
3410 waiting
-= (difference
/ WAITING_CARGO_CUT_FACTOR
);
3412 waiting
= min(waiting
, MAX_WAITING_CARGO
);
3413 waiting_changed
= true;
3416 /* We can't truncate cargo that's already reserved for loading.
3417 * Thus StoredCount() here. */
3418 if (waiting_changed
&& waiting
< ge
->cargo
.AvailableCount()) {
3419 /* Feed back the exact own waiting cargo at this station for the
3420 * next rating calculation. */
3421 ge
->max_waiting_cargo
= 0;
3423 /* If truncating also punish the source stations' ratings to
3424 * decrease the flow of incoming cargo. */
3426 StationCargoAmountMap waiting_per_source
;
3427 ge
->cargo
.Truncate(ge
->cargo
.AvailableCount() - waiting
, &waiting_per_source
);
3428 for (StationCargoAmountMap::iterator
i(waiting_per_source
.begin()); i
!= waiting_per_source
.end(); ++i
) {
3429 Station
*source_station
= Station::GetIfValid(i
->first
);
3430 if (source_station
== NULL
) continue;
3432 GoodsEntry
&source_ge
= source_station
->goods
[cs
->Index()];
3433 source_ge
.max_waiting_cargo
= max(source_ge
.max_waiting_cargo
, i
->second
);
3436 /* If the average number per next hop is low, be more forgiving. */
3437 ge
->max_waiting_cargo
= waiting_avg
;
3443 StationID index
= st
->index
;
3444 if (waiting_changed
) {
3445 SetWindowDirty(WC_STATION_VIEW
, index
); // update whole window
3447 SetWindowWidgetDirty(WC_STATION_VIEW
, index
, WID_SV_ACCEPT_RATING_LIST
); // update only ratings list
3452 * Reroute cargo of type c at station st or in any vehicles unloading there.
3453 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3454 * @param st Station to be rerouted at.
3455 * @param c Type of cargo.
3456 * @param avoid Original next hop of cargo, avoid this.
3457 * @param avoid2 Another station to be avoided when rerouting.
3459 void RerouteCargo(Station
*st
, CargoID c
, StationID avoid
, StationID avoid2
)
3461 GoodsEntry
&ge
= st
->goods
[c
];
3463 /* Reroute cargo in station. */
3464 ge
.cargo
.Reroute(UINT_MAX
, &ge
.cargo
, avoid
, avoid2
, &ge
);
3466 /* Reroute cargo staged to be transfered. */
3467 for (std::list
<Vehicle
*>::iterator
it(st
->loading_vehicles
.begin()); it
!= st
->loading_vehicles
.end(); ++it
) {
3468 for (Vehicle
*v
= *it
; v
!= NULL
; v
= v
->Next()) {
3469 if (v
->cargo_type
!= c
) continue;
3470 v
->cargo
.Reroute(UINT_MAX
, &v
->cargo
, avoid
, avoid2
, &ge
);
3476 * Check all next hops of cargo packets in this station for existance of a
3477 * a valid link they may use to travel on. Reroute any cargo not having a valid
3478 * link and remove timed out links found like this from the linkgraph. We're
3479 * not all links here as that is expensive and useless. A link no one is using
3480 * doesn't hurt either.
3481 * @param from Station to check.
3483 void DeleteStaleLinks(Station
*from
)
3485 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
3486 GoodsEntry
&ge
= from
->goods
[c
];
3487 LinkGraph
*lg
= LinkGraph::GetIfValid(ge
.link_graph
);
3488 if (lg
== NULL
) continue;
3489 Node node
= (*lg
)[ge
.node
];
3490 for (EdgeIterator
it(node
.Begin()); it
!= node
.End();) {
3491 Edge edge
= it
->second
;
3492 Station
*to
= Station::Get((*lg
)[it
->first
].Station());
3493 assert(to
->goods
[c
].node
== it
->first
);
3494 ++it
; // Do that before removing the edge. Anything else may crash.
3495 assert(_date
>= edge
.LastUpdate());
3496 uint timeout
= LinkGraph::MIN_TIMEOUT_DISTANCE
+ (DistanceManhattan(from
->xy
, to
->xy
) >> 3);
3497 if ((uint
)(_date
- edge
.LastUpdate()) > timeout
) {
3498 /* Have all vehicles refresh their next hops before deciding to
3499 * remove the node. */
3500 bool updated
= false;
3502 FOR_ALL_ORDER_LISTS(l
) {
3503 bool found_from
= false;
3504 bool found_to
= false;
3505 for (Order
*order
= l
->GetFirstOrder(); order
!= NULL
; order
= order
->next
) {
3506 if (!order
->IsType(OT_GOTO_STATION
) && !order
->IsType(OT_IMPLICIT
)) continue;
3507 if (order
->GetDestination() == from
->index
) {
3509 if (found_to
) break;
3510 } else if (order
->GetDestination() == to
->index
) {
3512 if (found_from
) break;
3515 if (!found_to
|| !found_from
) continue;
3516 for (Vehicle
*v
= l
->GetFirstSharedVehicle(); !updated
&& v
!= NULL
; v
= v
->NextShared()) {
3517 /* There is potential for optimization here:
3518 * - Usually consists of the same order list are the same. It's probably better to
3519 * first check the first of each list, then the second of each list and so on.
3520 * - We could try to figure out if we've seen a consist with the same cargo on the
3521 * same list already and if the consist can actually carry the cargo we're looking
3522 * for. With conditional and refit orders this is not quite trivial, though. */
3523 LinkRefresher::Run(v
, false); // Don't allow merging. Otherwise lg might get deleted.
3524 if (edge
.LastUpdate() == _date
) updated
= true;
3529 /* If it's still considered dead remove it. */
3530 node
.RemoveEdge(to
->goods
[c
].node
);
3531 ge
.flows
.DeleteFlows(to
->index
);
3532 RerouteCargo(from
, c
, to
->index
, from
->index
);
3534 } else if (edge
.LastUnrestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastUnrestrictedUpdate()) > timeout
) {
3536 ge
.flows
.RestrictFlows(to
->index
);
3537 RerouteCargo(from
, c
, to
->index
, from
->index
);
3538 } else if (edge
.LastRestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastRestrictedUpdate()) > timeout
) {
3542 assert(_date
>= lg
->LastCompression());
3543 if ((uint
)(_date
- lg
->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL
) {
3550 * Increase capacity for a link stat given by station cargo and next hop.
3551 * @param st Station to get the link stats from.
3552 * @param cargo Cargo to increase stat for.
3553 * @param next_station_id Station the consist will be travelling to next.
3554 * @param capacity Capacity to add to link stat.
3555 * @param usage Usage to add to link stat. If UINT_MAX refresh the link instead of increasing.
3557 void IncreaseStats(Station
*st
, CargoID cargo
, StationID next_station_id
, uint capacity
, uint usage
)
3559 GoodsEntry
&ge1
= st
->goods
[cargo
];
3560 Station
*st2
= Station::Get(next_station_id
);
3561 GoodsEntry
&ge2
= st2
->goods
[cargo
];
3562 LinkGraph
*lg
= NULL
;
3563 if (ge1
.link_graph
== INVALID_LINK_GRAPH
) {
3564 if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3565 if (LinkGraph::CanAllocateItem()) {
3566 lg
= new LinkGraph(cargo
);
3567 LinkGraphSchedule::Instance()->Queue(lg
);
3568 ge2
.link_graph
= lg
->index
;
3569 ge2
.node
= lg
->AddNode(st2
);
3571 DEBUG(misc
, 0, "Can't allocate link graph");
3574 lg
= LinkGraph::Get(ge2
.link_graph
);
3577 ge1
.link_graph
= lg
->index
;
3578 ge1
.node
= lg
->AddNode(st
);
3580 } else if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3581 lg
= LinkGraph::Get(ge1
.link_graph
);
3582 ge2
.link_graph
= lg
->index
;
3583 ge2
.node
= lg
->AddNode(st2
);
3585 lg
= LinkGraph::Get(ge1
.link_graph
);
3586 if (ge1
.link_graph
!= ge2
.link_graph
) {
3587 LinkGraph
*lg2
= LinkGraph::Get(ge2
.link_graph
);
3588 if (lg
->Size() < lg2
->Size()) {
3589 LinkGraphSchedule::Instance()->Unqueue(lg
);
3590 lg2
->Merge(lg
); // Updates GoodsEntries of lg
3593 LinkGraphSchedule::Instance()->Unqueue(lg2
);
3594 lg
->Merge(lg2
); // Updates GoodsEntries of lg2
3599 (*lg
)[ge1
.node
].UpdateEdge(ge2
.node
, capacity
, usage
);
3604 * Increase capacity for all link stats associated with vehicles in the given consist.
3605 * @param st Station to get the link stats from.
3606 * @param front First vehicle in the consist.
3607 * @param next_station_id Station the consist will be travelling to next.
3609 void IncreaseStats(Station
*st
, const Vehicle
*front
, StationID next_station_id
)
3611 for (const Vehicle
*v
= front
; v
!= NULL
; v
= v
->Next()) {
3612 if (v
->refit_cap
> 0) {
3613 /* The cargo count can indeed be higher than the refit_cap if
3614 * wagons have been auto-replaced and subsequently auto-
3615 * refitted to a higher capacity. The cargo gets redistributed
3616 * among the wagons in that case.
3617 * As usage is not such an important figure anyway we just
3618 * ignore the additional cargo then.*/
3619 IncreaseStats(st
, v
->cargo_type
, next_station_id
, v
->refit_cap
,
3620 min(v
->refit_cap
, v
->cargo
.StoredCount()));
3625 /* called for every station each tick */
3626 static void StationHandleSmallTick(BaseStation
*st
)
3628 if ((st
->facilities
& FACIL_WAYPOINT
) != 0 || !st
->IsInUse()) return;
3630 byte b
= st
->delete_ctr
+ 1;
3631 if (b
>= STATION_RATING_TICKS
) b
= 0;
3634 if (b
== 0) UpdateStationRating(Station::From(st
));
3637 void OnTick_Station()
3639 if (_game_mode
== GM_EDITOR
) return;
3642 FOR_ALL_BASE_STATIONS(st
) {
3643 StationHandleSmallTick(st
);
3645 /* Clean up the link graph about once a week. */
3646 if (Station::IsExpected(st
) && (_tick_counter
+ st
->index
) % STATION_LINKGRAPH_TICKS
== 0) {
3647 DeleteStaleLinks(Station::From(st
));
3650 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3651 * Station index is included so that triggers are not all done
3652 * at the same time. */
3653 if ((_tick_counter
+ st
->index
) % STATION_ACCEPTANCE_TICKS
== 0) {
3654 /* Stop processing this station if it was deleted */
3655 if (!StationHandleBigTick(st
)) continue;
3656 TriggerStationAnimation(st
, st
->xy
, SAT_250_TICKS
);
3657 if (Station::IsExpected(st
)) AirportAnimationTrigger(Station::From(st
), AAT_STATION_250_TICKS
);
3662 /** Monthly loop for stations. */
3663 void StationMonthlyLoop()
3667 FOR_ALL_STATIONS(st
) {
3668 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3669 GoodsEntry
*ge
= &st
->goods
[i
];
3670 SB(ge
->acceptance_pickup
, GoodsEntry::GES_LAST_MONTH
, 1, GB(ge
->acceptance_pickup
, GoodsEntry::GES_CURRENT_MONTH
, 1));
3671 ClrBit(ge
->acceptance_pickup
, GoodsEntry::GES_CURRENT_MONTH
);
3677 void ModifyStationRatingAround(TileIndex tile
, Owner owner
, int amount
, uint radius
)
3681 FOR_ALL_STATIONS(st
) {
3682 if (st
->owner
== owner
&&
3683 DistanceManhattan(tile
, st
->xy
) <= radius
) {
3684 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3685 GoodsEntry
*ge
= &st
->goods
[i
];
3687 if (ge
->acceptance_pickup
!= 0) {
3688 ge
->rating
= Clamp(ge
->rating
+ amount
, 0, 255);
3695 static uint
UpdateStationWaiting(Station
*st
, CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
)
3697 /* We can't allocate a CargoPacket? Then don't do anything
3698 * at all; i.e. just discard the incoming cargo. */
3699 if (!CargoPacket::CanAllocateItem()) return 0;
3701 GoodsEntry
&ge
= st
->goods
[type
];
3702 amount
+= ge
.amount_fract
;
3703 ge
.amount_fract
= GB(amount
, 0, 8);
3706 /* No new "real" cargo item yet. */
3707 if (amount
== 0) return 0;
3709 StationID next
= ge
.GetVia(st
->index
);
3710 ge
.cargo
.Append(new CargoPacket(st
->index
, st
->xy
, amount
, source_type
, source_id
), next
);
3711 LinkGraph
*lg
= NULL
;
3712 if (ge
.link_graph
== INVALID_LINK_GRAPH
) {
3713 if (LinkGraph::CanAllocateItem()) {
3714 lg
= new LinkGraph(type
);
3715 LinkGraphSchedule::Instance()->Queue(lg
);
3716 ge
.link_graph
= lg
->index
;
3717 ge
.node
= lg
->AddNode(st
);
3719 DEBUG(misc
, 0, "Can't allocate link graph");
3722 lg
= LinkGraph::Get(ge
.link_graph
);
3724 if (lg
!= NULL
) (*lg
)[ge
.node
].UpdateSupply(amount
);
3726 if (!ge
.HasRating()) {
3727 InvalidateWindowData(WC_STATION_LIST
, st
->index
);
3728 SetBit(ge
.acceptance_pickup
, GoodsEntry::GES_PICKUP
);
3731 TriggerStationRandomisation(st
, st
->xy
, SRT_NEW_CARGO
, type
);
3732 TriggerStationAnimation(st
, st
->xy
, SAT_NEW_CARGO
, type
);
3733 AirportAnimationTrigger(st
, AAT_STATION_NEW_CARGO
, type
);
3735 SetWindowDirty(WC_STATION_VIEW
, st
->index
);
3736 st
->MarkTilesDirty(true);
3740 static bool IsUniqueStationName(const char *name
)
3744 FOR_ALL_STATIONS(st
) {
3745 if (st
->name
!= NULL
&& strcmp(st
->name
, name
) == 0) return false;
3753 * @param tile unused
3754 * @param flags operation to perform
3755 * @param p1 station ID that is to be renamed
3757 * @param text the new name or an empty string when resetting to the default
3758 * @return the cost of this operation or an error
3760 CommandCost
CmdRenameStation(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
3762 Station
*st
= Station::GetIfValid(p1
);
3763 if (st
== NULL
) return CMD_ERROR
;
3765 CommandCost ret
= CheckOwnership(st
->owner
);
3766 if (ret
.Failed()) return ret
;
3768 bool reset
= StrEmpty(text
);
3771 if (Utf8StringLength(text
) >= MAX_LENGTH_STATION_NAME_CHARS
) return CMD_ERROR
;
3772 if (!IsUniqueStationName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
3775 if (flags
& DC_EXEC
) {
3777 st
->name
= reset
? NULL
: strdup(text
);
3779 st
->UpdateVirtCoord();
3780 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 1);
3783 return CommandCost();
3787 * Find all stations around a rectangular producer (industry, house, headquarter, ...)
3789 * @param location The location/area of the producer
3790 * @param stations The list to store the stations in
3792 void FindStationsAroundTiles(const TileArea
&location
, StationList
*stations
)
3794 /* area to search = producer plus station catchment radius */
3795 uint max_rad
= (_settings_game
.station
.modified_catchment
? MAX_CATCHMENT
: CA_UNMODIFIED
);
3797 uint x
= TileX(location
.tile
);
3798 uint y
= TileY(location
.tile
);
3800 uint min_x
= (x
> max_rad
) ? x
- max_rad
: 0;
3801 uint max_x
= x
+ location
.w
+ max_rad
;
3802 uint min_y
= (y
> max_rad
) ? y
- max_rad
: 0;
3803 uint max_y
= y
+ location
.h
+ max_rad
;
3805 if (min_x
== 0 && _settings_game
.construction
.freeform_edges
) min_x
= 1;
3806 if (min_y
== 0 && _settings_game
.construction
.freeform_edges
) min_y
= 1;
3807 if (max_x
>= MapSizeX()) max_x
= MapSizeX() - 1;
3808 if (max_y
>= MapSizeY()) max_y
= MapSizeY() - 1;
3810 for (uint cy
= min_y
; cy
< max_y
; cy
++) {
3811 for (uint cx
= min_x
; cx
< max_x
; cx
++) {
3812 TileIndex cur_tile
= TileXY(cx
, cy
);
3813 if (!IsStationTile(cur_tile
)) continue;
3815 Station
*st
= Station::GetByTile(cur_tile
);
3816 /* st can be NULL in case of waypoints */
3817 if (st
== NULL
) continue;
3819 if (_settings_game
.station
.modified_catchment
) {
3820 int rad
= st
->GetCatchmentRadius();
3824 if (rad_x
< -rad
|| rad_x
>= rad
+ location
.w
) continue;
3825 if (rad_y
< -rad
|| rad_y
>= rad
+ location
.h
) continue;
3828 /* Insert the station in the set. This will fail if it has
3829 * already been added.
3831 stations
->Include(st
);
3837 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
3838 * @return pointer to a StationList containing all stations found
3840 const StationList
*StationFinder::GetStations()
3842 if (this->tile
!= INVALID_TILE
) {
3843 FindStationsAroundTiles(*this, &this->stations
);
3844 this->tile
= INVALID_TILE
;
3846 return &this->stations
;
3849 uint
MoveGoodsToStation(CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
, const StationList
*all_stations
)
3851 /* Return if nothing to do. Also the rounding below fails for 0. */
3852 if (amount
== 0) return 0;
3854 Station
*st1
= NULL
; // Station with best rating
3855 Station
*st2
= NULL
; // Second best station
3856 uint best_rating1
= 0; // rating of st1
3857 uint best_rating2
= 0; // rating of st2
3859 for (Station
* const *st_iter
= all_stations
->Begin(); st_iter
!= all_stations
->End(); ++st_iter
) {
3860 Station
*st
= *st_iter
;
3862 /* Is the station reserved exclusively for somebody else? */
3863 if (st
->town
->exclusive_counter
> 0 && st
->town
->exclusivity
!= st
->owner
) continue;
3865 if (st
->goods
[type
].rating
== 0) continue; // Lowest possible rating, better not to give cargo anymore
3867 if (_settings_game
.order
.selectgoods
&& !st
->goods
[type
].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
3869 if (IsCargoInClass(type
, CC_PASSENGERS
)) {
3870 if (st
->facilities
== FACIL_TRUCK_STOP
) continue; // passengers are never served by just a truck stop
3872 if (st
->facilities
== FACIL_BUS_STOP
) continue; // non-passengers are never served by just a bus stop
3875 /* This station can be used, add it to st1/st2 */
3876 if (st1
== NULL
|| st
->goods
[type
].rating
>= best_rating1
) {
3877 st2
= st1
; best_rating2
= best_rating1
; st1
= st
; best_rating1
= st
->goods
[type
].rating
;
3878 } else if (st2
== NULL
|| st
->goods
[type
].rating
>= best_rating2
) {
3879 st2
= st
; best_rating2
= st
->goods
[type
].rating
;
3883 /* no stations around at all? */
3884 if (st1
== NULL
) return 0;
3886 /* From now we'll calculate with fractal cargo amounts.
3887 * First determine how much cargo we really have. */
3888 amount
*= best_rating1
+ 1;
3891 /* only one station around */
3892 return UpdateStationWaiting(st1
, type
, amount
, source_type
, source_id
);
3895 /* several stations around, the best two (highest rating) are in st1 and st2 */
3896 assert(st1
!= NULL
);
3897 assert(st2
!= NULL
);
3898 assert(best_rating1
!= 0 || best_rating2
!= 0);
3900 /* Then determine the amount the worst station gets. We do it this way as the
3901 * best should get a bonus, which in this case is the rounding difference from
3902 * this calculation. In reality that will mean the bonus will be pretty low.
3903 * Nevertheless, the best station should always get the most cargo regardless
3904 * of rounding issues. */
3905 uint worst_cargo
= amount
* best_rating2
/ (best_rating1
+ best_rating2
);
3906 assert(worst_cargo
<= (amount
- worst_cargo
));
3908 /* And then send the cargo to the stations! */
3909 uint moved
= UpdateStationWaiting(st1
, type
, amount
- worst_cargo
, source_type
, source_id
);
3910 /* These two UpdateStationWaiting's can't be in the statement as then the order
3911 * of execution would be undefined and that could cause desyncs with callbacks. */
3912 return moved
+ UpdateStationWaiting(st2
, type
, worst_cargo
, source_type
, source_id
);
3915 void BuildOilRig(TileIndex tile
)
3917 if (!Station::CanAllocateItem()) {
3918 DEBUG(misc
, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile
);
3922 if (!Dock::CanAllocateItem()) {
3923 DEBUG(misc
, 0, "Can't allocate dock for oilrig at 0x%X, reverting to oilrig only", tile
);
3927 Station
*st
= new Station(tile
);
3928 st
->town
= ClosestTownFromTile(tile
, UINT_MAX
);
3930 st
->string_id
= GenerateStationName(st
, tile
, STATIONNAMING_OILRIG
);
3932 assert(IsIndustryTile(tile
));
3933 DeleteAnimatedTile(tile
);
3934 MakeOilrig(tile
, st
->index
, GetWaterClass(tile
));
3936 st
->owner
= OWNER_NONE
;
3937 st
->docks
= new Dock(tile
);
3938 st
->dock_area
= TileArea(tile
, 1, 1);
3939 st
->airport
.type
= AT_OILRIG
;
3940 st
->airport
.Add(tile
);
3941 st
->facilities
= FACIL_AIRPORT
| FACIL_DOCK
;
3942 st
->build_date
= _date
;
3944 st
->rect
.BeforeAddTile(tile
, StationRect::ADD_FORCE
);
3946 st
->UpdateVirtCoord();
3947 UpdateStationAcceptance(st
, false);
3948 st
->RecomputeIndustriesNear();
3951 void DeleteOilRig(TileIndex tile
)
3953 Station
*st
= Station::GetByTile(tile
);
3955 MakeWaterKeepingClass(tile
, OWNER_NONE
);
3959 st
->dock_area
.Clear();
3960 st
->airport
.Clear();
3961 st
->facilities
&= ~(FACIL_AIRPORT
| FACIL_DOCK
);
3962 st
->airport
.flags
= 0;
3964 st
->rect
.AfterRemoveTile(st
, tile
);
3966 st
->UpdateVirtCoord();
3967 st
->RecomputeIndustriesNear();
3968 if (!st
->IsInUse()) delete st
;
3971 static void ChangeTileOwner_Station(TileIndex tile
, Owner old_owner
, Owner new_owner
)
3973 if (IsRoadStopTile(tile
)) {
3974 for (RoadType rt
= ROADTYPE_ROAD
; rt
< ROADTYPE_END
; rt
++) {
3975 /* Update all roadtypes, no matter if they are present */
3976 if (GetRoadOwner(tile
, rt
) == old_owner
) {
3977 if (HasTileRoadType(tile
, rt
)) {
3978 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
3979 Company::Get(old_owner
)->infrastructure
.road
[rt
] -= 2;
3980 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.road
[rt
] += 2;
3982 SetRoadOwner(tile
, rt
, new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
);
3987 if (!IsTileOwner(tile
, old_owner
)) return;
3989 if (new_owner
!= INVALID_OWNER
) {
3990 /* Update company infrastructure counts. Only do it here
3991 * if the new owner is valid as otherwise the clear
3992 * command will do it for us. No need to dirty windows
3993 * here, we'll redraw the whole screen anyway.*/
3994 Company
*old_company
= Company::Get(old_owner
);
3995 Company
*new_company
= Company::Get(new_owner
);
3997 /* Update counts for underlying infrastructure. */
3998 switch (GetStationType(tile
)) {
4000 case STATION_WAYPOINT
:
4001 if (!IsStationTileBlocked(tile
)) {
4002 old_company
->infrastructure
.rail
[GetRailType(tile
)]--;
4003 new_company
->infrastructure
.rail
[GetRailType(tile
)]++;
4009 /* Road stops were already handled above. */
4014 if (GetWaterClass(tile
) == WATER_CLASS_CANAL
) {
4015 old_company
->infrastructure
.water
--;
4016 new_company
->infrastructure
.water
++;
4024 /* Update station tile count. */
4025 if (!IsBuoy(tile
) && !IsAirport(tile
)) {
4026 old_company
->infrastructure
.station
--;
4027 new_company
->infrastructure
.station
++;
4030 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4031 SetTileOwner(tile
, new_owner
);
4032 InvalidateWindowClassesData(WC_STATION_LIST
, 0);
4034 if (IsDriveThroughStopTile(tile
)) {
4035 /* Remove the drive-through road stop */
4036 DoCommand(tile
, 1 | 1 << 8, (GetStationType(tile
) == STATION_TRUCK
) ? ROADSTOP_TRUCK
: ROADSTOP_BUS
, DC_EXEC
| DC_BANKRUPT
, CMD_REMOVE_ROAD_STOP
);
4037 assert(IsNormalRoadTile(tile
));
4038 /* Change owner of tile and all roadtypes */
4039 ChangeTileOwner(tile
, old_owner
, new_owner
);
4041 DoCommand(tile
, 0, 0, DC_EXEC
| DC_BANKRUPT
, CMD_LANDSCAPE_CLEAR
);
4042 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4043 * Update owner of buoy if it was not removed (was in orders).
4044 * Do not update when owned by OWNER_WATER (sea and rivers). */
4045 if ((IsWaterTile(tile
) || IsBuoyTile(tile
)) && IsTileOwner(tile
, old_owner
)) SetTileOwner(tile
, OWNER_NONE
);
4051 * Check if a drive-through road stop tile can be cleared.
4052 * Road stops built on town-owned roads check the conditions
4053 * that would allow clearing of the original road.
4054 * @param tile road stop tile to check
4055 * @param flags command flags
4056 * @return true if the road can be cleared
4058 static bool CanRemoveRoadWithStop(TileIndex tile
, DoCommandFlag flags
)
4060 /* Yeah... water can always remove stops, right? */
4061 if (_current_company
== OWNER_WATER
) return true;
4063 RoadTypes rts
= GetRoadTypes(tile
);
4064 if (HasBit(rts
, ROADTYPE_TRAM
)) {
4065 Owner tram_owner
= GetRoadOwner(tile
, ROADTYPE_TRAM
);
4066 if (tram_owner
!= OWNER_NONE
&& CheckOwnership(tram_owner
).Failed()) return false;
4068 if (HasBit(rts
, ROADTYPE_ROAD
)) {
4069 Owner road_owner
= GetRoadOwner(tile
, ROADTYPE_ROAD
);
4070 if (road_owner
!= OWNER_TOWN
) {
4071 if (road_owner
!= OWNER_NONE
&& CheckOwnership(road_owner
).Failed()) return false;
4073 if (CheckAllowRemoveRoad(tile
, GetAnyRoadBits(tile
, ROADTYPE_ROAD
), OWNER_TOWN
, ROADTYPE_ROAD
, flags
).Failed()) return false;
4081 * Clear a single tile of a station.
4082 * @param tile The tile to clear.
4083 * @param flags The DoCommand flags related to the "command".
4084 * @return The cost, or error of clearing.
4086 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
)
4088 if (flags
& DC_AUTO
) {
4089 switch (GetStationType(tile
)) {
4091 case STATION_RAIL
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD
);
4092 case STATION_WAYPOINT
: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
4093 case STATION_AIRPORT
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
4094 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
);
4095 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
);
4096 case STATION_BUOY
: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY
);
4097 case STATION_DOCK
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST
);
4098 case STATION_OILRIG
:
4099 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG
);
4100 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY
);
4104 switch (GetStationType(tile
)) {
4105 case STATION_RAIL
: return RemoveRailStation(tile
, flags
);
4106 case STATION_WAYPOINT
: return RemoveRailWaypoint(tile
, flags
);
4107 case STATION_AIRPORT
: return RemoveAirport(tile
, flags
);
4109 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4110 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST
);
4112 return RemoveRoadStop(tile
, flags
);
4114 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4115 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST
);
4117 return RemoveRoadStop(tile
, flags
);
4118 case STATION_BUOY
: return RemoveBuoy(tile
, flags
);
4119 case STATION_DOCK
: return RemoveDock(tile
, flags
);
4126 static CommandCost
TerraformTile_Station(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
4128 if (_settings_game
.construction
.build_on_slopes
&& AutoslopeEnabled()) {
4129 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4130 * TTDP does not call it.
4132 if (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
)) {
4133 switch (GetStationType(tile
)) {
4134 case STATION_WAYPOINT
:
4135 case STATION_RAIL
: {
4136 DiagDirection direction
= AxisToDiagDir(GetRailStationAxis(tile
));
4137 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4138 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4139 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4142 case STATION_AIRPORT
:
4143 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4147 DiagDirection direction
= GetRoadStopDir(tile
);
4148 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4149 if (IsDriveThroughStopTile(tile
)) {
4150 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4152 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4159 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
4163 * Get flow for a station.
4164 * @param st Station to get flow for.
4165 * @return Flow for st.
4167 uint
FlowStat::GetShare(StationID st
) const
4170 for (SharesMap::const_iterator it
= this->shares
.begin(); it
!= this->shares
.end(); ++it
) {
4171 if (it
->second
== st
) {
4172 return it
->first
- prev
;
4181 * Get a station a package can be routed to, but exclude the given ones.
4182 * @param excluded StationID not to be selected.
4183 * @param excluded2 Another StationID not to be selected.
4184 * @return A station ID from the shares map.
4186 StationID
FlowStat::GetVia(StationID excluded
, StationID excluded2
) const
4188 if (this->unrestricted
== 0) return INVALID_STATION
;
4189 assert(!this->shares
.empty());
4190 SharesMap::const_iterator it
= this->shares
.upper_bound(RandomRange(this->unrestricted
));
4191 assert(it
!= this->shares
.end() && it
->first
<= this->unrestricted
);
4192 if (it
->second
!= excluded
&& it
->second
!= excluded2
) return it
->second
;
4194 /* We've hit one of the excluded stations.
4195 * Draw another share, from outside its range. */
4197 uint end
= it
->first
;
4198 uint begin
= (it
== this->shares
.begin() ? 0 : (--it
)->first
);
4199 uint interval
= end
- begin
;
4200 if (interval
>= this->unrestricted
) return INVALID_STATION
; // Only one station in the map.
4201 uint new_max
= this->unrestricted
- interval
;
4202 uint rand
= RandomRange(new_max
);
4203 SharesMap::const_iterator it2
= (rand
< begin
) ? this->shares
.upper_bound(rand
) :
4204 this->shares
.upper_bound(rand
+ interval
);
4205 assert(it2
!= this->shares
.end() && it2
->first
<= this->unrestricted
);
4206 if (it2
->second
!= excluded
&& it2
->second
!= excluded2
) return it2
->second
;
4208 /* We've hit the second excluded station.
4209 * Same as before, only a bit more complicated. */
4211 uint end2
= it2
->first
;
4212 uint begin2
= (it2
== this->shares
.begin() ? 0 : (--it2
)->first
);
4213 uint interval2
= end2
- begin2
;
4214 if (interval2
>= new_max
) return INVALID_STATION
; // Only the two excluded stations in the map.
4215 new_max
-= interval2
;
4216 if (begin
> begin2
) {
4217 Swap(begin
, begin2
);
4219 Swap(interval
, interval2
);
4221 rand
= RandomRange(new_max
);
4222 SharesMap::const_iterator it3
= this->shares
.upper_bound(this->unrestricted
);
4224 it3
= this->shares
.upper_bound(rand
);
4225 } else if (rand
< begin2
- interval
) {
4226 it3
= this->shares
.upper_bound(rand
+ interval
);
4228 it3
= this->shares
.upper_bound(rand
+ interval
+ interval2
);
4230 assert(it3
!= this->shares
.end() && it3
->first
<= this->unrestricted
);
4235 * Reduce all flows to minimum capacity so that they don't get in the way of
4236 * link usage statistics too much. Keep them around, though, to continue
4237 * routing any remaining cargo.
4239 void FlowStat::Invalidate()
4241 assert(!this->shares
.empty());
4242 SharesMap new_shares
;
4244 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4245 new_shares
[++i
] = it
->second
;
4246 if (it
->first
== this->unrestricted
) this->unrestricted
= i
;
4248 this->shares
.swap(new_shares
);
4249 assert(!this->shares
.empty() && this->unrestricted
<= (--this->shares
.end())->first
);
4253 * Change share for specified station. By specifing INT_MIN as parameter you
4254 * can erase a share. Newly added flows will be unrestricted.
4255 * @param st Next Hop to be removed.
4256 * @param flow Share to be added or removed.
4258 void FlowStat::ChangeShare(StationID st
, int flow
)
4260 /* We assert only before changing as afterwards the shares can actually
4261 * be empty. In that case the whole flow stat must be deleted then. */
4262 assert(!this->shares
.empty());
4264 uint removed_shares
= 0;
4265 uint added_shares
= 0;
4266 uint last_share
= 0;
4267 SharesMap new_shares
;
4268 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4269 if (it
->second
== st
) {
4271 uint share
= it
->first
- last_share
;
4272 if (flow
== INT_MIN
|| (uint
)(-flow
) >= share
) {
4273 removed_shares
+= share
;
4274 if (it
->first
<= this->unrestricted
) this->unrestricted
-= share
;
4275 if (flow
!= INT_MIN
) flow
+= share
;
4276 last_share
= it
->first
;
4277 continue; // remove the whole share
4279 removed_shares
+= (uint
)(-flow
);
4281 added_shares
+= (uint
)(flow
);
4283 if (it
->first
<= this->unrestricted
) this->unrestricted
+= flow
;
4285 /* If we don't continue above the whole flow has been added or
4289 new_shares
[it
->first
+ added_shares
- removed_shares
] = it
->second
;
4290 last_share
= it
->first
;
4293 new_shares
[last_share
+ (uint
)flow
] = st
;
4294 if (this->unrestricted
< last_share
) {
4295 this->ReleaseShare(st
);
4297 this->unrestricted
+= flow
;
4300 this->shares
.swap(new_shares
);
4304 * Restrict a flow by moving it to the end of the map and decreasing the amount
4305 * of unrestricted flow.
4306 * @param st Station of flow to be restricted.
4308 void FlowStat::RestrictShare(StationID st
)
4310 assert(!this->shares
.empty());
4312 uint last_share
= 0;
4313 SharesMap new_shares
;
4314 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4316 if (it
->first
> this->unrestricted
) return; // Not present or already restricted.
4317 if (it
->second
== st
) {
4318 flow
= it
->first
- last_share
;
4319 this->unrestricted
-= flow
;
4321 new_shares
[it
->first
] = it
->second
;
4324 new_shares
[it
->first
- flow
] = it
->second
;
4326 last_share
= it
->first
;
4328 if (flow
== 0) return;
4329 new_shares
[last_share
+ flow
] = st
;
4330 this->shares
.swap(new_shares
);
4331 assert(!this->shares
.empty());
4335 * Release ("unrestrict") a flow by moving it to the begin of the map and
4336 * increasing the amount of unrestricted flow.
4337 * @param st Station of flow to be released.
4339 void FlowStat::ReleaseShare(StationID st
)
4341 assert(!this->shares
.empty());
4343 uint next_share
= 0;
4345 for (SharesMap::reverse_iterator
it(this->shares
.rbegin()); it
!= this->shares
.rend(); ++it
) {
4346 if (it
->first
< this->unrestricted
) return; // Note: not <= as the share may hit the limit.
4348 flow
= next_share
- it
->first
;
4349 this->unrestricted
+= flow
;
4352 if (it
->first
== this->unrestricted
) return; // !found -> Limit not hit.
4353 if (it
->second
== st
) found
= true;
4355 next_share
= it
->first
;
4357 if (flow
== 0) return;
4358 SharesMap new_shares
;
4359 new_shares
[flow
] = st
;
4360 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4361 if (it
->second
!= st
) {
4362 new_shares
[flow
+ it
->first
] = it
->second
;
4367 this->shares
.swap(new_shares
);
4368 assert(!this->shares
.empty());
4372 * Scale all shares from link graph's runtime to monthly values.
4373 * @param runtime Time the link graph has been running without compression.
4375 void FlowStat::ScaleToMonthly(uint runtime
)
4377 SharesMap new_shares
;
4379 for (SharesMap::iterator i
= this->shares
.begin(); i
!= this->shares
.end(); ++i
) {
4380 share
= max(share
+ 1, i
->first
* 30 / runtime
);
4381 new_shares
[share
] = i
->second
;
4382 if (this->unrestricted
== i
->first
) this->unrestricted
= share
;
4384 this->shares
.swap(new_shares
);
4388 * Add some flow from "origin", going via "via".
4389 * @param origin Origin of the flow.
4390 * @param via Next hop.
4391 * @param flow Amount of flow to be added.
4393 void FlowStatMap::AddFlow(StationID origin
, StationID via
, uint flow
)
4395 FlowStatMap::iterator origin_it
= this->find(origin
);
4396 if (origin_it
== this->end()) {
4397 this->insert(std::make_pair(origin
, FlowStat(via
, flow
)));
4399 origin_it
->second
.ChangeShare(via
, flow
);
4400 assert(!origin_it
->second
.GetShares()->empty());
4405 * Pass on some flow, remembering it as invalid, for later subtraction from
4406 * locally consumed flow. This is necessary because we can't have negative
4407 * flows and we don't want to sort the flows before adding them up.
4408 * @param origin Origin of the flow.
4409 * @param via Next hop.
4410 * @param flow Amount of flow to be passed.
4412 void FlowStatMap::PassOnFlow(StationID origin
, StationID via
, uint flow
)
4414 FlowStatMap::iterator prev_it
= this->find(origin
);
4415 if (prev_it
== this->end()) {
4416 FlowStat
fs(via
, flow
);
4417 fs
.AppendShare(INVALID_STATION
, flow
);
4418 this->insert(std::make_pair(origin
, fs
));
4420 prev_it
->second
.ChangeShare(via
, flow
);
4421 prev_it
->second
.ChangeShare(INVALID_STATION
, flow
);
4422 assert(!prev_it
->second
.GetShares()->empty());
4427 * Subtract invalid flows from locally consumed flow.
4428 * @param self ID of own station.
4430 void FlowStatMap::FinalizeLocalConsumption(StationID self
)
4432 for (FlowStatMap::iterator i
= this->begin(); i
!= this->end(); ++i
) {
4433 FlowStat
&fs
= i
->second
;
4434 uint local
= fs
.GetShare(INVALID_STATION
);
4435 if (local
> INT_MAX
) { // make sure it fits in an int
4436 fs
.ChangeShare(self
, -INT_MAX
);
4437 fs
.ChangeShare(INVALID_STATION
, -INT_MAX
);
4440 fs
.ChangeShare(self
, -(int)local
);
4441 fs
.ChangeShare(INVALID_STATION
, -(int)local
);
4443 /* If the local share is used up there must be a share for some
4444 * remote station. */
4445 assert(!fs
.GetShares()->empty());
4450 * Delete all flows at a station for specific cargo and destination.
4451 * @param via Remote station of flows to be deleted.
4452 * @return IDs of source stations for which the complete FlowStat, not only a
4453 * share, has been erased.
4455 StationIDStack
FlowStatMap::DeleteFlows(StationID via
)
4458 for (FlowStatMap::iterator f_it
= this->begin(); f_it
!= this->end();) {
4459 FlowStat
&s_flows
= f_it
->second
;
4460 s_flows
.ChangeShare(via
, INT_MIN
);
4461 if (s_flows
.GetShares()->empty()) {
4462 ret
.Push(f_it
->first
);
4463 this->erase(f_it
++);
4472 * Restrict all flows at a station for specific cargo and destination.
4473 * @param via Remote station of flows to be restricted.
4475 void FlowStatMap::RestrictFlows(StationID via
)
4477 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4478 it
->second
.RestrictShare(via
);
4483 * Release all flows at a station for specific cargo and destination.
4484 * @param via Remote station of flows to be released.
4486 void FlowStatMap::ReleaseFlows(StationID via
)
4488 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4489 it
->second
.ReleaseShare(via
);
4494 * Get the sum of flows via a specific station from this GoodsEntry.
4495 * @param via Remote station to look for.
4496 * @return a FlowStat with all flows for 'via' added up.
4498 uint
GoodsEntry::GetSumFlowVia(StationID via
) const
4501 for (FlowStatMap::const_iterator i
= this->flows
.begin(); i
!= this->flows
.end(); ++i
) {
4502 ret
+= i
->second
.GetShare(via
);
4507 extern const TileTypeProcs _tile_type_station_procs
= {
4508 DrawTile_Station
, // draw_tile_proc
4509 GetSlopePixelZ_Station
, // get_slope_z_proc
4510 ClearTile_Station
, // clear_tile_proc
4511 NULL
, // add_accepted_cargo_proc
4512 GetTileDesc_Station
, // get_tile_desc_proc
4513 GetTileRailwayStatus_Station
, // get_tile_railway_status_proc
4514 GetTileRoadStatus_Station
, // get_tile_road_status_proc
4515 GetTileWaterwayStatus_Station
, // get_tile_waterway_status_proc
4516 ClickTile_Station
, // click_tile_proc
4517 AnimateTile_Station
, // animate_tile_proc
4518 TileLoop_Station
, // tile_loop_proc
4519 ChangeTileOwner_Station
, // change_tile_owner_proc
4520 NULL
, // add_produced_cargo_proc
4521 GetFoundation_Station
, // get_foundation_proc
4522 TerraformTile_Station
, // terraform_tile_proc