Update: Translations from eints
[openttd-github.git] / src / station_cmd.cpp
blob4353e8010a1f53d86ce978e68e741b8acd8606cb
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file station_cmd.cpp Handling of station tiles. */
10 #include "stdafx.h"
11 #include "aircraft.h"
12 #include "bridge_map.h"
13 #include "vehiclelist_func.h"
14 #include "viewport_func.h"
15 #include "viewport_kdtree.h"
16 #include "command_func.h"
17 #include "town.h"
18 #include "news_func.h"
19 #include "train.h"
20 #include "ship.h"
21 #include "roadveh.h"
22 #include "industry.h"
23 #include "newgrf_cargo.h"
24 #include "newgrf_debug.h"
25 #include "newgrf_station.h"
26 #include "newgrf_canal.h" /* For the buoy */
27 #include "pathfinder/yapf/yapf_cache.h"
28 #include "road_internal.h" /* For drawing catenary/checking road removal */
29 #include "autoslope.h"
30 #include "water.h"
31 #include "strings_internal.h"
32 #include "clear_func.h"
33 #include "timer/timer_game_calendar.h"
34 #include "vehicle_func.h"
35 #include "string_func.h"
36 #include "animated_tile_func.h"
37 #include "elrail_func.h"
38 #include "station_base.h"
39 #include "station_func.h"
40 #include "station_kdtree.h"
41 #include "roadstop_base.h"
42 #include "newgrf_railtype.h"
43 #include "newgrf_roadtype.h"
44 #include "waypoint_base.h"
45 #include "waypoint_func.h"
46 #include "pbs.h"
47 #include "debug.h"
48 #include "core/random_func.hpp"
49 #include "core/container_func.hpp"
50 #include "company_base.h"
51 #include "table/airporttile_ids.h"
52 #include "newgrf_airporttiles.h"
53 #include "order_backup.h"
54 #include "newgrf_house.h"
55 #include "company_gui.h"
56 #include "linkgraph/linkgraph_base.h"
57 #include "linkgraph/refresh.h"
58 #include "tunnelbridge_map.h"
59 #include "station_cmd.h"
60 #include "waypoint_cmd.h"
61 #include "landscape_cmd.h"
62 #include "rail_cmd.h"
63 #include "newgrf_roadstop.h"
64 #include "timer/timer.h"
65 #include "timer/timer_game_calendar.h"
66 #include "timer/timer_game_economy.h"
67 #include "timer/timer_game_tick.h"
68 #include "cheat_type.h"
69 #include "road_func.h"
71 #include "widgets/station_widget.h"
73 #include "table/strings.h"
75 #include <bitset>
77 #include "safeguards.h"
79 /**
80 * Static instance of FlowStat::SharesMap.
81 * Note: This instance is created on task start.
82 * Lazy creation on first usage results in a data race between the CDist threads.
84 /* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
86 /**
87 * Check whether the given tile is a hangar.
88 * @param t the tile to of whether it is a hangar.
89 * @pre IsTileType(t, MP_STATION)
90 * @return true if and only if the tile is a hangar.
92 bool IsHangar(Tile t)
94 assert(IsTileType(t, MP_STATION));
96 /* If the tile isn't an airport there's no chance it's a hangar. */
97 if (!IsAirport(t)) return false;
99 const Station *st = Station::GetByTile(t);
100 const AirportSpec *as = st->airport.GetSpec();
102 for (const auto &depot : as->depots) {
103 if (st->airport.GetRotatedTileFromOffset(depot.ti) == TileIndex(t)) return true;
106 return false;
110 * Look for a station owned by the given company around the given tile area.
111 * @param ta the area to search over
112 * @param closest_station the closest owned station found so far
113 * @param company the company whose stations to look for
114 * @param st to 'return' the found station
115 * @param filter Filter function
116 * @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
118 template <class T, class F>
119 CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st, F filter)
121 ta.Expand(1);
123 /* check around to see if there are any stations there owned by the company */
124 for (TileIndex tile_cur : ta) {
125 if (IsTileType(tile_cur, MP_STATION)) {
126 StationID t = GetStationIndex(tile_cur);
127 if (!T::IsValidID(t) || T::Get(t)->owner != company || !filter(T::Get(t))) continue;
128 if (closest_station == INVALID_STATION) {
129 closest_station = t;
130 } else if (closest_station != t) {
131 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
135 *st = (closest_station == INVALID_STATION) ? nullptr : T::Get(closest_station);
136 return CommandCost();
140 * Function to check whether the given tile matches some criterion.
141 * @param tile the tile to check
142 * @return true if it matches, false otherwise
144 typedef bool (*CMSAMatcher)(TileIndex tile);
147 * Counts the numbers of tiles matching a specific type in the area around
148 * @param tile the center tile of the 'count area'
149 * @param cmp the comparator/matcher (@see CMSAMatcher)
150 * @return the number of matching tiles around
152 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
154 int num = 0;
156 for (int dx = -3; dx <= 3; dx++) {
157 for (int dy = -3; dy <= 3; dy++) {
158 TileIndex t = TileAddWrap(tile, dx, dy);
159 if (t != INVALID_TILE && cmp(t)) num++;
163 return num;
167 * Check whether the tile is a mine.
168 * @param tile the tile to investigate.
169 * @return true if and only if the tile is a mine
171 static bool CMSAMine(TileIndex tile)
173 /* No industry */
174 if (!IsTileType(tile, MP_INDUSTRY)) return false;
176 const Industry *ind = Industry::GetByTile(tile);
178 /* No extractive industry */
179 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
181 for (const auto &p : ind->produced) {
182 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
183 * Also the production of passengers and mail is ignored. */
184 if (IsValidCargoID(p.cargo) &&
185 (CargoSpec::Get(p.cargo)->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
186 return true;
190 return false;
194 * Check whether the tile is water.
195 * @param tile the tile to investigate.
196 * @return true if and only if the tile is a water tile
198 static bool CMSAWater(TileIndex tile)
200 return IsTileType(tile, MP_WATER) && IsWater(tile);
204 * Check whether the tile is a tree.
205 * @param tile the tile to investigate.
206 * @return true if and only if the tile is a tree tile
208 static bool CMSATree(TileIndex tile)
210 return IsTileType(tile, MP_TREES);
213 #define M(x) ((x) - STR_SV_STNAME)
215 enum StationNaming {
216 STATIONNAMING_RAIL,
217 STATIONNAMING_ROAD,
218 STATIONNAMING_AIRPORT,
219 STATIONNAMING_OILRIG,
220 STATIONNAMING_DOCK,
221 STATIONNAMING_HELIPORT,
224 /** Information to handle station action 0 property 24 correctly */
225 struct StationNameInformation {
226 uint32_t free_names; ///< Current bitset of free names (we can remove names).
227 std::bitset<NUM_INDUSTRYTYPES> indtypes; ///< Bit set indicating when an industry type has been found.
231 * Find a station action 0 property 24 station name, or reduce the
232 * free_names if needed.
233 * @param tile the tile to search
234 * @param user_data the StationNameInformation to base the search on
235 * @return true if the tile contains an industry that has not given
236 * its name to one of the other stations in town.
238 static bool FindNearIndustryName(TileIndex tile, void *user_data)
240 /* All already found industry types */
241 StationNameInformation *sni = (StationNameInformation*)user_data;
242 if (!IsTileType(tile, MP_INDUSTRY)) return false;
244 /* If the station name is undefined it means that it doesn't name a station */
245 IndustryType indtype = GetIndustryType(tile);
246 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
248 /* In all cases if an industry that provides a name is found two of
249 * the standard names will be disabled. */
250 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
251 return !sni->indtypes[indtype];
254 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
256 static const uint32_t _gen_station_name_bits[] = {
257 0, // STATIONNAMING_RAIL
258 0, // STATIONNAMING_ROAD
259 1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
260 1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
261 1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
262 1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
265 const Town *t = st->town;
267 StationNameInformation sni{};
268 sni.free_names = UINT32_MAX;
270 for (const Station *s : Station::Iterate()) {
271 if (s != st && s->town == t) {
272 if (s->indtype != IT_INVALID) {
273 sni.indtypes[s->indtype] = true;
274 StringID name = GetIndustrySpec(s->indtype)->station_name;
275 if (name != STR_UNDEFINED) {
276 /* Filter for other industrytypes with the same name */
277 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
278 const IndustrySpec *indsp = GetIndustrySpec(it);
279 if (indsp->enabled && indsp->station_name == name) sni.indtypes[it] = true;
282 continue;
284 uint str = M(s->string_id);
285 if (str <= 0x20) {
286 if (str == M(STR_SV_STNAME_FOREST)) {
287 str = M(STR_SV_STNAME_WOODS);
289 ClrBit(sni.free_names, str);
294 TileIndex indtile = tile;
295 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
296 /* An industry has been found nearby */
297 IndustryType indtype = GetIndustryType(indtile);
298 const IndustrySpec *indsp = GetIndustrySpec(indtype);
299 /* STR_NULL means it only disables oil rig/mines */
300 if (indsp->station_name != STR_NULL) {
301 st->indtype = indtype;
302 return STR_SV_STNAME_FALLBACK;
306 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
308 /* check default names */
309 uint32_t tmp = sni.free_names & _gen_station_name_bits[name_class];
310 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
312 /* check mine? */
313 if (HasBit(sni.free_names, M(STR_SV_STNAME_MINES))) {
314 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
315 return STR_SV_STNAME_MINES;
319 /* check close enough to town to get central as name? */
320 if (DistanceMax(tile, t->xy) < 8) {
321 if (HasBit(sni.free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
323 if (HasBit(sni.free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
326 /* Check lakeside */
327 if (HasBit(sni.free_names, M(STR_SV_STNAME_LAKESIDE)) &&
328 DistanceFromEdge(tile) < 20 &&
329 CountMapSquareAround(tile, CMSAWater) >= 5) {
330 return STR_SV_STNAME_LAKESIDE;
333 /* Check woods */
334 if (HasBit(sni.free_names, M(STR_SV_STNAME_WOODS)) && (
335 CountMapSquareAround(tile, CMSATree) >= 8 ||
336 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
338 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
341 /* check elevation compared to town */
342 int z = GetTileZ(tile);
343 int z2 = GetTileZ(t->xy);
344 if (z < z2) {
345 if (HasBit(sni.free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
346 } else if (z > z2) {
347 if (HasBit(sni.free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
350 /* check direction compared to town */
351 static const int8_t _direction_and_table[] = {
352 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
353 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
354 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
355 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
358 sni.free_names &= _direction_and_table[
359 (TileX(tile) < TileX(t->xy)) +
360 (TileY(tile) < TileY(t->xy)) * 2];
362 /** Bitmask of remaining station names that can be used when a more specific name has not been used. */
363 static const uint32_t fallback_names = (
364 (1U << M(STR_SV_STNAME_NORTH)) |
365 (1U << M(STR_SV_STNAME_SOUTH)) |
366 (1U << M(STR_SV_STNAME_EAST)) |
367 (1U << M(STR_SV_STNAME_WEST)) |
368 (1U << M(STR_SV_STNAME_TRANSFER)) |
369 (1U << M(STR_SV_STNAME_HALT)) |
370 (1U << M(STR_SV_STNAME_EXCHANGE)) |
371 (1U << M(STR_SV_STNAME_ANNEXE)) |
372 (1U << M(STR_SV_STNAME_SIDINGS)) |
373 (1U << M(STR_SV_STNAME_BRANCH)) |
374 (1U << M(STR_SV_STNAME_UPPER)) |
375 (1U << M(STR_SV_STNAME_LOWER))
378 sni.free_names &= fallback_names;
379 return (sni.free_names == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(sni.free_names));
381 #undef M
384 * Find the closest deleted station of the current company
385 * @param tile the tile to search from.
386 * @return the closest station or nullptr if too far.
388 static Station *GetClosestDeletedStation(TileIndex tile)
390 uint threshold = 8;
392 Station *best_station = nullptr;
393 ForAllStationsRadius(tile, threshold, [&](Station *st) {
394 if (!st->IsInUse() && st->owner == _current_company) {
395 uint cur_dist = DistanceManhattan(tile, st->xy);
397 if (cur_dist < threshold) {
398 threshold = cur_dist;
399 best_station = st;
400 } else if (cur_dist == threshold && best_station != nullptr) {
401 /* In case of a tie, lowest station ID wins */
402 if (st->index < best_station->index) best_station = st;
407 return best_station;
411 void Station::GetTileArea(TileArea *ta, StationType type) const
413 switch (type) {
414 case STATION_RAIL:
415 *ta = this->train_station;
416 return;
418 case STATION_AIRPORT:
419 *ta = this->airport;
420 return;
422 case STATION_TRUCK:
423 *ta = this->truck_station;
424 return;
426 case STATION_BUS:
427 *ta = this->bus_station;
428 return;
430 case STATION_DOCK:
431 case STATION_OILRIG:
432 *ta = this->docking_station;
433 return;
435 default: NOT_REACHED();
440 * Update the virtual coords needed to draw the station sign.
442 void Station::UpdateVirtCoord()
444 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
446 pt.y -= 32 * ZOOM_BASE;
447 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_BASE;
449 if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
451 SetDParam(0, this->index);
452 SetDParam(1, this->facilities);
453 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION, STR_VIEWPORT_STATION_TINY);
455 _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
457 SetWindowDirty(WC_STATION_VIEW, this->index);
461 * Move the station main coordinate somewhere else.
462 * @param new_xy new tile location of the sign
464 void Station::MoveSign(TileIndex new_xy)
466 if (this->xy == new_xy) return;
468 _station_kdtree.Remove(this->index);
470 this->BaseStation::MoveSign(new_xy);
472 _station_kdtree.Insert(this->index);
475 /** Update the virtual coords needed to draw the station sign for all stations. */
476 void UpdateAllStationVirtCoords()
478 for (BaseStation *st : BaseStation::Iterate()) {
479 st->UpdateVirtCoord();
483 void BaseStation::FillCachedName() const
485 auto tmp_params = MakeParameters(this->index);
486 this->cached_name = GetStringWithArgs(Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, tmp_params);
489 void ClearAllStationCachedNames()
491 for (BaseStation *st : BaseStation::Iterate()) {
492 st->cached_name.clear();
497 * Get a mask of the cargo types that the station accepts.
498 * @param st Station to query
499 * @return the expected mask
501 CargoTypes GetAcceptanceMask(const Station *st)
503 CargoTypes mask = 0;
505 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
506 if (HasBit(it->status, GoodsEntry::GES_ACCEPTANCE)) SetBit(mask, std::distance(std::begin(st->goods), it));
508 return mask;
512 * Get a mask of the cargo types that are empty at the station.
513 * @param st Station to query
514 * @return the empty mask
516 CargoTypes GetEmptyMask(const Station *st)
518 CargoTypes mask = 0;
520 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
521 if (it->cargo.TotalCount() == 0) SetBit(mask, std::distance(std::begin(st->goods), it));
523 return mask;
527 * Add news item for when a station changes which cargoes it accepts.
528 * @param st Station of cargo change.
529 * @param cargoes Bit mask of cargo types to list.
530 * @param reject True iff the station rejects the cargo types.
532 static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
534 SetDParam(0, st->index);
535 SetDParam(1, cargoes);
536 StringID msg = reject ? STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_LIST : STR_NEWS_STATION_NOW_ACCEPTS_CARGO_LIST;
537 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
541 * Get the cargo types being produced around the tile (in a rectangle).
542 * @param north_tile Northern most tile of area
543 * @param w X extent of the area
544 * @param h Y extent of the area
545 * @param rad Search radius in addition to the given area
547 CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
549 CargoArray produced{};
550 std::set<IndustryID> industries;
551 TileArea ta = TileArea(north_tile, w, h).Expand(rad);
553 /* Loop over all tiles to get the produced cargo of
554 * everything except industries */
555 for (TileIndex tile : ta) {
556 if (IsTileType(tile, MP_INDUSTRY)) industries.insert(GetIndustryIndex(tile));
557 AddProducedCargo(tile, produced);
560 /* Loop over the seen industries. They produce cargo for
561 * anything that is within 'rad' of any one of their tiles.
563 for (IndustryID industry : industries) {
564 const Industry *i = Industry::Get(industry);
565 /* Skip industry with neutral station */
566 if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
568 for (const auto &p : i->produced) {
569 if (IsValidCargoID(p.cargo)) produced[p.cargo]++;
573 return produced;
577 * Get the acceptance of cargoes around the tile in 1/8.
578 * @param center_tile Center of the search area
579 * @param w X extent of area
580 * @param h Y extent of area
581 * @param rad Search radius in addition to given area
582 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
583 * @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
585 CargoArray GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad, CargoTypes *always_accepted)
587 CargoArray acceptance{};
588 if (always_accepted != nullptr) *always_accepted = 0;
590 TileArea ta = TileArea(center_tile, w, h).Expand(rad);
592 for (TileIndex tile : ta) {
593 /* Ignore industry if it has a neutral station. */
594 if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
596 AddAcceptedCargo(tile, acceptance, always_accepted);
599 return acceptance;
603 * Get the acceptance of cargoes around the station in.
604 * @param st Station to get acceptance of.
605 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
607 static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
609 CargoArray acceptance{};
610 if (always_accepted != nullptr) *always_accepted = 0;
612 BitmapTileIterator it(st->catchment_tiles);
613 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
614 AddAcceptedCargo(tile, acceptance, always_accepted);
617 return acceptance;
621 * Update the acceptance for a station.
622 * @param st Station to update
623 * @param show_msg controls whether to display a message that acceptance was changed.
625 void UpdateStationAcceptance(Station *st, bool show_msg)
627 /* old accepted goods types */
628 CargoTypes old_acc = GetAcceptanceMask(st);
630 /* And retrieve the acceptance. */
631 CargoArray acceptance{};
632 if (!st->rect.IsEmpty()) {
633 acceptance = GetAcceptanceAroundStation(st, &st->always_accepted);
636 /* Adjust in case our station only accepts fewer kinds of goods */
637 for (CargoID i = 0; i < NUM_CARGO; i++) {
638 uint amt = acceptance[i];
640 /* Make sure the station can accept the goods type. */
641 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
642 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
643 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
644 amt = 0;
647 GoodsEntry &ge = st->goods[i];
648 SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
649 if (LinkGraph::IsValidID(ge.link_graph)) {
650 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
654 /* Only show a message in case the acceptance was actually changed. */
655 CargoTypes new_acc = GetAcceptanceMask(st);
656 if (old_acc == new_acc) return;
658 /* show a message to report that the acceptance was changed? */
659 if (show_msg && st->owner == _local_company && st->IsInUse()) {
660 /* Combine old and new masks to get changes */
661 CargoTypes accepts = new_acc & ~old_acc;
662 CargoTypes rejects = ~new_acc & old_acc;
664 /* Show news message if there are any changes */
665 if (accepts != 0) ShowRejectOrAcceptNews(st, accepts, false);
666 if (rejects != 0) ShowRejectOrAcceptNews(st, rejects, true);
669 /* redraw the station view since acceptance changed */
670 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
673 static void UpdateStationSignCoord(BaseStation *st)
675 const StationRect *r = &st->rect;
677 if (r->IsEmpty()) return; // no tiles belong to this station
679 /* clamp sign coord to be inside the station rect */
680 TileIndex new_xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
681 st->MoveSign(new_xy);
683 if (!Station::IsExpected(st)) return;
684 Station *full_station = Station::From(st);
685 for (const GoodsEntry &ge : full_station->goods) {
686 LinkGraphID lg = ge.link_graph;
687 if (!LinkGraph::IsValidID(lg)) continue;
688 (*LinkGraph::Get(lg))[ge.node].UpdateLocation(st->xy);
693 * Common part of building various station parts and possibly attaching them to an existing one.
694 * @param[in,out] st Station to attach to
695 * @param flags Command flags
696 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
697 * @param area Area occupied by the new part
698 * @param name_class Station naming class to use to generate the new station's name
699 * @return Command error that occurred, if any
701 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
703 /* Find a deleted station close to us */
704 if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
706 if (*st != nullptr) {
707 if ((*st)->owner != _current_company) {
708 return_cmd_error(CMD_ERROR);
711 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
712 if (ret.Failed()) return ret;
713 } else {
714 /* allocate and initialize new station */
715 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
717 if (flags & DC_EXEC) {
718 *st = new Station(area.tile);
719 _station_kdtree.Insert((*st)->index);
721 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
722 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
724 if (Company::IsValidID(_current_company)) {
725 SetBit((*st)->town->have_ratings, _current_company);
729 return CommandCost();
733 * This is called right after a station was deleted.
734 * It checks if the whole station is free of substations, and if so, the station will be
735 * deleted after a little while.
736 * @param st Station
738 static void DeleteStationIfEmpty(BaseStation *st)
740 if (!st->IsInUse()) {
741 st->delete_ctr = 0;
742 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
744 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
745 UpdateStationSignCoord(st);
749 * After adding/removing tiles to station, update some station-related stuff.
750 * @param adding True if adding tiles, false if removing them.
751 * @param type StationType being modified.
753 void Station::AfterStationTileSetChange(bool adding, StationType type)
755 this->UpdateVirtCoord();
756 DirtyCompanyInfrastructureWindows(this->owner);
758 if (adding) {
759 this->RecomputeCatchment();
760 MarkCatchmentTilesDirty();
761 InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
762 } else {
763 MarkCatchmentTilesDirty();
766 switch (type) {
767 case STATION_RAIL:
768 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_TRAINS);
769 break;
770 case STATION_AIRPORT:
771 break;
772 case STATION_TRUCK:
773 case STATION_BUS:
774 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_ROADVEHS);
775 break;
776 case STATION_DOCK:
777 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_SHIPS);
778 break;
779 default: NOT_REACHED();
782 if (adding) {
783 UpdateStationAcceptance(this, false);
784 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
785 } else {
786 DeleteStationIfEmpty(this);
787 this->RecomputeCatchment();
792 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
795 * Checks if the given tile is buildable, flat and has a certain height.
796 * @param tile TileIndex to check.
797 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
798 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
799 * @param allow_steep Whether steep slopes are allowed.
800 * @param check_bridge Check for the existence of a bridge.
801 * @return The cost in case of success, or an error code if it failed.
803 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
805 if (check_bridge && IsBridgeAbove(tile)) {
806 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
809 CommandCost ret = EnsureNoVehicleOnGround(tile);
810 if (ret.Failed()) return ret;
812 auto [tileh, z] = GetTileSlopeZ(tile);
814 /* Prohibit building if
815 * 1) The tile is "steep" (i.e. stretches two height levels).
816 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
818 if ((!allow_steep && IsSteepSlope(tileh)) ||
819 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
820 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
823 CommandCost cost(EXPENSES_CONSTRUCTION);
824 int flat_z = z + GetSlopeMaxZ(tileh);
825 if (tileh != SLOPE_FLAT) {
826 /* Forbid building if the tile faces a slope in a invalid direction. */
827 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
828 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
829 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
832 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
835 /* The level of this tile must be equal to allowed_z. */
836 if (allowed_z < 0) {
837 /* First tile. */
838 allowed_z = flat_z;
839 } else if (allowed_z != flat_z) {
840 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
843 return cost;
847 * Checks if an airport can be built at the given location and clear the area.
848 * @param tile_iter Airport tile iterator.
849 * @param flags Operation to perform.
850 * @return The cost in case of success, or an error code if it failed.
852 static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlag flags)
854 CommandCost cost(EXPENSES_CONSTRUCTION);
855 int allowed_z = -1;
857 for (; tile_iter != INVALID_TILE; ++tile_iter) {
858 CommandCost ret = CheckBuildableTile(tile_iter, 0, allowed_z, true);
859 if (ret.Failed()) return ret;
860 cost.AddCost(ret);
862 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_iter);
863 if (ret.Failed()) return ret;
864 cost.AddCost(ret);
867 return cost;
871 * Checks if a rail station can be built at the given tile.
872 * @param tile_cur Tile to check.
873 * @param north_tile North tile of the area being checked.
874 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
875 * @param flags Operation to perform.
876 * @param axis Rail station axis.
877 * @param station StationID to be queried and returned if available.
878 * @param rt The rail type to check for (overbuilding rail stations over rail).
879 * @param affected_vehicles List of trains with PBS reservations on the tiles
880 * @param spec_class Station class.
881 * @param spec_index Index into the station class.
882 * @param plat_len Platform length.
883 * @param numtracks Number of platforms.
884 * @return The cost in case of success, or an error code if it failed.
886 static CommandCost CheckFlatLandRailStation(TileIndex tile_cur, TileIndex north_tile, int &allowed_z, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
888 CommandCost cost(EXPENSES_CONSTRUCTION);
889 uint invalid_dirs = 5 << axis;
891 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
892 bool slope_cb = statspec != nullptr && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
894 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
895 if (ret.Failed()) return ret;
896 cost.AddCost(ret);
898 if (slope_cb) {
899 /* Do slope check if requested. */
900 ret = PerformStationTileSlopeCheck(north_tile, tile_cur, statspec, axis, plat_len, numtracks);
901 if (ret.Failed()) return ret;
904 /* if station is set, then we have special handling to allow building on top of already existing stations.
905 * so station points to INVALID_STATION if we can build on any station.
906 * Or it points to a station if we're only allowed to build on exactly that station. */
907 if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
908 if (!IsRailStation(tile_cur)) {
909 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
910 } else {
911 StationID st = GetStationIndex(tile_cur);
912 if (*station == INVALID_STATION) {
913 *station = st;
914 } else if (*station != st) {
915 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
918 } else {
919 /* Rail type is only valid when building a railway station; if station to
920 * build isn't a rail station it's INVALID_RAILTYPE. */
921 if (rt != INVALID_RAILTYPE &&
922 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
923 HasPowerOnRail(GetRailType(tile_cur), rt)) {
924 /* Allow overbuilding if the tile:
925 * - has rail, but no signals
926 * - it has exactly one track
927 * - the track is in line with the station
928 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
930 TrackBits tracks = GetTrackBits(tile_cur);
931 Track track = RemoveFirstTrack(&tracks);
932 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
934 if (tracks == TRACK_BIT_NONE && track == expected_track) {
935 /* Check for trains having a reservation for this tile. */
936 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
937 Train *v = GetTrainForReservation(tile_cur, track);
938 if (v != nullptr) {
939 affected_vehicles.push_back(v);
942 ret = Command<CMD_REMOVE_SINGLE_RAIL>::Do(flags, tile_cur, track);
943 if (ret.Failed()) return ret;
944 cost.AddCost(ret);
945 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
946 return cost;
949 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
950 if (ret.Failed()) return ret;
951 cost.AddCost(ret);
954 return cost;
958 * Checks if a road stop can be built at the given tile.
959 * @param cur_tile Tile to check.
960 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
961 * @param flags Operation to perform.
962 * @param invalid_dirs Prohibited directions (set of DiagDirections).
963 * @param is_drive_through True if trying to build a drive-through station.
964 * @param station_type Station type (bus, truck or road waypoint).
965 * @param axis Axis of a drive-through road stop.
966 * @param station StationID to be queried and returned if available.
967 * @param rt Road type to build, may be INVALID_ROADTYPE if an existing road is required.
968 * @return The cost in case of success, or an error code if it failed.
970 CommandCost CheckFlatLandRoadStop(TileIndex cur_tile, int &allowed_z, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, StationType station_type, Axis axis, StationID *station, RoadType rt)
972 CommandCost cost(EXPENSES_CONSTRUCTION);
974 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
975 if (ret.Failed()) return ret;
976 cost.AddCost(ret);
978 /* If station is set, then we have special handling to allow building on top of already existing stations.
979 * Station points to INVALID_STATION if we can build on any station.
980 * Or it points to a station if we're only allowed to build on exactly that station. */
981 if (station != nullptr && IsTileType(cur_tile, MP_STATION)) {
982 if (!IsAnyRoadStop(cur_tile)) {
983 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
984 } else {
985 if (station_type != GetStationType(cur_tile) ||
986 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
987 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
989 /* Drive-through station in the wrong direction. */
990 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && GetDriveThroughStopAxis(cur_tile) != axis) {
991 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
993 StationID st = GetStationIndex(cur_tile);
994 if (*station == INVALID_STATION) {
995 *station = st;
996 } else if (*station != st) {
997 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1000 } else {
1001 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
1002 /* Road bits in the wrong direction. */
1003 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
1004 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
1005 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1006 switch (CountBits(rb)) {
1007 case 1:
1008 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1010 case 2:
1011 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1012 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
1014 default: // 3 or 4
1015 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1019 if (build_over_road) {
1020 /* There is a road, check if we can build road+tram stop over it. */
1021 RoadType road_rt = GetRoadType(cur_tile, RTT_ROAD);
1022 if (road_rt != INVALID_ROADTYPE) {
1023 Owner road_owner = GetRoadOwner(cur_tile, RTT_ROAD);
1024 if (road_owner == OWNER_TOWN) {
1025 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1026 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1027 ret = CheckOwnership(road_owner);
1028 if (ret.Failed()) return ret;
1030 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_ROAD));
1032 if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1034 if (GetDisallowedRoadDirections(cur_tile) != DRD_NONE && road_owner != OWNER_TOWN) {
1035 ret = CheckOwnership(road_owner);
1036 if (ret.Failed()) return ret;
1039 cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1040 } else if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt)) {
1041 cost.AddCost(RoadBuildCost(rt) * 2);
1044 /* There is a tram, check if we can build road+tram stop over it. */
1045 RoadType tram_rt = GetRoadType(cur_tile, RTT_TRAM);
1046 if (tram_rt != INVALID_ROADTYPE) {
1047 Owner tram_owner = GetRoadOwner(cur_tile, RTT_TRAM);
1048 if (Company::IsValidID(tram_owner) &&
1049 (!_settings_game.construction.road_stop_on_competitor_road ||
1050 /* Disallow breaking end-of-line of someone else
1051 * so trams can still reverse on this tile. */
1052 HasExactlyOneBit(GetRoadBits(cur_tile, RTT_TRAM)))) {
1053 ret = CheckOwnership(tram_owner);
1054 if (ret.Failed()) return ret;
1056 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_TRAM));
1058 if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1060 cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1061 } else if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt)) {
1062 cost.AddCost(RoadBuildCost(rt) * 2);
1064 } else if (rt == INVALID_ROADTYPE) {
1065 return_cmd_error(STR_ERROR_THERE_IS_NO_ROAD);
1066 } else {
1067 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, cur_tile);
1068 if (ret.Failed()) return ret;
1069 cost.AddCost(ret);
1070 cost.AddCost(RoadBuildCost(rt) * 2);
1074 return cost;
1078 * Check whether we can expand the rail part of the given station.
1079 * @param st the station to expand
1080 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1081 * @return Succeeded or failed command.
1083 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta)
1085 TileArea cur_ta = st->train_station;
1087 /* determine new size of train station region.. */
1088 int x = std::min(TileX(cur_ta.tile), TileX(new_ta.tile));
1089 int y = std::min(TileY(cur_ta.tile), TileY(new_ta.tile));
1090 new_ta.w = std::max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1091 new_ta.h = std::max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1092 new_ta.tile = TileXY(x, y);
1094 /* make sure the final size is not too big. */
1095 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
1096 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1099 return CommandCost();
1102 static inline uint8_t *CreateSingle(uint8_t *layout, int n)
1104 int i = n;
1105 do *layout++ = 0; while (--i);
1106 layout[((n - 1) >> 1) - n] = 2;
1107 return layout;
1110 static inline uint8_t *CreateMulti(uint8_t *layout, int n, uint8_t b)
1112 int i = n;
1113 do *layout++ = b; while (--i);
1114 if (n > 4) {
1115 layout[0 - n] = 0;
1116 layout[n - 1 - n] = 0;
1118 return layout;
1122 * Create the station layout for the given number of tracks and platform length.
1123 * @param layout The layout to write to.
1124 * @param numtracks The number of tracks to write.
1125 * @param plat_len The length of the platforms.
1126 * @param statspec The specification of the station to (possibly) get the layout from.
1128 void GetStationLayout(uint8_t *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
1130 if (statspec != nullptr) {
1131 auto found = statspec->layouts.find(GetStationLayoutKey(numtracks, plat_len));
1132 if (found != std::end(statspec->layouts)) {
1133 /* Custom layout defined, copy to buffer. */
1134 std::copy(std::begin(found->second), std::end(found->second), layout);
1135 return;
1139 if (plat_len == 1) {
1140 CreateSingle(layout, numtracks);
1141 } else {
1142 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1143 int n = numtracks >> 1;
1145 while (--n >= 0) {
1146 layout = CreateMulti(layout, plat_len, 4);
1147 layout = CreateMulti(layout, plat_len, 6);
1153 * Find a nearby station that joins this station.
1154 * @tparam T the class to find a station for
1155 * @tparam error_message the error message when building a station on top of others
1156 * @tparam F the filter functor type
1157 * @param existing_station an existing station we build over
1158 * @param station_to_join the station to join to
1159 * @param adjacent whether adjacent stations are allowed
1160 * @param ta the area of the newly build station
1161 * @param st 'return' pointer for the found station
1162 * @return command cost with the error or 'okay'
1164 template <class T, StringID error_message, class F>
1165 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
1167 assert(*st == nullptr);
1168 bool check_surrounding = true;
1170 if (_settings_game.station.adjacent_stations) {
1171 if (existing_station != INVALID_STATION) {
1172 if (adjacent && existing_station != station_to_join) {
1173 /* You can't build an adjacent station over the top of one that
1174 * already exists. */
1175 return_cmd_error(error_message);
1176 } else {
1177 /* Extend the current station, and don't check whether it will
1178 * be near any other stations. */
1179 T *candidate = T::GetIfValid(existing_station);
1180 if (candidate != nullptr && filter(candidate)) *st = candidate;
1181 check_surrounding = (*st == nullptr);
1183 } else {
1184 /* There's no station here. Don't check the tiles surrounding this
1185 * one if the company wanted to build an adjacent station. */
1186 if (adjacent) check_surrounding = false;
1190 if (check_surrounding) {
1191 /* Make sure there is no more than one other station around us that is owned by us. */
1192 CommandCost ret = GetStationAround(ta, existing_station, _current_company, st, filter);
1193 if (ret.Failed()) return ret;
1196 /* Distant join */
1197 if (*st == nullptr && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1199 return CommandCost();
1203 * Find a nearby station that joins this station.
1204 * @param existing_station an existing station we build over
1205 * @param station_to_join the station to join to
1206 * @param adjacent whether adjacent stations are allowed
1207 * @param ta the area of the newly build station
1208 * @param st 'return' pointer for the found station
1209 * @return command cost with the error or 'okay'
1211 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1213 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1217 * Find a nearby waypoint that joins this waypoint.
1218 * @param existing_waypoint an existing waypoint we build over
1219 * @param waypoint_to_join the waypoint to join to
1220 * @param adjacent whether adjacent waypoints are allowed
1221 * @param ta the area of the newly build waypoint
1222 * @param wp 'return' pointer for the found waypoint
1223 * @param is_road whether to find a road waypoint
1224 * @return command cost with the error or 'okay'
1226 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
1228 if (is_road) {
1229 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_ROADWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp, [](const Waypoint *wp) -> bool { return HasBit(wp->waypoint_flags, WPF_ROAD); });
1230 } else {
1231 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp, [](const Waypoint *wp) -> bool { return !HasBit(wp->waypoint_flags, WPF_ROAD); });
1236 * Clear platform reservation during station building/removing.
1237 * @param v vehicle which holds reservation
1239 static void FreeTrainReservation(Train *v)
1241 FreeTrainTrackReservation(v);
1242 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1243 v = v->Last();
1244 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
1248 * Restore platform reservation during station building/removing.
1249 * @param v vehicle which held reservation
1251 static void RestoreTrainReservation(Train *v)
1253 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1254 TryPathReserve(v, true, true);
1255 v = v->Last();
1256 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1260 * Calculates cost of new rail stations within the area.
1261 * @param tile_area Area to check.
1262 * @param flags Operation to perform.
1263 * @param axis Rail station axis.
1264 * @param station StationID to be queried and returned if available.
1265 * @param rt The rail type to check for (overbuilding rail stations over rail).
1266 * @param affected_vehicles List of trains with PBS reservations on the tiles
1267 * @param spec_class Station class.
1268 * @param spec_index Index into the station class.
1269 * @param plat_len Platform length.
1270 * @param numtracks Number of platforms.
1271 * @return The cost in case of success, or an error code if it failed.
1273 static CommandCost CalculateRailStationCost(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
1275 CommandCost cost(EXPENSES_CONSTRUCTION);
1276 bool length_price_ready = true;
1277 uint8_t tracknum = 0;
1278 int allowed_z = -1;
1279 for (TileIndex cur_tile : tile_area) {
1280 /* Clear the land below the station. */
1281 CommandCost ret = CheckFlatLandRailStation(cur_tile, tile_area.tile, allowed_z, flags, axis, station, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1282 if (ret.Failed()) return ret;
1284 /* Only add _price[PR_BUILD_STATION_RAIL_LENGTH] once for each valid plat_len. */
1285 if (tracknum == numtracks) {
1286 length_price_ready = true;
1287 tracknum = 0;
1288 } else {
1289 tracknum++;
1292 /* AddCost for new or rotated rail stations. */
1293 if (!IsRailStationTile(cur_tile) || (IsRailStationTile(cur_tile) && GetRailStationAxis(cur_tile) != axis)) {
1294 cost.AddCost(ret);
1295 cost.AddCost(_price[PR_BUILD_STATION_RAIL]);
1296 cost.AddCost(RailBuildCost(rt));
1298 if (length_price_ready) {
1299 cost.AddCost(_price[PR_BUILD_STATION_RAIL_LENGTH]);
1300 length_price_ready = false;
1305 return cost;
1309 * Get station tile flags for the given StationGfx.
1310 * @param gfx StationGfx of station tile.
1311 * @param statspec Station spec of station tile.
1312 * @return Tile flags to apply.
1314 static StationSpec::TileFlags GetStationTileFlags(StationGfx gfx, const StationSpec *statspec)
1316 /* Default stations do not draw pylons under roofs (gfx >= 4) */
1317 if (statspec == nullptr || gfx >= statspec->tileflags.size()) return gfx < 4 ? StationSpec::TileFlags::Pylons : StationSpec::TileFlags::None;
1318 return statspec->tileflags[gfx];
1322 * Set rail station tile flags for the given tile.
1323 * @param tile Tile to set flags on.
1324 * @param statspec Statspec of the tile.
1326 void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
1328 const auto flags = GetStationTileFlags(GetStationGfx(tile), statspec);
1329 SetStationTileBlocked(tile, HasFlag(flags, StationSpec::TileFlags::Blocked));
1330 SetStationTileHavePylons(tile, HasFlag(flags, StationSpec::TileFlags::Pylons));
1331 SetStationTileHaveWires(tile, !HasFlag(flags, StationSpec::TileFlags::NoWires));
1335 * Build rail station
1336 * @param flags operation to perform
1337 * @param tile_org northern most position of station dragging/placement
1338 * @param rt railtype
1339 * @param axis orientation (Axis)
1340 * @param numtracks number of tracks
1341 * @param plat_len platform length
1342 * @param spec_class custom station class
1343 * @param spec_index custom station id
1344 * @param station_to_join station ID to join (NEW_STATION if build new one)
1345 * @param adjacent allow stations directly adjacent to other stations.
1346 * @return the cost of this operation or an error
1348 CommandCost CmdBuildRailStation(DoCommandFlag flags, TileIndex tile_org, RailType rt, Axis axis, uint8_t numtracks, uint8_t plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1350 /* Does the authority allow this? */
1351 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1352 if (ret.Failed()) return ret;
1354 if (!ValParamRailType(rt) || !IsValidAxis(axis)) return CMD_ERROR;
1356 /* Check if the given station class is valid */
1357 if (static_cast<uint>(spec_class) >= StationClass::GetClassCount()) return CMD_ERROR;
1358 const StationClass *cls = StationClass::Get(spec_class);
1359 if (IsWaypointClass(*cls)) return CMD_ERROR;
1360 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1361 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1363 int w_org, h_org;
1364 if (axis == AXIS_X) {
1365 w_org = plat_len;
1366 h_org = numtracks;
1367 } else {
1368 h_org = plat_len;
1369 w_org = numtracks;
1372 bool reuse = (station_to_join != NEW_STATION);
1373 if (!reuse) station_to_join = INVALID_STATION;
1374 bool distant_join = (station_to_join != INVALID_STATION);
1376 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1378 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1380 /* these values are those that will be stored in train_tile and station_platforms */
1381 TileArea new_location(tile_org, w_org, h_org);
1383 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1384 StationID est = INVALID_STATION;
1385 std::vector<Train *> affected_vehicles;
1386 /* Add construction and clearing expenses. */
1387 CommandCost cost = CalculateRailStationCost(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1388 if (cost.Failed()) return cost;
1390 Station *st = nullptr;
1391 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1392 if (ret.Failed()) return ret;
1394 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1395 if (ret.Failed()) return ret;
1397 if (st != nullptr && st->train_station.tile != INVALID_TILE) {
1398 ret = CanExpandRailStation(st, new_location);
1399 if (ret.Failed()) return ret;
1402 /* Check if we can allocate a custom stationspec to this station */
1403 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1404 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1405 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1407 if (statspec != nullptr) {
1408 /* Perform NewStation checks */
1410 /* Check if the station size is permitted */
1411 if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7))) return_cmd_error(STR_ERROR_STATION_DISALLOWED_NUMBER_TRACKS);
1412 if (HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) return_cmd_error(STR_ERROR_STATION_DISALLOWED_LENGTH);
1414 /* Check if the station is buildable */
1415 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1416 uint16_t cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1417 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1421 if (flags & DC_EXEC) {
1422 st->train_station = new_location;
1423 st->AddFacility(FACIL_TRAIN, new_location.tile);
1425 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1427 if (statspec != nullptr) {
1428 /* Include this station spec's animation trigger bitmask
1429 * in the station's cached copy. */
1430 st->cached_anim_triggers |= statspec->animation.triggers;
1433 TileIndexDiff tile_delta = TileOffsByAxis(axis); // offset to go to the next platform tile
1434 TileIndexDiff track_delta = TileOffsByAxis(OtherAxis(axis)); // offset to go to the next track
1435 Track track = AxisToTrack(axis);
1437 std::vector<uint8_t> layouts(numtracks * plat_len);
1438 GetStationLayout(layouts.data(), numtracks, plat_len, statspec);
1440 uint8_t numtracks_orig = numtracks;
1442 Company *c = Company::Get(st->owner);
1443 size_t layout_idx = 0;
1444 TileIndex tile_track = tile_org;
1445 do {
1446 TileIndex tile = tile_track;
1447 int w = plat_len;
1448 do {
1449 uint8_t layout = layouts[layout_idx++];
1450 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1451 /* Check for trains having a reservation for this tile. */
1452 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1453 if (v != nullptr) {
1454 affected_vehicles.push_back(v);
1455 FreeTrainReservation(v);
1459 /* Railtype can change when overbuilding. */
1460 if (IsRailStationTile(tile)) {
1461 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1462 c->infrastructure.station--;
1465 /* Remove animation if overbuilding */
1466 DeleteAnimatedTile(tile);
1467 uint8_t old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1468 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1469 /* Free the spec if we overbuild something */
1470 DeallocateSpecFromStation(st, old_specindex);
1472 SetCustomStationSpecIndex(tile, specindex);
1473 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1474 SetAnimationFrame(tile, 0);
1476 if (statspec != nullptr) {
1477 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1478 uint32_t platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1480 /* As the station is not yet completely finished, the station does not yet exist. */
1481 uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1482 if (callback != CALLBACK_FAILED) {
1483 if (callback <= UINT8_MAX) {
1484 SetStationGfx(tile, (callback & ~1) + axis);
1485 } else {
1486 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_BUILD_TILE_LAYOUT, callback);
1490 /* Trigger station animation -- after building? */
1491 TriggerStationAnimation(st, tile, SAT_BUILT);
1494 SetRailStationTileFlags(tile, statspec);
1496 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1497 c->infrastructure.station++;
1499 tile += tile_delta;
1500 } while (--w);
1501 AddTrackToSignalBuffer(tile_track, track, _current_company);
1502 YapfNotifyTrackLayoutChange(tile_track, track);
1503 tile_track += track_delta;
1504 } while (--numtracks);
1506 for (uint i = 0; i < affected_vehicles.size(); ++i) {
1507 /* Restore reservations of trains. */
1508 RestoreTrainReservation(affected_vehicles[i]);
1511 /* Check whether we need to expand the reservation of trains already on the station. */
1512 TileArea update_reservation_area;
1513 if (axis == AXIS_X) {
1514 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1515 } else {
1516 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1519 for (TileIndex tile : update_reservation_area) {
1520 /* Don't even try to make eye candy parts reserved. */
1521 if (IsStationTileBlocked(tile)) continue;
1523 DiagDirection dir = AxisToDiagDir(axis);
1524 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1525 TileIndex platform_begin = tile;
1526 TileIndex platform_end = tile;
1528 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1529 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1530 platform_begin = next_tile;
1532 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1533 platform_end = next_tile;
1536 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1537 bool reservation = false;
1538 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1539 reservation = HasStationReservation(t);
1542 if (reservation) {
1543 SetRailStationPlatformReservation(platform_begin, dir, true);
1547 st->MarkTilesDirty(false);
1548 st->AfterStationTileSetChange(true, STATION_RAIL);
1551 return cost;
1554 static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1556 restart:
1558 /* too small? */
1559 if (ta.w != 0 && ta.h != 0) {
1560 /* check the left side, x = constant, y changes */
1561 for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1562 /* the left side is unused? */
1563 if (++i == ta.h) {
1564 ta.tile += TileDiffXY(1, 0);
1565 ta.w--;
1566 goto restart;
1570 /* check the right side, x = constant, y changes */
1571 for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1572 /* the right side is unused? */
1573 if (++i == ta.h) {
1574 ta.w--;
1575 goto restart;
1579 /* check the upper side, y = constant, x changes */
1580 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1581 /* the left side is unused? */
1582 if (++i == ta.w) {
1583 ta.tile += TileDiffXY(0, 1);
1584 ta.h--;
1585 goto restart;
1589 /* check the lower side, y = constant, x changes */
1590 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1591 /* the left side is unused? */
1592 if (++i == ta.w) {
1593 ta.h--;
1594 goto restart;
1597 } else {
1598 ta.Clear();
1601 return ta;
1604 static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1606 return st->TileBelongsToRailStation(tile);
1609 static void MakeRailStationAreaSmaller(BaseStation *st)
1611 st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1614 static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1616 return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1619 static void MakeShipStationAreaSmaller(Station *st)
1621 st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1622 UpdateStationDockingTiles(st);
1625 static bool TileBelongsToRoadWaypointStation(BaseStation *st, TileIndex tile)
1627 return IsRoadWaypointTile(tile) && GetStationIndex(tile) == st->index;
1630 void MakeRoadWaypointStationAreaSmaller(BaseStation *st, TileArea &road_waypoint_area)
1632 road_waypoint_area = MakeStationAreaSmaller(st, road_waypoint_area, TileBelongsToRoadWaypointStation);
1636 * Remove a number of tiles from any rail station within the area.
1637 * @param ta the area to clear station tile from.
1638 * @param affected_stations the stations affected.
1639 * @param flags the command flags.
1640 * @param removal_cost the cost for removing the tile, including the rail.
1641 * @param keep_rail whether to keep the rail of the station.
1642 * @tparam T the type of station to remove.
1643 * @return the number of cleared tiles or an error.
1645 template <class T>
1646 CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1648 /* Count of the number of tiles removed */
1649 int quantity = 0;
1650 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1651 /* Accumulator for the errors seen during clearing. If no errors happen,
1652 * and the quantity is 0 there is no station. Otherwise it will be one
1653 * of the other error that got accumulated. */
1654 CommandCost error;
1656 /* Do the action for every tile into the area */
1657 for (TileIndex tile : ta) {
1658 /* Make sure the specified tile is a rail station */
1659 if (!HasStationTileRail(tile)) continue;
1661 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1662 CommandCost ret = EnsureNoVehicleOnGround(tile);
1663 error.AddCost(ret);
1664 if (ret.Failed()) continue;
1666 /* Check ownership of station */
1667 T *st = T::GetByTile(tile);
1668 if (st == nullptr) continue;
1670 if (_current_company != OWNER_WATER) {
1671 ret = CheckOwnership(st->owner);
1672 error.AddCost(ret);
1673 if (ret.Failed()) continue;
1676 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1677 quantity++;
1679 if (keep_rail || IsStationTileBlocked(tile)) {
1680 /* Don't refund the 'steel' of the track when we keep the
1681 * rail, or when the tile didn't have any rail at all. */
1682 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1685 if (flags & DC_EXEC) {
1686 /* read variables before the station tile is removed */
1687 uint specindex = GetCustomStationSpecIndex(tile);
1688 Track track = GetRailStationTrack(tile);
1689 Owner owner = GetTileOwner(tile);
1690 RailType rt = GetRailType(tile);
1691 Train *v = nullptr;
1693 if (HasStationReservation(tile)) {
1694 v = GetTrainForReservation(tile, track);
1695 if (v != nullptr) FreeTrainReservation(v);
1698 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1699 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1701 DoClearSquare(tile);
1702 DeleteNewGRFInspectWindow(GSF_STATIONS, tile.base());
1703 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1704 Company::Get(owner)->infrastructure.station--;
1705 DirtyCompanyInfrastructureWindows(owner);
1707 st->rect.AfterRemoveTile(st, tile);
1708 AddTrackToSignalBuffer(tile, track, owner);
1709 YapfNotifyTrackLayoutChange(tile, track);
1711 DeallocateSpecFromStation(st, specindex);
1713 include(affected_stations, st);
1715 if (v != nullptr) RestoreTrainReservation(v);
1719 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1721 for (T *st : affected_stations) {
1723 /* now we need to make the "spanned" area of the railway station smaller
1724 * if we deleted something at the edges.
1725 * we also need to adjust train_tile. */
1726 MakeRailStationAreaSmaller(st);
1727 UpdateStationSignCoord(st);
1729 /* if we deleted the whole station, delete the train facility. */
1730 if (st->train_station.tile == INVALID_TILE) {
1731 st->facilities &= ~FACIL_TRAIN;
1732 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
1733 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1734 MarkCatchmentTilesDirty();
1735 st->UpdateVirtCoord();
1736 DeleteStationIfEmpty(st);
1740 total_cost.AddCost(quantity * removal_cost);
1741 return total_cost;
1745 * Remove a single tile from a rail station.
1746 * This allows for custom-built station with holes and weird layouts
1747 * @param flags operation to perform
1748 * @param start tile of station piece to remove
1749 * @param end other edge of the rect to remove
1750 * @param keep_rail if set keep the rail
1751 * @return the cost of this operation or an error
1753 CommandCost CmdRemoveFromRailStation(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
1755 if (end == 0) end = start;
1756 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1758 TileArea ta(start, end);
1759 std::vector<Station *> affected_stations;
1761 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], keep_rail);
1762 if (ret.Failed()) return ret;
1764 /* Do all station specific functions here. */
1765 for (Station *st : affected_stations) {
1767 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1768 st->MarkTilesDirty(false);
1769 MarkCatchmentTilesDirty();
1770 st->RecomputeCatchment();
1773 /* Now apply the rail cost to the number that we deleted */
1774 return ret;
1778 * Remove a single tile from a waypoint.
1779 * This allows for custom-built waypoint with holes and weird layouts
1780 * @param flags operation to perform
1781 * @param start tile of waypoint piece to remove
1782 * @param end other edge of the rect to remove
1783 * @param keep_rail if set keep the rail
1784 * @return the cost of this operation or an error
1786 CommandCost CmdRemoveFromRailWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
1788 if (end == 0) end = start;
1789 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1791 TileArea ta(start, end);
1792 std::vector<Waypoint *> affected_stations;
1794 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], keep_rail);
1799 * Remove a rail station/waypoint
1800 * @param st The station/waypoint to remove the rail part from
1801 * @param flags operation to perform
1802 * @param removal_cost the cost for removing a tile
1803 * @tparam T the type of station to remove
1804 * @return cost or failure of operation
1806 template <class T>
1807 CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
1809 /* Current company owns the station? */
1810 if (_current_company != OWNER_WATER) {
1811 CommandCost ret = CheckOwnership(st->owner);
1812 if (ret.Failed()) return ret;
1815 /* determine width and height of platforms */
1816 TileArea ta = st->train_station;
1818 assert(ta.w != 0 && ta.h != 0);
1820 CommandCost cost(EXPENSES_CONSTRUCTION);
1821 /* clear all areas of the station */
1822 for (TileIndex tile : ta) {
1823 /* only remove tiles that are actually train station tiles */
1824 if (st->TileBelongsToRailStation(tile)) {
1825 std::vector<T*> affected_stations; // dummy
1826 CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1827 if (ret.Failed()) return ret;
1828 cost.AddCost(ret);
1832 return cost;
1836 * Remove a rail station
1837 * @param tile Tile of the station.
1838 * @param flags operation to perform
1839 * @return cost or failure of operation
1841 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1843 /* if there is flooding, remove platforms tile by tile */
1844 if (_current_company == OWNER_WATER) {
1845 return Command<CMD_REMOVE_FROM_RAIL_STATION>::Do(DC_EXEC, tile, 0, false);
1848 Station *st = Station::GetByTile(tile);
1849 CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1851 if (flags & DC_EXEC) st->RecomputeCatchment();
1853 return cost;
1857 * Remove a rail waypoint
1858 * @param tile Tile of the waypoint.
1859 * @param flags operation to perform
1860 * @return cost or failure of operation
1862 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1864 /* if there is flooding, remove waypoints tile by tile */
1865 if (_current_company == OWNER_WATER) {
1866 return Command<CMD_REMOVE_FROM_RAIL_WAYPOINT>::Do(DC_EXEC, tile, 0, false);
1869 return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1874 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1875 * @param st The Station to do the whole procedure for
1876 * @return a pointer to where to link a new RoadStop*
1878 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1880 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1882 if (*primary_stop == nullptr) {
1883 /* we have no roadstop of the type yet, so write a "primary stop" */
1884 return primary_stop;
1885 } else {
1886 /* there are stops already, so append to the end of the list */
1887 RoadStop *stop = *primary_stop;
1888 while (stop->next != nullptr) stop = stop->next;
1889 return &stop->next;
1893 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
1894 CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
1897 * Find a nearby station that joins this road stop.
1898 * @param existing_stop an existing road stop we build over
1899 * @param station_to_join the station to join to
1900 * @param adjacent whether adjacent stations are allowed
1901 * @param ta the area of the newly build station
1902 * @param st 'return' pointer for the found station
1903 * @return command cost with the error or 'okay'
1905 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1907 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1911 * Calculates cost of new road stops within the area.
1912 * @param tile_area Area to check.
1913 * @param flags Operation to perform.
1914 * @param is_drive_through True if trying to build a drive-through station.
1915 * @param station_type Station type (bus, truck or road waypoint).
1916 * @param axis Axis of a drive-through road stop.
1917 * @param ddir Entrance direction (#DiagDirection) for normal stops. Converted to the axis for drive-through stops.
1918 * @param station StationID to be queried and returned if available.
1919 * @param rt Road type to build, may be INVALID_ROADTYPE if an existing road is required.
1920 * @param unit_cost The cost to build one road stop of the current type.
1921 * @return The cost in case of success, or an error code if it failed.
1923 CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlag flags, bool is_drive_through, StationType station_type, Axis axis, DiagDirection ddir, StationID *est, RoadType rt, Money unit_cost)
1925 uint invalid_dirs = 0;
1926 if (is_drive_through) {
1927 SetBit(invalid_dirs, AxisToDiagDir(axis));
1928 SetBit(invalid_dirs, ReverseDiagDir(AxisToDiagDir(axis)));
1929 } else {
1930 SetBit(invalid_dirs, ddir);
1933 /* Check every tile in the area. */
1934 int allowed_z = -1;
1935 CommandCost cost(EXPENSES_CONSTRUCTION);
1936 for (TileIndex cur_tile : tile_area) {
1937 CommandCost ret = CheckFlatLandRoadStop(cur_tile, allowed_z, flags, invalid_dirs, is_drive_through, station_type, axis, est, rt);
1938 if (ret.Failed()) return ret;
1940 bool is_preexisting_roadstop = IsTileType(cur_tile, MP_STATION) && IsAnyRoadStop(cur_tile);
1942 /* Only add costs if a stop doesn't already exist in the location */
1943 if (!is_preexisting_roadstop) {
1944 cost.AddCost(ret);
1945 cost.AddCost(unit_cost);
1949 return cost;
1953 * Build a bus or truck stop.
1954 * @param flags Operation to perform.
1955 * @param tile Northernmost tile of the stop.
1956 * @param width Width of the road stop.
1957 * @param length Length of the road stop.
1958 * @param stop_type Type of road stop (bus/truck).
1959 * @param is_drive_through False for normal stops, true for drive-through.
1960 * @param ddir Entrance direction (#DiagDirection) for normal stops. Converted to the axis for drive-through stops.
1961 * @param rt The roadtype.
1962 * @param spec_class Road stop spec class.
1963 * @param spec_index Road stop spec index.
1964 * @param station_to_join Station ID to join (NEW_STATION if build new one).
1965 * @param adjacent Allow stations directly adjacent to other stations.
1966 * @return The cost of this operation or an error.
1968 CommandCost CmdBuildRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through,
1969 DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1971 if (!ValParamRoadType(rt) || !IsValidDiagDirection(ddir) || stop_type >= ROADSTOP_END) return CMD_ERROR;
1972 bool reuse = (station_to_join != NEW_STATION);
1973 if (!reuse) station_to_join = INVALID_STATION;
1974 bool distant_join = (station_to_join != INVALID_STATION);
1976 /* Check if the given station class is valid */
1977 if (static_cast<uint>(spec_class) >= RoadStopClass::GetClassCount()) return CMD_ERROR;
1978 const RoadStopClass *cls = RoadStopClass::Get(spec_class);
1979 if (IsWaypointClass(*cls)) return CMD_ERROR;
1980 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1982 const RoadStopSpec *roadstopspec = cls->GetSpec(spec_index);
1983 if (roadstopspec != nullptr) {
1984 if (stop_type == ROADSTOP_TRUCK && roadstopspec->stop_type != ROADSTOPTYPE_FREIGHT && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1985 if (stop_type == ROADSTOP_BUS && roadstopspec->stop_type != ROADSTOPTYPE_PASSENGER && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1986 if (!is_drive_through && HasBit(roadstopspec->flags, RSF_DRIVE_THROUGH_ONLY)) return CMD_ERROR;
1989 /* Check if the requested road stop is too big */
1990 if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1991 /* Check for incorrect width / length. */
1992 if (width == 0 || length == 0) return CMD_ERROR;
1993 /* Check if the first tile and the last tile are valid */
1994 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
1996 TileArea roadstop_area(tile, width, length);
1998 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2000 /* Trams only have drive through stops */
2001 if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
2003 Axis axis = DiagDirToAxis(ddir);
2005 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2006 if (ret.Failed()) return ret;
2008 bool is_truck_stop = stop_type != ROADSTOP_BUS;
2010 /* Total road stop cost. */
2011 Money unit_cost;
2012 if (roadstopspec != nullptr) {
2013 unit_cost = roadstopspec->GetBuildCost(is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS);
2014 } else {
2015 unit_cost = _price[is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS];
2017 StationID est = INVALID_STATION;
2018 CommandCost cost = CalculateRoadStopCost(roadstop_area, flags, is_drive_through, is_truck_stop ? STATION_TRUCK : STATION_BUS, axis, ddir, &est, rt, unit_cost);
2019 if (cost.Failed()) return cost;
2021 Station *st = nullptr;
2022 ret = FindJoiningRoadStop(est, station_to_join, adjacent, roadstop_area, &st);
2023 if (ret.Failed()) return ret;
2025 /* Check if this number of road stops can be allocated. */
2026 if (!RoadStop::CanAllocateItem(static_cast<size_t>(roadstop_area.w) * roadstop_area.h)) return_cmd_error(is_truck_stop ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
2028 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
2029 if (ret.Failed()) return ret;
2031 /* Check if we can allocate a custom stationspec to this station */
2032 int specindex = AllocateSpecToRoadStop(roadstopspec, st, (flags & DC_EXEC) != 0);
2033 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
2035 if (roadstopspec != nullptr) {
2036 /* Perform NewGRF checks */
2038 /* Check if the road stop is buildable */
2039 if (HasBit(roadstopspec->callback_mask, CBM_ROAD_STOP_AVAIL)) {
2040 uint16_t cb_res = GetRoadStopCallback(CBID_STATION_AVAILABILITY, 0, 0, roadstopspec, nullptr, INVALID_TILE, rt, is_truck_stop ? STATION_TRUCK : STATION_BUS, 0);
2041 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(roadstopspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
2045 if (flags & DC_EXEC) {
2046 /* Check every tile in the area. */
2047 for (TileIndex cur_tile : roadstop_area) {
2048 /* Get existing road types and owners before any tile clearing */
2049 RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_ROAD) : INVALID_ROADTYPE;
2050 RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_TRAM) : INVALID_ROADTYPE;
2051 Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_ROAD) : _current_company;
2052 Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_TRAM) : _current_company;
2054 if (IsTileType(cur_tile, MP_STATION) && IsStationRoadStop(cur_tile)) {
2055 RemoveRoadStop(cur_tile, flags, specindex);
2058 if (roadstopspec != nullptr) {
2059 /* Include this road stop spec's animation trigger bitmask
2060 * in the station's cached copy. */
2061 st->cached_roadstop_anim_triggers |= roadstopspec->animation.triggers;
2064 RoadStop *road_stop = new RoadStop(cur_tile);
2065 /* Insert into linked list of RoadStops. */
2066 RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
2067 *currstop = road_stop;
2069 if (is_truck_stop) {
2070 st->truck_station.Add(cur_tile);
2071 } else {
2072 st->bus_station.Add(cur_tile);
2075 /* Initialize an empty station. */
2076 st->AddFacility(is_truck_stop ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
2078 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
2080 RoadStopType rs_type = is_truck_stop ? ROADSTOP_TRUCK : ROADSTOP_BUS;
2081 if (is_drive_through) {
2082 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2083 * bits first. */
2084 if (IsNormalRoadTile(cur_tile)) {
2085 UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD)));
2086 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM)));
2089 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2090 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2092 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, (rs_type == ROADSTOP_BUS ? STATION_BUS : STATION_TRUCK), road_rt, tram_rt, axis);
2093 road_stop->MakeDriveThrough();
2094 } else {
2095 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2096 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2097 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
2099 UpdateCompanyRoadInfrastructure(road_rt, road_owner, ROAD_STOP_TRACKBIT_FACTOR);
2100 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, ROAD_STOP_TRACKBIT_FACTOR);
2101 Company::Get(st->owner)->infrastructure.station++;
2103 SetCustomRoadStopSpecIndex(cur_tile, specindex);
2104 if (roadstopspec != nullptr) {
2105 st->SetRoadStopRandomBits(cur_tile, GB(Random(), 0, 8));
2106 TriggerRoadStopAnimation(st, cur_tile, SAT_BUILT);
2109 MarkTileDirtyByTile(cur_tile);
2112 if (st != nullptr) {
2113 st->AfterStationTileSetChange(true, is_truck_stop ? STATION_TRUCK: STATION_BUS);
2116 return cost;
2120 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
2122 if (v->type == VEH_ROAD) {
2123 /* Okay... we are a road vehicle on a drive through road stop.
2124 * But that road stop has just been removed, so we need to make
2125 * sure we are in a valid state... however, vehicles can also
2126 * turn on road stop tiles, so only clear the 'road stop' state
2127 * bits and only when the state was 'in road stop', otherwise
2128 * we'll end up clearing the turn around bits. */
2129 RoadVehicle *rv = RoadVehicle::From(v);
2130 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
2133 return nullptr;
2138 * Remove a bus station/truck stop
2139 * @param tile TileIndex been queried
2140 * @param flags operation to perform
2141 * @param replacement_spec_index replacement spec index to avoid deallocating, if < 0, tile is not being replaced
2142 * @return cost or failure of operation
2144 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2146 Station *st = Station::GetByTile(tile);
2148 if (_current_company != OWNER_WATER) {
2149 CommandCost ret = CheckOwnership(st->owner);
2150 if (ret.Failed()) return ret;
2153 bool is_truck = IsTruckStop(tile);
2155 RoadStop **primary_stop;
2156 RoadStop *cur_stop;
2157 if (is_truck) { // truck stop
2158 primary_stop = &st->truck_stops;
2159 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
2160 } else {
2161 primary_stop = &st->bus_stops;
2162 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
2165 assert(cur_stop != nullptr);
2167 /* don't do the check for drive-through road stops when company bankrupts */
2168 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
2169 /* remove the 'going through road stop' status from all vehicles on that tile */
2170 if (flags & DC_EXEC) FindVehicleOnPos(tile, nullptr, &ClearRoadStopStatusEnum);
2171 } else {
2172 CommandCost ret = EnsureNoVehicleOnGround(tile);
2173 if (ret.Failed()) return ret;
2176 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2178 if (flags & DC_EXEC) {
2179 if (*primary_stop == cur_stop) {
2180 /* removed the first stop in the list */
2181 *primary_stop = cur_stop->next;
2182 /* removed the only stop? */
2183 if (*primary_stop == nullptr) {
2184 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
2185 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2187 } else {
2188 /* tell the predecessor in the list to skip this stop */
2189 RoadStop *pred = *primary_stop;
2190 while (pred->next != cur_stop) pred = pred->next;
2191 pred->next = cur_stop->next;
2194 /* Update company infrastructure counts. */
2195 for (RoadTramType rtt : _roadtramtypes) {
2196 RoadType rt = GetRoadType(tile, rtt);
2197 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2200 Company::Get(st->owner)->infrastructure.station--;
2201 DirtyCompanyInfrastructureWindows(st->owner);
2203 DeleteAnimatedTile(tile);
2205 uint specindex = GetCustomRoadStopSpecIndex(tile);
2207 DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile.base());
2209 if (IsDriveThroughStopTile(tile)) {
2210 /* Clears the tile for us */
2211 cur_stop->ClearDriveThrough();
2212 } else {
2213 DoClearSquare(tile);
2216 delete cur_stop;
2218 /* Make sure no vehicle is going to the old roadstop. Narrow the search to any road vehicles with an order to
2219 * this station, then look for any currently heading to the tile. */
2220 StationID station_id = st->index;
2221 FindVehiclesWithOrder(
2222 [](const Vehicle *v) { return v->type == VEH_ROAD; },
2223 [station_id](const Order *order) { return order->IsType(OT_GOTO_STATION) && order->GetDestination() == station_id; },
2224 [station_id, tile](Vehicle *v) {
2225 if (v->current_order.IsType(OT_GOTO_STATION) && v->dest_tile == tile) {
2226 v->SetDestTile(v->GetOrderStationLocation(station_id));
2231 st->rect.AfterRemoveTile(st, tile);
2233 if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? STATION_TRUCK: STATION_BUS);
2235 st->RemoveRoadStopTileData(tile);
2236 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex);
2238 /* Update the tile area of the truck/bus stop */
2239 if (is_truck) {
2240 st->truck_station.Clear();
2241 for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2242 } else {
2243 st->bus_station.Clear();
2244 for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2248 Price category = is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS;
2249 return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(category) : _price[category]);
2253 * Remove a road waypoint
2254 * @param tile TileIndex been queried
2255 * @param flags operation to perform
2256 * @param replacement_spec_index replacement spec index to avoid deallocating, if < 0, tile is not being replaced
2257 * @return cost or failure of operation
2259 CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2261 Waypoint *wp = Waypoint::GetByTile(tile);
2263 if (_current_company != OWNER_WATER) {
2264 CommandCost ret = CheckOwnership(wp->owner);
2265 if (ret.Failed()) return ret;
2268 /* Ignore vehicles when the company goes bankrupt. The road will remain, any vehicles going to the waypoint will be removed. */
2269 if (!(flags & DC_BANKRUPT)) {
2270 CommandCost ret = EnsureNoVehicleOnGround(tile);
2271 if (ret.Failed()) return ret;
2274 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2276 if (flags & DC_EXEC) {
2277 /* Update company infrastructure counts. */
2278 for (RoadTramType rtt : _roadtramtypes) {
2279 RoadType rt = GetRoadType(tile, rtt);
2280 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2283 Company::Get(wp->owner)->infrastructure.station--;
2284 DirtyCompanyInfrastructureWindows(wp->owner);
2286 DeleteAnimatedTile(tile);
2288 uint specindex = GetCustomRoadStopSpecIndex(tile);
2290 DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile.base());
2292 DoClearSquare(tile);
2294 wp->rect.AfterRemoveTile(wp, tile);
2296 wp->RemoveRoadStopTileData(tile);
2297 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(wp, specindex);
2299 if (replacement_spec_index < 0) {
2300 MakeRoadWaypointStationAreaSmaller(wp, wp->road_waypoint_area);
2302 UpdateStationSignCoord(wp);
2304 /* if we deleted the whole waypoint, delete the road facility. */
2305 if (wp->road_waypoint_area.tile == INVALID_TILE) {
2306 wp->facilities &= ~(FACIL_BUS_STOP | FACIL_TRUCK_STOP);
2307 SetWindowWidgetDirty(WC_STATION_VIEW, wp->index, WID_SV_ROADVEHS);
2308 wp->UpdateVirtCoord();
2309 DeleteStationIfEmpty(wp);
2314 return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(PR_CLEAR_STATION_TRUCK) : _price[PR_CLEAR_STATION_TRUCK]);
2318 * Remove a tile area of road stop or road waypoints
2319 * @param flags operation to perform
2320 * @param roadstop_area tile area of road stop or road waypoint tiles to remove
2321 * @param station_type station type to remove
2322 * @param remove_road Remove roads of drive-through stops?
2323 * @return the cost of this operation or an error
2325 static CommandCost RemoveGenericRoadStop(DoCommandFlag flags, const TileArea &roadstop_area, StationType station_type, bool remove_road)
2327 CommandCost cost(EXPENSES_CONSTRUCTION);
2328 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2329 bool had_success = false;
2331 for (TileIndex cur_tile : roadstop_area) {
2332 /* Make sure the specified tile is a road stop of the correct type */
2333 if (!IsTileType(cur_tile, MP_STATION) || !IsAnyRoadStop(cur_tile) || GetStationType(cur_tile) != station_type) continue;
2335 /* Save information on to-be-restored roads before the stop is removed. */
2336 RoadBits road_bits = ROAD_NONE;
2337 RoadType road_type[] = { INVALID_ROADTYPE, INVALID_ROADTYPE };
2338 Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
2339 if (IsDriveThroughStopTile(cur_tile)) {
2340 for (RoadTramType rtt : _roadtramtypes) {
2341 road_type[rtt] = GetRoadType(cur_tile, rtt);
2342 if (road_type[rtt] == INVALID_ROADTYPE) continue;
2343 road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2344 /* If we don't want to preserve our roads then restore only roads of others. */
2345 if (remove_road && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2347 road_bits = AxisToRoadBits(GetDriveThroughStopAxis(cur_tile));
2350 CommandCost ret;
2351 if (station_type == STATION_ROADWAYPOINT) {
2352 ret = RemoveRoadWaypointStop(cur_tile, flags);
2353 } else {
2354 ret = RemoveRoadStop(cur_tile, flags);
2356 if (ret.Failed()) {
2357 last_error = ret;
2358 continue;
2360 cost.AddCost(ret);
2361 had_success = true;
2363 /* Restore roads. */
2364 if ((flags & DC_EXEC) && (road_type[RTT_ROAD] != INVALID_ROADTYPE || road_type[RTT_TRAM] != INVALID_ROADTYPE)) {
2365 MakeRoadNormal(cur_tile, road_bits, road_type[RTT_ROAD], road_type[RTT_TRAM], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2366 road_owner[RTT_ROAD], road_owner[RTT_TRAM]);
2368 /* Update company infrastructure counts. */
2369 int count = CountBits(road_bits);
2370 UpdateCompanyRoadInfrastructure(road_type[RTT_ROAD], road_owner[RTT_ROAD], count);
2371 UpdateCompanyRoadInfrastructure(road_type[RTT_TRAM], road_owner[RTT_TRAM], count);
2375 return had_success ? cost : last_error;
2379 * Remove bus or truck stops.
2380 * @param flags Operation to perform.
2381 * @param tile Northernmost tile of the removal area.
2382 * @param width Width of the removal area.
2383 * @param height Height of the removal area.
2384 * @param stop_type Type of stop (bus/truck).
2385 * @param remove_road Remove roads of drive-through stops?
2386 * @return The cost of this operation or an error.
2388 CommandCost CmdRemoveRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
2390 if (stop_type >= ROADSTOP_END) return CMD_ERROR;
2391 /* Check for incorrect width / height. */
2392 if (width == 0 || height == 0) return CMD_ERROR;
2393 /* Check if the first tile and the last tile are valid */
2394 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2395 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2396 if (remove_road && (flags & DC_BANKRUPT)) return CMD_ERROR;
2398 TileArea roadstop_area(tile, width, height);
2400 return RemoveGenericRoadStop(flags, roadstop_area, stop_type == ROADSTOP_BUS ? STATION_BUS : STATION_TRUCK, remove_road);
2404 * Remove road waypoints.
2405 * @param flags operation to perform
2406 * @param start tile of road waypoint piece to remove
2407 * @param end other edge of the rect to remove
2408 * @return the cost of this operation or an error
2410 CommandCost CmdRemoveFromRoadWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end)
2412 if (end == 0) end = start;
2413 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
2415 TileArea roadstop_area(start, end);
2417 return RemoveGenericRoadStop(flags, roadstop_area, STATION_ROADWAYPOINT, false);
2421 * Get a possible noise reduction factor based on distance from town center.
2422 * The further you get, the less noise you generate.
2423 * So all those folks at city council can now happily slee... work in their offices
2424 * @param as airport information
2425 * @param distance minimum distance between town and airport
2426 * @return the noise that will be generated, according to distance
2428 uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2430 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2431 * So no need to go any further*/
2432 if (as->noise_level < 2) return as->noise_level;
2434 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2435 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2436 * Basically, it says that the less tolerant a town is, the bigger the distance before
2437 * an actual decrease can be granted */
2438 uint8_t town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2440 /* now, we want to have the distance segmented using the distance judged bareable by town
2441 * This will give us the coefficient of reduction the distance provides. */
2442 uint noise_reduction = distance / town_tolerance_distance;
2444 /* If the noise reduction equals the airport noise itself, don't give it for free.
2445 * Otherwise, simply reduce the airport's level. */
2446 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2450 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2451 * If two towns have the same distance, town with lower index is returned.
2452 * @param as airport's description
2453 * @param rotation airport's rotation
2454 * @param tile origin tile (top corner of the airport)
2455 * @param it An iterator over all airport tiles (consumed)
2456 * @param[out] mindist Minimum distance to town
2457 * @return nearest town to airport
2459 Town *AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
2461 assert(Town::GetNumItems() > 0);
2463 Town *nearest = nullptr;
2465 auto width = as->size_x;
2466 auto height = as->size_y;
2467 if (rotation == DIR_E || rotation == DIR_W) std::swap(width, height);
2469 uint perimeter_min_x = TileX(tile);
2470 uint perimeter_min_y = TileY(tile);
2471 uint perimeter_max_x = perimeter_min_x + width - 1;
2472 uint perimeter_max_y = perimeter_min_y + height - 1;
2474 mindist = UINT_MAX - 1; // prevent overflow
2476 for (TileIndex cur_tile = *it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2477 assert(IsInsideBS(TileX(cur_tile), perimeter_min_x, width));
2478 assert(IsInsideBS(TileY(cur_tile), perimeter_min_y, height));
2479 if (TileX(cur_tile) == perimeter_min_x || TileX(cur_tile) == perimeter_max_x || TileY(cur_tile) == perimeter_min_y || TileY(cur_tile) == perimeter_max_y) {
2480 Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2481 if (t == nullptr) continue;
2483 uint dist = DistanceManhattan(t->xy, cur_tile);
2484 if (dist == mindist && t->index < nearest->index) nearest = t;
2485 if (dist < mindist) {
2486 nearest = t;
2487 mindist = dist;
2492 return nearest;
2496 * Finds the town nearest to given existing airport. Based on minimal manhattan distance to any airport's tile.
2497 * If two towns have the same distance, town with lower index is returned.
2498 * @param station existing station with airport
2499 * @param[out] mindist Minimum distance to town
2500 * @return nearest town to airport
2502 static Town *AirportGetNearestTown(const Station *st, uint &mindist)
2504 return AirportGetNearestTown(st->airport.GetSpec(), st->airport.rotation, st->airport.tile, AirportTileIterator(st), mindist);
2508 /** Recalculate the noise generated by the airports of each town */
2509 void UpdateAirportsNoise()
2511 for (Town *t : Town::Iterate()) t->noise_reached = 0;
2513 for (const Station *st : Station::Iterate()) {
2514 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2515 uint dist;
2516 Town *nearest = AirportGetNearestTown(st, dist);
2517 nearest->noise_reached += GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2523 * Place an Airport.
2524 * @param flags operation to perform
2525 * @param tile tile where airport will be built
2526 * @param airport_type airport type, @see airport.h
2527 * @param layout airport layout
2528 * @param station_to_join station ID to join (NEW_STATION if build new one)
2529 * @param allow_adjacent allow airports directly adjacent to other airports.
2530 * @return the cost of this operation or an error
2532 CommandCost CmdBuildAirport(DoCommandFlag flags, TileIndex tile, uint8_t airport_type, uint8_t layout, StationID station_to_join, bool allow_adjacent)
2534 bool reuse = (station_to_join != NEW_STATION);
2535 if (!reuse) station_to_join = INVALID_STATION;
2536 bool distant_join = (station_to_join != INVALID_STATION);
2538 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2540 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2542 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2543 if (ret.Failed()) return ret;
2545 /* Check if a valid, buildable airport was chosen for construction */
2546 const AirportSpec *as = AirportSpec::Get(airport_type);
2547 if (!as->IsAvailable() || layout >= as->layouts.size()) return CMD_ERROR;
2548 if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2550 Direction rotation = as->layouts[layout].rotation;
2551 int w = as->size_x;
2552 int h = as->size_y;
2553 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2554 TileArea airport_area = TileArea(tile, w, h);
2556 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2557 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2560 AirportTileTableIterator tile_iter(as->layouts[layout].tiles.data(), tile);
2561 CommandCost cost = CheckFlatLandAirport(tile_iter, flags);
2562 if (cost.Failed()) return cost;
2564 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2565 uint dist;
2566 Town *nearest = AirportGetNearestTown(as, rotation, tile, std::move(tile_iter), dist);
2567 uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2569 /* Check if local auth would allow a new airport */
2570 StringID authority_refuse_message = STR_NULL;
2571 Town *authority_refuse_town = nullptr;
2573 if (_settings_game.economy.station_noise_level) {
2574 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2575 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2576 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2577 authority_refuse_town = nearest;
2579 } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
2580 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2581 uint num = 0;
2582 for (const Station *st : Station::Iterate()) {
2583 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2585 if (num >= 2) {
2586 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2587 authority_refuse_town = t;
2591 if (authority_refuse_message != STR_NULL) {
2592 SetDParam(0, authority_refuse_town->index);
2593 return_cmd_error(authority_refuse_message);
2596 Station *st = nullptr;
2597 ret = FindJoiningStation(INVALID_STATION, station_to_join, allow_adjacent, airport_area, &st);
2598 if (ret.Failed()) return ret;
2600 /* Distant join */
2601 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2603 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2604 if (ret.Failed()) return ret;
2606 if (st != nullptr && st->airport.tile != INVALID_TILE) {
2607 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2610 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2611 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2614 if (flags & DC_EXEC) {
2615 /* Always add the noise, so there will be no need to recalculate when option toggles */
2616 nearest->noise_reached += newnoise_level;
2618 st->AddFacility(FACIL_AIRPORT, tile);
2619 st->airport.type = airport_type;
2620 st->airport.layout = layout;
2621 st->airport.flags = 0;
2622 st->airport.rotation = rotation;
2624 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2626 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2627 Tile t(iter);
2628 MakeAirport(t, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2629 SetStationTileRandomBits(t, GB(Random(), 0, 4));
2630 st->airport.Add(iter);
2632 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(t);
2635 /* Only call the animation trigger after all tiles have been built */
2636 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2637 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2640 UpdateAirplanesOnNewStation(st);
2642 Company::Get(st->owner)->infrastructure.airport++;
2644 st->AfterStationTileSetChange(true, STATION_AIRPORT);
2645 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2647 if (_settings_game.economy.station_noise_level) {
2648 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2652 return cost;
2656 * Remove an airport
2657 * @param tile TileIndex been queried
2658 * @param flags operation to perform
2659 * @return cost or failure of operation
2661 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2663 Station *st = Station::GetByTile(tile);
2665 if (_current_company != OWNER_WATER) {
2666 CommandCost ret = CheckOwnership(st->owner);
2667 if (ret.Failed()) return ret;
2670 tile = st->airport.tile;
2672 CommandCost cost(EXPENSES_CONSTRUCTION);
2674 for (const Aircraft *a : Aircraft::Iterate()) {
2675 if (!a->IsNormalAircraft()) continue;
2676 if (a->targetairport == st->index && a->state != FLYING) {
2677 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2681 if (flags & DC_EXEC) {
2682 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2683 TileIndex tile_cur = st->airport.GetHangarTile(i);
2684 OrderBackup::Reset(tile_cur, false);
2685 CloseWindowById(WC_VEHICLE_DEPOT, tile_cur);
2688 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2689 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2690 * need of recalculation */
2691 uint dist;
2692 Town *nearest = AirportGetNearestTown(st, dist);
2693 nearest->noise_reached -= GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2695 if (_settings_game.economy.station_noise_level) {
2696 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2700 for (TileIndex tile_cur : st->airport) {
2701 if (!st->TileBelongsToAirport(tile_cur)) continue;
2703 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2704 if (ret.Failed()) return ret;
2706 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2708 if (flags & DC_EXEC) {
2709 DeleteAnimatedTile(tile_cur);
2710 DoClearSquare(tile_cur);
2711 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur.base());
2715 if (flags & DC_EXEC) {
2716 /* Clear the persistent storage. */
2717 delete st->airport.psa;
2719 st->rect.AfterRemoveRect(st, st->airport);
2721 st->airport.Clear();
2722 st->facilities &= ~FACIL_AIRPORT;
2723 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2725 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2727 Company::Get(st->owner)->infrastructure.airport--;
2729 st->AfterStationTileSetChange(false, STATION_AIRPORT);
2731 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2734 return cost;
2738 * Open/close an airport to incoming aircraft.
2739 * @param flags Operation to perform.
2740 * @param station_id Station ID of the airport.
2741 * @return the cost of this operation or an error
2743 CommandCost CmdOpenCloseAirport(DoCommandFlag flags, StationID station_id)
2745 if (!Station::IsValidID(station_id)) return CMD_ERROR;
2746 Station *st = Station::Get(station_id);
2748 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2750 CommandCost ret = CheckOwnership(st->owner);
2751 if (ret.Failed()) return ret;
2753 if (flags & DC_EXEC) {
2754 st->airport.flags ^= AIRPORT_CLOSED_block;
2755 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2757 return CommandCost();
2761 * Tests whether the company's vehicles have this station in orders
2762 * @param station station ID
2763 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2764 * @param company company ID
2766 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2768 for (const OrderList *orderlist : OrderList::Iterate()) {
2769 const Vehicle *v = orderlist->GetFirstSharedVehicle();
2770 assert(v != nullptr);
2771 if ((v->owner == company) != include_company) continue;
2773 for (const Order *order = orderlist->GetFirstOrder(); order != nullptr; order = order->next) {
2774 if (order->GetDestination() == station && (order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT))) {
2775 return true;
2779 return false;
2782 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2783 {-1, 0},
2784 { 0, 0},
2785 { 0, 0},
2786 { 0, -1}
2788 static const uint8_t _dock_w_chk[4] = { 2, 1, 2, 1 };
2789 static const uint8_t _dock_h_chk[4] = { 1, 2, 1, 2 };
2792 * Build a dock/haven.
2793 * @param flags operation to perform
2794 * @param tile tile where dock will be built
2795 * @param station_to_join station ID to join (NEW_STATION if build new one)
2796 * @param adjacent allow docks directly adjacent to other docks.
2797 * @return the cost of this operation or an error
2799 CommandCost CmdBuildDock(DoCommandFlag flags, TileIndex tile, StationID station_to_join, bool adjacent)
2801 bool reuse = (station_to_join != NEW_STATION);
2802 if (!reuse) station_to_join = INVALID_STATION;
2803 bool distant_join = (station_to_join != INVALID_STATION);
2805 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2807 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
2808 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2809 direction = ReverseDiagDir(direction);
2811 /* Docks cannot be placed on rapids */
2812 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2814 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2815 if (ret.Failed()) return ret;
2817 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2819 CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2820 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
2821 if (ret.Failed()) return ret;
2822 cost.AddCost(ret);
2824 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2826 if (!HasTileWaterGround(tile_cur) || !IsTileFlat(tile_cur)) {
2827 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2830 if (IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2832 /* Get the water class of the water tile before it is cleared.*/
2833 WaterClass wc = GetWaterClass(tile_cur);
2835 bool add_cost = !IsWaterTile(tile_cur);
2836 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
2837 if (ret.Failed()) return ret;
2838 if (add_cost) cost.AddCost(ret);
2840 tile_cur += TileOffsByDiagDir(direction);
2841 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2842 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2845 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2846 _dock_w_chk[direction], _dock_h_chk[direction]);
2848 /* middle */
2849 Station *st = nullptr;
2850 ret = FindJoiningStation(INVALID_STATION, station_to_join, adjacent, dock_area, &st);
2851 if (ret.Failed()) return ret;
2853 /* Distant join */
2854 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2856 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2857 if (ret.Failed()) return ret;
2859 if (flags & DC_EXEC) {
2860 st->ship_station.Add(tile);
2861 TileIndex flat_tile = tile + TileOffsByDiagDir(direction);
2862 st->ship_station.Add(flat_tile);
2863 st->AddFacility(FACIL_DOCK, tile);
2865 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2867 /* If the water part of the dock is on a canal, update infrastructure counts.
2868 * This is needed as we've cleared that tile before.
2869 * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
2870 * See: MakeWaterKeepingClass() */
2871 if (wc == WATER_CLASS_CANAL && !(HasTileWaterClass(flat_tile) && GetWaterClass(flat_tile) == WATER_CLASS_CANAL && IsTileOwner(flat_tile, _current_company))) {
2872 Company::Get(st->owner)->infrastructure.water++;
2874 Company::Get(st->owner)->infrastructure.station += 2;
2876 MakeDock(tile, st->owner, st->index, direction, wc);
2877 UpdateStationDockingTiles(st);
2879 st->AfterStationTileSetChange(true, STATION_DOCK);
2882 return cost;
2885 void RemoveDockingTile(TileIndex t)
2887 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2888 TileIndex tile = t + TileOffsByDiagDir(d);
2889 if (!IsValidTile(tile)) continue;
2891 if (IsTileType(tile, MP_STATION)) {
2892 Station *st = Station::GetByTile(tile);
2893 if (st != nullptr) UpdateStationDockingTiles(st);
2894 } else if (IsTileType(tile, MP_INDUSTRY)) {
2895 Station *neutral = Industry::GetByTile(tile)->neutral_station;
2896 if (neutral != nullptr) UpdateStationDockingTiles(neutral);
2902 * Clear docking tile status from tiles around a removed dock, if the tile has
2903 * no neighbours which would keep it as a docking tile.
2904 * @param tile Ex-dock tile to check.
2906 void ClearDockingTilesCheckingNeighbours(TileIndex tile)
2908 assert(IsValidTile(tile));
2910 /* Clear and maybe re-set docking tile */
2911 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2912 TileIndex docking_tile = tile + TileOffsByDiagDir(d);
2913 if (!IsValidTile(docking_tile)) continue;
2915 if (IsPossibleDockingTile(docking_tile)) {
2916 SetDockingTile(docking_tile, false);
2917 CheckForDockingTile(docking_tile);
2923 * Find the part of a dock that is land-based
2924 * @param t Dock tile to find land part of
2925 * @return tile of land part of dock
2927 static TileIndex FindDockLandPart(TileIndex t)
2929 assert(IsDockTile(t));
2931 StationGfx gfx = GetStationGfx(t);
2932 if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
2934 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2935 TileIndex tile = t + TileOffsByDiagDir(d);
2936 if (!IsValidTile(tile)) continue;
2937 if (!IsDockTile(tile)) continue;
2938 if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
2941 return INVALID_TILE;
2945 * Remove a dock
2946 * @param tile TileIndex been queried
2947 * @param flags operation to perform
2948 * @return cost or failure of operation
2950 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2952 Station *st = Station::GetByTile(tile);
2953 CommandCost ret = CheckOwnership(st->owner);
2954 if (ret.Failed()) return ret;
2956 if (!IsDockTile(tile)) return CMD_ERROR;
2958 TileIndex tile1 = FindDockLandPart(tile);
2959 if (tile1 == INVALID_TILE) return CMD_ERROR;
2960 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2962 ret = EnsureNoVehicleOnGround(tile1);
2963 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2964 if (ret.Failed()) return ret;
2966 if (flags & DC_EXEC) {
2967 DoClearSquare(tile1);
2968 MarkTileDirtyByTile(tile1);
2969 MakeWaterKeepingClass(tile2, st->owner);
2971 st->rect.AfterRemoveTile(st, tile1);
2972 st->rect.AfterRemoveTile(st, tile2);
2974 MakeShipStationAreaSmaller(st);
2975 if (st->ship_station.tile == INVALID_TILE) {
2976 st->ship_station.Clear();
2977 st->docking_station.Clear();
2978 st->facilities &= ~FACIL_DOCK;
2979 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2982 Company::Get(st->owner)->infrastructure.station -= 2;
2984 st->AfterStationTileSetChange(false, STATION_DOCK);
2986 ClearDockingTilesCheckingNeighbours(tile1);
2987 ClearDockingTilesCheckingNeighbours(tile2);
2989 for (Ship *s : Ship::Iterate()) {
2990 /* Find all ships going to our dock. */
2991 if (s->current_order.GetDestination() != st->index) {
2992 continue;
2995 /* Find ships that are marked as "loading" but are no longer on a
2996 * docking tile. Force them to leave the station (as they were loading
2997 * on the removed dock). */
2998 if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
2999 s->LeaveStation();
3002 /* If we no longer have a dock, mark the order as invalid and send
3003 * the ship to the next order (or, if there is none, make it
3004 * wander the world). */
3005 if (s->current_order.IsType(OT_GOTO_STATION) && !(st->facilities & FACIL_DOCK)) {
3006 s->SetDestTile(s->GetOrderStationLocation(st->index));
3011 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
3014 #include "table/station_land.h"
3017 * Get station tile layout for a station type and its station gfx.
3018 * @param st Station type to draw.
3019 * @param gfx StationGfx of tile to draw.
3020 * @return Tile layout to draw.
3022 const DrawTileSprites *GetStationTileLayout(StationType st, uint8_t gfx)
3024 const auto &layouts = _station_display_datas[st];
3025 if (gfx >= layouts.size()) gfx &= 1;
3026 return layouts.data() + gfx;
3030 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
3031 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
3032 * is set to the overlay to draw.
3033 * @param ti Positional info for the tile to decide snowyness etc. May be nullptr.
3034 * @param[in,out] ground Groundsprite to draw.
3035 * @param[out] overlay_offset Overlay to draw.
3036 * @return true if overlay can be drawn.
3038 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
3040 bool snow_desert;
3041 switch (*ground) {
3042 case SPR_RAIL_TRACK_X:
3043 case SPR_MONO_TRACK_X:
3044 case SPR_MGLV_TRACK_X:
3045 snow_desert = false;
3046 *overlay_offset = RTO_X;
3047 break;
3049 case SPR_RAIL_TRACK_Y:
3050 case SPR_MONO_TRACK_Y:
3051 case SPR_MGLV_TRACK_Y:
3052 snow_desert = false;
3053 *overlay_offset = RTO_Y;
3054 break;
3056 case SPR_RAIL_TRACK_X_SNOW:
3057 case SPR_MONO_TRACK_X_SNOW:
3058 case SPR_MGLV_TRACK_X_SNOW:
3059 snow_desert = true;
3060 *overlay_offset = RTO_X;
3061 break;
3063 case SPR_RAIL_TRACK_Y_SNOW:
3064 case SPR_MONO_TRACK_Y_SNOW:
3065 case SPR_MGLV_TRACK_Y_SNOW:
3066 snow_desert = true;
3067 *overlay_offset = RTO_Y;
3068 break;
3070 default:
3071 return false;
3074 if (ti != nullptr) {
3075 /* Decide snow/desert from tile */
3076 switch (_settings_game.game_creation.landscape) {
3077 case LT_ARCTIC:
3078 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
3079 break;
3081 case LT_TROPIC:
3082 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
3083 break;
3085 default:
3086 break;
3090 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
3091 return true;
3094 static void DrawTile_Station(TileInfo *ti)
3096 const NewGRFSpriteLayout *layout = nullptr;
3097 DrawTileSprites tmp_rail_layout;
3098 const DrawTileSprites *t = nullptr;
3099 int32_t total_offset;
3100 const RailTypeInfo *rti = nullptr;
3101 uint32_t relocation = 0;
3102 uint32_t ground_relocation = 0;
3103 BaseStation *st = nullptr;
3104 const StationSpec *statspec = nullptr;
3105 uint tile_layout = 0;
3107 if (HasStationRail(ti->tile)) {
3108 rti = GetRailTypeInfo(GetRailType(ti->tile));
3109 total_offset = rti->GetRailtypeSpriteOffset();
3111 if (IsCustomStationSpecIndex(ti->tile)) {
3112 /* look for customization */
3113 st = BaseStation::GetByTile(ti->tile);
3114 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
3116 if (statspec != nullptr) {
3117 tile_layout = GetStationGfx(ti->tile);
3119 if (HasBit(statspec->callback_mask, CBM_STATION_DRAW_TILE_LAYOUT)) {
3120 uint16_t callback = GetStationCallback(CBID_STATION_DRAW_TILE_LAYOUT, 0, 0, statspec, st, ti->tile);
3121 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
3124 /* Ensure the chosen tile layout is valid for this custom station */
3125 if (!statspec->renderdata.empty()) {
3126 layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
3127 if (!layout->NeedsPreprocessing()) {
3128 t = layout;
3129 layout = nullptr;
3134 } else {
3135 total_offset = 0;
3138 StationGfx gfx = GetStationGfx(ti->tile);
3139 if (IsAirport(ti->tile)) {
3140 gfx = GetAirportGfx(ti->tile);
3141 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
3142 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
3143 if (ats->grf_prop.spritegroup[0] != nullptr && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), ats)) {
3144 return;
3146 /* No sprite group (or no valid one) found, meaning no graphics associated.
3147 * Use the substitute one instead */
3148 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
3149 gfx = ats->grf_prop.subst_id;
3151 switch (gfx) {
3152 case APT_RADAR_GRASS_FENCE_SW:
3153 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
3154 break;
3155 case APT_GRASS_FENCE_NE_FLAG:
3156 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
3157 break;
3158 case APT_RADAR_FENCE_SW:
3159 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
3160 break;
3161 case APT_RADAR_FENCE_NE:
3162 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
3163 break;
3164 case APT_GRASS_FENCE_NE_FLAG_2:
3165 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
3166 break;
3170 Owner owner = GetTileOwner(ti->tile);
3172 PaletteID palette;
3173 if (Company::IsValidID(owner)) {
3174 palette = COMPANY_SPRITE_COLOUR(owner);
3175 } else {
3176 /* Some stations are not owner by a company, namely oil rigs */
3177 palette = PALETTE_TO_GREY;
3180 if (layout == nullptr && (t == nullptr || t->seq == nullptr)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
3182 /* don't show foundation for docks */
3183 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
3184 if (statspec != nullptr && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
3185 /* Station has custom foundations.
3186 * Check whether the foundation continues beyond the tile's upper sides. */
3187 uint edge_info = 0;
3188 auto [slope, z] = GetFoundationPixelSlope(ti->tile);
3189 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
3190 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
3191 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
3192 if (image == 0) goto draw_default_foundation;
3194 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
3195 /* Station provides extended foundations. */
3197 static const uint8_t foundation_parts[] = {
3198 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3199 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3200 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3201 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3204 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3205 } else {
3206 /* Draw simple foundations, built up from 8 possible foundation sprites. */
3208 /* Each set bit represents one of the eight composite sprites to be drawn.
3209 * 'Invalid' entries will not drawn but are included for completeness. */
3210 static const uint8_t composite_foundation_parts[] = {
3211 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
3212 0x00, 0xD1, 0xE4, 0xE0,
3213 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
3214 0xCA, 0xC9, 0xC4, 0xC0,
3215 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
3216 0xD2, 0x91, 0xE4, 0xA0,
3217 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
3218 0x4A, 0x09, 0x44
3221 uint8_t parts = composite_foundation_parts[ti->tileh];
3223 /* If foundations continue beyond the tile's upper sides then
3224 * mask out the last two pieces. */
3225 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
3226 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
3228 if (parts == 0) {
3229 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
3230 * correct offset for the childsprites.
3231 * So, draw the (completely empty) sprite of the default foundations. */
3232 goto draw_default_foundation;
3235 StartSpriteCombine();
3236 for (int i = 0; i < 8; i++) {
3237 if (HasBit(parts, i)) {
3238 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3241 EndSpriteCombine();
3244 OffsetGroundSprite(0, -8);
3245 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, ti->tileh);
3246 } else {
3247 draw_default_foundation:
3248 DrawFoundation(ti, FOUNDATION_LEVELED);
3252 bool draw_ground = false;
3254 if (IsBuoy(ti->tile)) {
3255 DrawWaterClassGround(ti);
3256 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
3257 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
3258 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
3259 if (ti->tileh == SLOPE_FLAT) {
3260 DrawWaterClassGround(ti);
3261 } else {
3262 assert(IsDock(ti->tile));
3263 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
3264 WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WATER_CLASS_INVALID;
3265 if (wc == WATER_CLASS_SEA) {
3266 DrawShoreTile(ti->tileh);
3267 } else {
3268 DrawClearLandTile(ti, 3);
3271 } else if (IsRoadWaypointTile(ti->tile)) {
3272 RoadBits bits = AxisToRoadBits(GetDriveThroughStopAxis(ti->tile));
3273 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3274 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3275 RoadBits road = (road_rt != INVALID_ROADTYPE) ? bits : ROAD_NONE;
3276 RoadBits tram = (tram_rt != INVALID_ROADTYPE) ? bits : ROAD_NONE;
3277 const RoadTypeInfo *road_rti = (road_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(road_rt) : nullptr;
3278 const RoadTypeInfo *tram_rti = (tram_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(tram_rt) : nullptr;
3280 if (ti->tileh != SLOPE_FLAT) {
3281 DrawFoundation(ti, FOUNDATION_LEVELED);
3284 DrawRoadGroundSprites(ti, road, tram, road_rti, tram_rti, GetRoadWaypointRoadside(ti->tile), IsRoadWaypointOnSnowOrDesert(ti->tile));
3285 } else {
3286 if (layout != nullptr) {
3287 /* Sprite layout which needs preprocessing */
3288 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
3289 uint32_t var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
3290 for (uint8_t var10 : SetBitIterator(var10_values)) {
3291 uint32_t var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
3292 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
3294 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
3295 t = &tmp_rail_layout;
3296 total_offset = 0;
3297 } else if (statspec != nullptr) {
3298 /* Simple sprite layout */
3299 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
3300 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
3301 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
3303 ground_relocation += rti->fallback_railtype;
3306 draw_ground = true;
3309 if (draw_ground && !IsAnyRoadStop(ti->tile)) {
3310 SpriteID image = t->ground.sprite;
3311 PaletteID pal = t->ground.pal;
3312 RailTrackOffset overlay_offset;
3313 if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3314 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
3315 DrawGroundSprite(image, PAL_NONE);
3316 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3318 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3319 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
3320 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3322 } else {
3323 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3324 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3325 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3327 /* PBS debugging, draw reserved tracks darker */
3328 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3329 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
3334 if (HasStationRail(ti->tile) && HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
3336 if (IsAnyRoadStop(ti->tile)) {
3337 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3338 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3339 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3340 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3342 StationGfx view = GetStationGfx(ti->tile);
3343 StationType type = GetStationType(ti->tile);
3345 const RoadStopSpec *stopspec = GetRoadStopSpec(ti->tile);
3346 RoadStopDrawMode stop_draw_mode{};
3347 if (stopspec != nullptr) {
3348 stop_draw_mode = stopspec->draw_mode;
3349 st = BaseStation::GetByTile(ti->tile);
3350 RoadStopResolverObject object(stopspec, st, ti->tile, INVALID_ROADTYPE, type, view);
3351 const SpriteGroup *group = object.Resolve();
3352 if (group != nullptr && group->type == SGT_TILELAYOUT) {
3353 if (HasBit(stopspec->flags, RSF_DRAW_MODE_REGISTER)) {
3354 stop_draw_mode = static_cast<RoadStopDrawMode>(GetRegister(0x100));
3356 if (type == STATION_ROADWAYPOINT && (stop_draw_mode & ROADSTOP_DRAW_MODE_WAYP_GROUND)) {
3357 draw_ground = true;
3359 t = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(nullptr);
3363 /* Draw ground sprite */
3364 if (draw_ground) {
3365 SpriteID image = t->ground.sprite;
3366 PaletteID pal = t->ground.pal;
3367 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3368 if (GB(image, 0, SPRITE_WIDTH) != 0) {
3369 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3370 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3374 if (IsDriveThroughStopTile(ti->tile)) {
3375 if (type != STATION_ROADWAYPOINT && (stopspec == nullptr || (stop_draw_mode & ROADSTOP_DRAW_MODE_OVERLAY) != 0)) {
3376 uint sprite_offset = GetDriveThroughStopAxis(ti->tile) == AXIS_X ? 1 : 0;
3377 DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3379 } else {
3380 /* Non-drivethrough road stops are only valid for roads. */
3381 assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3383 if ((stopspec == nullptr || (stop_draw_mode & ROADSTOP_DRAW_MODE_ROAD) != 0) && road_rti->UsesOverlay()) {
3384 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_ROADSTOP);
3385 DrawGroundSprite(ground + view, PAL_NONE);
3389 if (stopspec == nullptr || !HasBit(stopspec->flags, RSF_NO_CATENARY)) {
3390 /* Draw road, tram catenary */
3391 DrawRoadCatenary(ti);
3395 if (IsRailWaypoint(ti->tile)) {
3396 /* Don't offset the waypoint graphics; they're always the same. */
3397 total_offset = 0;
3400 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
3403 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3405 int32_t total_offset = 0;
3406 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3407 const DrawTileSprites *t = GetStationTileLayout(st, image);
3408 const RailTypeInfo *railtype_info = nullptr;
3410 if (railtype != INVALID_RAILTYPE) {
3411 railtype_info = GetRailTypeInfo(railtype);
3412 total_offset = railtype_info->GetRailtypeSpriteOffset();
3415 SpriteID img = t->ground.sprite;
3416 RailTrackOffset overlay_offset;
3417 if (railtype_info != nullptr && railtype_info->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3418 SpriteID ground = GetCustomRailSprite(railtype_info, INVALID_TILE, RTSG_GROUND);
3419 DrawSprite(img, PAL_NONE, x, y);
3420 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3421 } else {
3422 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3425 if (roadtype != INVALID_ROADTYPE) {
3426 const RoadTypeInfo *roadtype_info = GetRoadTypeInfo(roadtype);
3427 if (image >= 4) {
3428 /* Drive-through stop */
3429 uint sprite_offset = 5 - image;
3431 /* Road underlay takes precedence over tram */
3432 if (roadtype_info->UsesOverlay()) {
3433 SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_GROUND);
3434 DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3436 SpriteID overlay = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_OVERLAY);
3437 if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3438 } else if (RoadTypeIsTram(roadtype)) {
3439 DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3441 } else {
3442 /* Bay stop */
3443 if (RoadTypeIsRoad(roadtype) && roadtype_info->UsesOverlay()) {
3444 SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_ROADSTOP);
3445 DrawSprite(ground + image, PAL_NONE, x, y);
3450 /* Default waypoint has no railtype specific sprites */
3451 DrawRailTileSeqInGUI(x, y, t, (st == STATION_WAYPOINT || st == STATION_ROADWAYPOINT) ? 0 : total_offset, 0, pal);
3454 static int GetSlopePixelZ_Station(TileIndex tile, uint, uint, bool)
3456 return GetTileMaxPixelZ(tile);
3459 static Foundation GetFoundation_Station(TileIndex, Slope tileh)
3461 return FlatteningFoundation(tileh);
3464 static void FillTileDescRoadStop(TileIndex tile, TileDesc *td)
3466 RoadType road_rt = GetRoadTypeRoad(tile);
3467 RoadType tram_rt = GetRoadTypeTram(tile);
3468 Owner road_owner = INVALID_OWNER;
3469 Owner tram_owner = INVALID_OWNER;
3470 if (road_rt != INVALID_ROADTYPE) {
3471 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3472 td->roadtype = rti->strings.name;
3473 td->road_speed = rti->max_speed / 2;
3474 road_owner = GetRoadOwner(tile, RTT_ROAD);
3477 if (tram_rt != INVALID_ROADTYPE) {
3478 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3479 td->tramtype = rti->strings.name;
3480 td->tram_speed = rti->max_speed / 2;
3481 tram_owner = GetRoadOwner(tile, RTT_TRAM);
3484 if (IsDriveThroughStopTile(tile)) {
3485 /* Is there a mix of owners? */
3486 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3487 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3488 uint i = 1;
3489 if (road_owner != INVALID_OWNER) {
3490 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3491 td->owner[i] = road_owner;
3492 i++;
3494 if (tram_owner != INVALID_OWNER) {
3495 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3496 td->owner[i] = tram_owner;
3502 void FillTileDescRailStation(TileIndex tile, TileDesc *td)
3504 const StationSpec *spec = GetStationSpec(tile);
3506 if (spec != nullptr) {
3507 td->station_class = StationClass::Get(spec->class_index)->name;
3508 td->station_name = spec->name;
3510 if (spec->grf_prop.grffile != nullptr) {
3511 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3512 td->grf = gc->GetName();
3516 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3517 td->rail_speed = rti->max_speed;
3518 td->railtype = rti->strings.name;
3521 void FillTileDescAirport(TileIndex tile, TileDesc *td)
3523 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3524 td->airport_class = AirportClass::Get(as->class_index)->name;
3525 td->airport_name = as->name;
3527 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3528 td->airport_tile_name = ats->name;
3530 if (as->grf_prop.grffile != nullptr) {
3531 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3532 td->grf = gc->GetName();
3533 } else if (ats->grf_prop.grffile != nullptr) {
3534 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3535 td->grf = gc->GetName();
3539 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3541 td->owner[0] = GetTileOwner(tile);
3542 td->build_date = BaseStation::GetByTile(tile)->build_date;
3544 if (IsAnyRoadStop(tile)) FillTileDescRoadStop(tile, td);
3545 if (HasStationRail(tile)) FillTileDescRailStation(tile, td);
3546 if (IsAirport(tile)) FillTileDescAirport(tile, td);
3548 StringID str;
3549 switch (GetStationType(tile)) {
3550 default: NOT_REACHED();
3551 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3552 case STATION_AIRPORT:
3553 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3554 break;
3555 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3556 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3557 case STATION_OILRIG: {
3558 const Industry *i = Station::GetByTile(tile)->industry;
3559 const IndustrySpec *is = GetIndustrySpec(i->type);
3560 td->owner[0] = i->owner;
3561 str = is->name;
3562 if (is->grf_prop.grffile != nullptr) td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
3563 break;
3565 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3566 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3567 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3568 case STATION_ROADWAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3570 td->str = str;
3574 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3576 TrackBits trackbits = TRACK_BIT_NONE;
3578 switch (mode) {
3579 case TRANSPORT_RAIL:
3580 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3581 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3583 break;
3585 case TRANSPORT_WATER:
3586 /* buoy is coded as a station, it is always on open water */
3587 if (IsBuoy(tile)) {
3588 trackbits = TRACK_BIT_ALL;
3589 /* remove tracks that connect NE map edge */
3590 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3591 /* remove tracks that connect NW map edge */
3592 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3594 break;
3596 case TRANSPORT_ROAD:
3597 if (IsAnyRoadStop(tile)) {
3598 RoadTramType rtt = (RoadTramType)sub_mode;
3599 if (!HasTileRoadType(tile, rtt)) break;
3601 if (IsBayRoadStopTile(tile)) {
3602 DiagDirection dir = GetBayRoadStopDir(tile);
3603 if (side != INVALID_DIAGDIR && dir != side) break;
3604 trackbits = DiagDirToDiagTrackBits(dir);
3605 } else {
3606 Axis axis = GetDriveThroughStopAxis(tile);
3607 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
3608 trackbits = AxisToTrackBits(axis);
3611 break;
3613 default:
3614 break;
3617 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3621 static void TileLoop_Station(TileIndex tile)
3623 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3624 * hardcoded.....not good */
3625 switch (GetStationType(tile)) {
3626 case STATION_AIRPORT:
3627 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3628 break;
3630 case STATION_DOCK:
3631 if (!IsTileFlat(tile)) break; // only handle water part
3632 [[fallthrough]];
3634 case STATION_OILRIG: //(station part)
3635 case STATION_BUOY:
3636 TileLoop_Water(tile);
3637 break;
3639 case STATION_ROADWAYPOINT: {
3640 switch (_settings_game.game_creation.landscape) {
3641 case LT_ARCTIC:
3642 if (IsRoadWaypointOnSnowOrDesert(tile) != (GetTileZ(tile) > GetSnowLine())) {
3643 ToggleRoadWaypointOnSnowOrDesert(tile);
3644 MarkTileDirtyByTile(tile);
3646 break;
3648 case LT_TROPIC:
3649 if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsRoadWaypointOnSnowOrDesert(tile)) {
3650 ToggleRoadWaypointOnSnowOrDesert(tile);
3651 MarkTileDirtyByTile(tile);
3653 break;
3655 default: break;
3658 HouseZonesBits new_zone = HZB_TOWN_EDGE;
3659 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
3660 if (t != nullptr) {
3661 new_zone = GetTownRadiusGroup(t, tile);
3664 /* Adjust road ground type depending on 'new_zone' */
3665 Roadside new_rs = new_zone > HZB_TOWN_EDGE ? ROADSIDE_PAVED : ROADSIDE_GRASS;
3666 Roadside cur_rs = GetRoadWaypointRoadside(tile);
3668 if (new_rs != cur_rs) {
3669 SetRoadWaypointRoadside(tile, cur_rs == ROADSIDE_BARREN ? new_rs : ROADSIDE_BARREN);
3670 MarkTileDirtyByTile(tile);
3672 break;
3675 default: break;
3680 static void AnimateTile_Station(TileIndex tile)
3682 if (HasStationRail(tile)) {
3683 AnimateStationTile(tile);
3684 return;
3687 if (IsAirport(tile)) {
3688 AnimateAirportTile(tile);
3689 return;
3692 if (IsAnyRoadStopTile(tile)) {
3693 AnimateRoadStopTile(tile);
3694 return;
3699 static bool ClickTile_Station(TileIndex tile)
3701 const BaseStation *bst = BaseStation::GetByTile(tile);
3703 if (bst->facilities & FACIL_WAYPOINT) {
3704 ShowWaypointWindow(Waypoint::From(bst));
3705 } else if (IsHangar(tile)) {
3706 const Station *st = Station::From(bst);
3707 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3708 } else {
3709 ShowStationViewWindow(bst->index);
3711 return true;
3714 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3716 if (v->type == VEH_TRAIN) {
3717 StationID station_id = GetStationIndex(tile);
3718 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3719 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3721 int station_ahead;
3722 int station_length;
3723 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3725 /* Stop whenever that amount of station ahead + the distance from the
3726 * begin of the platform to the stop location is longer than the length
3727 * of the platform. Station ahead 'includes' the current tile where the
3728 * vehicle is on, so we need to subtract that. */
3729 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3731 DiagDirection dir = DirToDiagDir(v->direction);
3733 x &= 0xF;
3734 y &= 0xF;
3736 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3737 if (y == TILE_SIZE / 2) {
3738 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3739 stop &= TILE_SIZE - 1;
3741 if (x == stop) {
3742 return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3743 } else if (x < stop) {
3744 v->vehstatus |= VS_TRAIN_SLOWING;
3745 uint16_t spd = std::max(0, (stop - x) * 20 - 15);
3746 if (spd < v->cur_speed) v->cur_speed = spd;
3749 } else if (v->type == VEH_ROAD) {
3750 RoadVehicle *rv = RoadVehicle::From(v);
3751 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3752 if (IsStationRoadStop(tile) && rv->IsFrontEngine()) {
3753 /* Attempt to allocate a parking bay in a road stop */
3754 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
3759 return VETSB_CONTINUE;
3763 * Run the watched cargo callback for all houses in the catchment area.
3764 * @param st Station.
3766 void TriggerWatchedCargoCallbacks(Station *st)
3768 /* Collect cargoes accepted since the last big tick. */
3769 CargoTypes cargoes = 0;
3770 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3771 if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3774 /* Anything to do? */
3775 if (cargoes == 0) return;
3777 /* Loop over all houses in the catchment. */
3778 BitmapTileIterator it(st->catchment_tiles);
3779 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3780 if (IsTileType(tile, MP_HOUSE)) {
3781 WatchedCargoCallback(tile, cargoes);
3787 * This function is called for each station once every 250 ticks.
3788 * Not all stations will get the tick at the same time.
3789 * @param st the station receiving the tick.
3790 * @return true if the station is still valid (wasn't deleted)
3792 static bool StationHandleBigTick(BaseStation *st)
3794 if (!st->IsInUse()) {
3795 if (++st->delete_ctr >= 8) delete st;
3796 return false;
3799 if (Station::IsExpected(st)) {
3800 TriggerWatchedCargoCallbacks(Station::From(st));
3802 for (GoodsEntry &ge : Station::From(st)->goods) {
3803 ClrBit(ge.status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3808 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3810 return true;
3813 static inline void byte_inc_sat(uint8_t *p)
3815 uint8_t b = *p + 1;
3816 if (b != 0) *p = b;
3820 * Truncate the cargo by a specific amount.
3821 * @param cs The type of cargo to perform the truncation for.
3822 * @param ge The goods entry, of the station, to truncate.
3823 * @param amount The amount to truncate the cargo by.
3825 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3827 /* If truncating also punish the source stations' ratings to
3828 * decrease the flow of incoming cargo. */
3830 StationCargoAmountMap waiting_per_source;
3831 ge->cargo.Truncate(amount, &waiting_per_source);
3832 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3833 Station *source_station = Station::GetIfValid(i->first);
3834 if (source_station == nullptr) continue;
3836 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3837 source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3841 static void UpdateStationRating(Station *st)
3843 bool waiting_changed = false;
3845 byte_inc_sat(&st->time_since_load);
3846 byte_inc_sat(&st->time_since_unload);
3848 for (const CargoSpec *cs : CargoSpec::Iterate()) {
3849 GoodsEntry *ge = &st->goods[cs->Index()];
3850 /* Slowly increase the rating back to its original level in the case we
3851 * didn't deliver cargo yet to this station. This happens when a bribe
3852 * failed while you didn't moved that cargo yet to a station. */
3853 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3854 ge->rating++;
3857 /* Only change the rating if we are moving this cargo */
3858 if (ge->HasRating()) {
3859 byte_inc_sat(&ge->time_since_pickup);
3860 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3861 ClrBit(ge->status, GoodsEntry::GES_RATING);
3862 ge->last_speed = 0;
3863 TruncateCargo(cs, ge);
3864 waiting_changed = true;
3865 continue;
3868 bool skip = false;
3869 int rating = 0;
3870 uint waiting = ge->cargo.AvailableCount();
3872 /* num_dests is at least 1 if there is any cargo as
3873 * INVALID_STATION is also a destination.
3875 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3877 /* Average amount of cargo per next hop, but prefer solitary stations
3878 * with only one or two next hops. They are allowed to have more
3879 * cargo waiting per next hop.
3880 * With manual cargo distribution waiting_avg = waiting / 2 as then
3881 * INVALID_STATION is the only destination.
3883 uint waiting_avg = waiting / (num_dests + 1);
3885 if (_cheats.station_rating.value) {
3886 ge->rating = rating = MAX_STATION_RATING;
3887 skip = true;
3888 } else if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3889 /* Perform custom station rating. If it succeeds the speed, days in transit and
3890 * waiting cargo ratings must not be executed. */
3892 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3893 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3895 uint32_t var18 = ClampTo<uint8_t>(ge->time_since_pickup)
3896 | (ClampTo<uint16_t>(ge->max_waiting_cargo) << 8)
3897 | (ClampTo<uint8_t>(last_speed) << 24);
3898 /* Convert to the 'old' vehicle types */
3899 uint32_t var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3900 uint16_t callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3901 if (callback != CALLBACK_FAILED) {
3902 skip = true;
3903 rating = GB(callback, 0, 14);
3905 /* Simulate a 15 bit signed value */
3906 if (HasBit(callback, 14)) rating -= 0x4000;
3910 if (!skip) {
3911 int b = ge->last_speed - 85;
3912 if (b >= 0) rating += b >> 2;
3914 uint8_t waittime = ge->time_since_pickup;
3915 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3916 if (waittime <= 21) rating += 25;
3917 if (waittime <= 12) rating += 25;
3918 if (waittime <= 6) rating += 45;
3919 if (waittime <= 3) rating += 35;
3921 rating -= 90;
3922 if (ge->max_waiting_cargo <= 1500) rating += 55;
3923 if (ge->max_waiting_cargo <= 1000) rating += 35;
3924 if (ge->max_waiting_cargo <= 600) rating += 10;
3925 if (ge->max_waiting_cargo <= 300) rating += 20;
3926 if (ge->max_waiting_cargo <= 100) rating += 10;
3929 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3931 uint8_t age = ge->last_age;
3932 if (age < 3) rating += 10;
3933 if (age < 2) rating += 10;
3934 if (age < 1) rating += 13;
3937 int or_ = ge->rating; // old rating
3939 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3940 ge->rating = rating = or_ + Clamp(ClampTo<uint8_t>(rating) - or_, -2, 2);
3942 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3943 * remove some random amount of goods from the station */
3944 if (rating <= 64 && waiting_avg >= 100) {
3945 int dec = Random() & 0x1F;
3946 if (waiting_avg < 200) dec &= 7;
3947 waiting -= (dec + 1) * num_dests;
3948 waiting_changed = true;
3951 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3952 if (rating <= 127 && waiting != 0) {
3953 uint32_t r = Random();
3954 if (rating <= (int)GB(r, 0, 7)) {
3955 /* Need to have int, otherwise it will just overflow etc. */
3956 waiting = std::max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3957 waiting_changed = true;
3961 /* At some point we really must cap the cargo. Previously this
3962 * was a strict 4095, but now we'll have a less strict, but
3963 * increasingly aggressive truncation of the amount of cargo. */
3964 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3965 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3966 static const uint MAX_WAITING_CARGO = 1 << 15;
3968 if (waiting > WAITING_CARGO_THRESHOLD) {
3969 uint difference = waiting - WAITING_CARGO_THRESHOLD;
3970 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3972 waiting = std::min(waiting, MAX_WAITING_CARGO);
3973 waiting_changed = true;
3976 /* We can't truncate cargo that's already reserved for loading.
3977 * Thus StoredCount() here. */
3978 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3979 /* Feed back the exact own waiting cargo at this station for the
3980 * next rating calculation. */
3981 ge->max_waiting_cargo = 0;
3983 TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3984 } else {
3985 /* If the average number per next hop is low, be more forgiving. */
3986 ge->max_waiting_cargo = waiting_avg;
3992 StationID index = st->index;
3993 if (waiting_changed) {
3994 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3995 } else {
3996 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
4001 * Reroute cargo of type c at station st or in any vehicles unloading there.
4002 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
4003 * @param st Station to be rerouted at.
4004 * @param c Type of cargo.
4005 * @param avoid Original next hop of cargo, avoid this.
4006 * @param avoid2 Another station to be avoided when rerouting.
4008 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
4010 GoodsEntry &ge = st->goods[c];
4012 /* Reroute cargo in station. */
4013 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
4015 /* Reroute cargo staged to be transferred. */
4016 for (Vehicle *v : st->loading_vehicles) {
4017 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
4018 if (u->cargo_type != c) continue;
4019 u->cargo.Reroute(UINT_MAX, &u->cargo, avoid, avoid2, &ge);
4025 * Check all next hops of cargo packets in this station for existence of a
4026 * a valid link they may use to travel on. Reroute any cargo not having a valid
4027 * link and remove timed out links found like this from the linkgraph. We're
4028 * not all links here as that is expensive and useless. A link no one is using
4029 * doesn't hurt either.
4030 * @param from Station to check.
4032 void DeleteStaleLinks(Station *from)
4034 for (CargoID c = 0; c < NUM_CARGO; ++c) {
4035 const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
4036 GoodsEntry &ge = from->goods[c];
4037 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
4038 if (lg == nullptr) continue;
4039 std::vector<NodeID> to_remove{};
4040 for (Edge &edge : (*lg)[ge.node].edges) {
4041 Station *to = Station::Get((*lg)[edge.dest_node].station);
4042 assert(to->goods[c].node == edge.dest_node);
4043 assert(TimerGameEconomy::date >= edge.LastUpdate());
4044 auto timeout = TimerGameEconomy::Date(LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3));
4045 if (TimerGameEconomy::date - edge.LastUpdate() > timeout) {
4046 bool updated = false;
4048 if (auto_distributed) {
4049 /* Have all vehicles refresh their next hops before deciding to
4050 * remove the node. */
4051 std::vector<Vehicle *> vehicles;
4052 for (OrderList *l : OrderList::Iterate()) {
4053 bool found_from = false;
4054 bool found_to = false;
4055 for (Order *order = l->GetFirstOrder(); order != nullptr; order = order->next) {
4056 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
4057 if (order->GetDestination() == from->index) {
4058 found_from = true;
4059 if (found_to) break;
4060 } else if (order->GetDestination() == to->index) {
4061 found_to = true;
4062 if (found_from) break;
4065 if (!found_to || !found_from) continue;
4066 vehicles.push_back(l->GetFirstSharedVehicle());
4069 auto iter = vehicles.begin();
4070 while (iter != vehicles.end()) {
4071 Vehicle *v = *iter;
4072 /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
4073 if (!v->IsStoppedInDepot() || TimerGameEconomy::date - v->date_of_last_service <= LinkGraph::STALE_LINK_DEPOT_TIMEOUT) {
4074 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
4076 if (edge.LastUpdate() == TimerGameEconomy::date) {
4077 updated = true;
4078 break;
4081 Vehicle *next_shared = v->NextShared();
4082 if (next_shared) {
4083 *iter = next_shared;
4084 ++iter;
4085 } else {
4086 iter = vehicles.erase(iter);
4089 if (iter == vehicles.end()) iter = vehicles.begin();
4093 if (!updated) {
4094 /* If it's still considered dead remove it. */
4095 to_remove.emplace_back(to->goods[c].node);
4096 ge.flows.DeleteFlows(to->index);
4097 RerouteCargo(from, c, to->index, from->index);
4099 } else if (edge.last_unrestricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_unrestricted_update > timeout) {
4100 edge.Restrict();
4101 ge.flows.RestrictFlows(to->index);
4102 RerouteCargo(from, c, to->index, from->index);
4103 } else if (edge.last_restricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_restricted_update > timeout) {
4104 edge.Release();
4107 /* Remove dead edges. */
4108 for (NodeID r : to_remove) (*lg)[ge.node].RemoveEdge(r);
4110 assert(TimerGameEconomy::date >= lg->LastCompression());
4111 if (TimerGameEconomy::date - lg->LastCompression() > LinkGraph::COMPRESSION_INTERVAL) {
4112 lg->Compress();
4118 * Increase capacity for a link stat given by station cargo and next hop.
4119 * @param st Station to get the link stats from.
4120 * @param cargo Cargo to increase stat for.
4121 * @param next_station_id Station the consist will be travelling to next.
4122 * @param capacity Capacity to add to link stat.
4123 * @param usage Usage to add to link stat.
4124 * @param mode Update mode to be applied.
4126 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateMode mode)
4128 GoodsEntry &ge1 = st->goods[cargo];
4129 Station *st2 = Station::Get(next_station_id);
4130 GoodsEntry &ge2 = st2->goods[cargo];
4131 LinkGraph *lg = nullptr;
4132 if (ge1.link_graph == INVALID_LINK_GRAPH) {
4133 if (ge2.link_graph == INVALID_LINK_GRAPH) {
4134 if (LinkGraph::CanAllocateItem()) {
4135 lg = new LinkGraph(cargo);
4136 LinkGraphSchedule::instance.Queue(lg);
4137 ge2.link_graph = lg->index;
4138 ge2.node = lg->AddNode(st2);
4139 } else {
4140 Debug(misc, 0, "Can't allocate link graph");
4142 } else {
4143 lg = LinkGraph::Get(ge2.link_graph);
4145 if (lg) {
4146 ge1.link_graph = lg->index;
4147 ge1.node = lg->AddNode(st);
4149 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
4150 lg = LinkGraph::Get(ge1.link_graph);
4151 ge2.link_graph = lg->index;
4152 ge2.node = lg->AddNode(st2);
4153 } else {
4154 lg = LinkGraph::Get(ge1.link_graph);
4155 if (ge1.link_graph != ge2.link_graph) {
4156 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
4157 if (lg->Size() < lg2->Size()) {
4158 LinkGraphSchedule::instance.Unqueue(lg);
4159 lg2->Merge(lg); // Updates GoodsEntries of lg
4160 lg = lg2;
4161 } else {
4162 LinkGraphSchedule::instance.Unqueue(lg2);
4163 lg->Merge(lg2); // Updates GoodsEntries of lg2
4167 if (lg != nullptr) {
4168 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, mode);
4173 * Increase capacity for all link stats associated with vehicles in the given consist.
4174 * @param st Station to get the link stats from.
4175 * @param front First vehicle in the consist.
4176 * @param next_station_id Station the consist will be travelling to next.
4178 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32_t time)
4180 for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
4181 if (v->refit_cap > 0) {
4182 /* The cargo count can indeed be higher than the refit_cap if
4183 * wagons have been auto-replaced and subsequently auto-
4184 * refitted to a higher capacity. The cargo gets redistributed
4185 * among the wagons in that case.
4186 * As usage is not such an important figure anyway we just
4187 * ignore the additional cargo then.*/
4188 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
4189 std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EUM_INCREASE);
4194 /* called for every station each tick */
4195 static void StationHandleSmallTick(BaseStation *st)
4197 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
4199 uint8_t b = st->delete_ctr + 1;
4200 if (b >= Ticks::STATION_RATING_TICKS) b = 0;
4201 st->delete_ctr = b;
4203 if (b == 0) UpdateStationRating(Station::From(st));
4206 void OnTick_Station()
4208 if (_game_mode == GM_EDITOR) return;
4210 for (BaseStation *st : BaseStation::Iterate()) {
4211 StationHandleSmallTick(st);
4213 /* Clean up the link graph about once a week. */
4214 if (Station::IsExpected(st) && (TimerGameTick::counter + st->index) % Ticks::STATION_LINKGRAPH_TICKS == 0) {
4215 DeleteStaleLinks(Station::From(st));
4218 /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */
4219 if ((TimerGameTick::counter + st->index) % Ticks::STATION_ACCEPTANCE_TICKS == 0) {
4220 /* Stop processing this station if it was deleted */
4221 if (!StationHandleBigTick(st)) continue;
4224 /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */
4225 if ((TimerGameTick::counter + st->index) % Ticks::STATION_ACCEPTANCE_TICKS == 0) {
4226 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
4227 TriggerRoadStopAnimation(st, st->xy, SAT_250_TICKS);
4228 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
4233 /** Economy monthly loop for stations. */
4234 static IntervalTimer<TimerGameEconomy> _economy_stations_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::STATION}, [](auto)
4236 for (Station *st : Station::Iterate()) {
4237 for (GoodsEntry &ge : st->goods) {
4238 SB(ge.status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge.status, GoodsEntry::GES_CURRENT_MONTH, 1));
4239 ClrBit(ge.status, GoodsEntry::GES_CURRENT_MONTH);
4244 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
4246 ForAllStationsRadius(tile, radius, [&](Station *st) {
4247 if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
4248 for (GoodsEntry &ge : st->goods) {
4249 if (ge.status != 0) {
4250 ge.rating = ClampTo<uint8_t>(ge.rating + amount);
4257 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
4259 /* We can't allocate a CargoPacket? Then don't do anything
4260 * at all; i.e. just discard the incoming cargo. */
4261 if (!CargoPacket::CanAllocateItem()) return 0;
4263 GoodsEntry &ge = st->goods[type];
4264 amount += ge.amount_fract;
4265 ge.amount_fract = GB(amount, 0, 8);
4267 amount >>= 8;
4268 /* No new "real" cargo item yet. */
4269 if (amount == 0) return 0;
4271 StationID next = ge.GetVia(st->index);
4272 ge.cargo.Append(new CargoPacket(st->index, amount, source_type, source_id), next);
4273 LinkGraph *lg = nullptr;
4274 if (ge.link_graph == INVALID_LINK_GRAPH) {
4275 if (LinkGraph::CanAllocateItem()) {
4276 lg = new LinkGraph(type);
4277 LinkGraphSchedule::instance.Queue(lg);
4278 ge.link_graph = lg->index;
4279 ge.node = lg->AddNode(st);
4280 } else {
4281 Debug(misc, 0, "Can't allocate link graph");
4283 } else {
4284 lg = LinkGraph::Get(ge.link_graph);
4286 if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
4288 if (!ge.HasRating()) {
4289 InvalidateWindowData(WC_STATION_LIST, st->owner);
4290 SetBit(ge.status, GoodsEntry::GES_RATING);
4293 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
4294 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
4295 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
4296 TriggerRoadStopRandomisation(st, st->xy, RSRT_NEW_CARGO, type);
4297 TriggerRoadStopAnimation(st, st->xy, SAT_NEW_CARGO, type);
4300 SetWindowDirty(WC_STATION_VIEW, st->index);
4301 st->MarkTilesDirty(true);
4302 return amount;
4305 static bool IsUniqueStationName(const std::string &name)
4307 for (const Station *st : Station::Iterate()) {
4308 if (!st->name.empty() && st->name == name) return false;
4311 return true;
4315 * Rename a station
4316 * @param flags operation to perform
4317 * @param station_id station ID that is to be renamed
4318 * @param text the new name or an empty string when resetting to the default
4319 * @return the cost of this operation or an error
4321 CommandCost CmdRenameStation(DoCommandFlag flags, StationID station_id, const std::string &text)
4323 Station *st = Station::GetIfValid(station_id);
4324 if (st == nullptr) return CMD_ERROR;
4326 CommandCost ret = CheckOwnership(st->owner);
4327 if (ret.Failed()) return ret;
4329 bool reset = text.empty();
4331 if (!reset) {
4332 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
4333 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
4336 if (flags & DC_EXEC) {
4337 st->cached_name.clear();
4338 if (reset) {
4339 st->name.clear();
4340 } else {
4341 st->name = text;
4344 st->UpdateVirtCoord();
4345 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
4348 return CommandCost();
4351 static void AddNearbyStationsByCatchment(TileIndex tile, StationList *stations, StationList &nearby)
4353 for (Station *st : nearby) {
4354 if (st->TileIsInCatchment(tile)) stations->insert(st);
4359 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
4360 * @return pointer to a StationList containing all stations found
4362 const StationList *StationFinder::GetStations()
4364 if (this->tile != INVALID_TILE) {
4365 if (IsTileType(this->tile, MP_HOUSE)) {
4366 /* Town nearby stations need to be filtered per tile. */
4367 assert(this->w == 1 && this->h == 1);
4368 AddNearbyStationsByCatchment(this->tile, &this->stations, Town::GetByTile(this->tile)->stations_near);
4369 } else {
4370 ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex) {
4371 this->stations.insert(st);
4372 return true;
4375 this->tile = INVALID_TILE;
4377 return &this->stations;
4381 static bool CanMoveGoodsToStation(const Station *st, CargoID type)
4383 /* Is the station reserved exclusively for somebody else? */
4384 if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
4386 /* Lowest possible rating, better not to give cargo anymore. */
4387 if (st->goods[type].rating == 0) return false;
4389 /* Selectively servicing stations, and not this one. */
4390 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) return false;
4392 if (IsCargoInClass(type, CC_PASSENGERS)) {
4393 /* Passengers are never served by just a truck stop. */
4394 if (st->facilities == FACIL_TRUCK_STOP) return false;
4395 } else {
4396 /* Non-passengers are never served by just a bus stop. */
4397 if (st->facilities == FACIL_BUS_STOP) return false;
4399 return true;
4402 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations, Owner exclusivity)
4404 /* Return if nothing to do. Also the rounding below fails for 0. */
4405 if (all_stations->empty()) return 0;
4406 if (amount == 0) return 0;
4408 Station *first_station = nullptr;
4409 typedef std::pair<Station *, uint> StationInfo;
4410 std::vector<StationInfo> used_stations;
4412 for (Station *st : *all_stations) {
4413 if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4414 if (!CanMoveGoodsToStation(st, type)) continue;
4416 /* Avoid allocating a vector if there is only one station to significantly
4417 * improve performance in this common case. */
4418 if (first_station == nullptr) {
4419 first_station = st;
4420 continue;
4422 if (used_stations.empty()) {
4423 used_stations.reserve(2);
4424 used_stations.emplace_back(first_station, 0);
4426 used_stations.emplace_back(st, 0);
4429 /* no stations around at all? */
4430 if (first_station == nullptr) return 0;
4432 if (used_stations.empty()) {
4433 /* only one station around */
4434 amount *= first_station->goods[type].rating + 1;
4435 return UpdateStationWaiting(first_station, type, amount, source_type, source_id);
4438 uint company_best[OWNER_NONE + 1] = {}; // best rating for each company, including OWNER_NONE
4439 uint company_sum[OWNER_NONE + 1] = {}; // sum of ratings for each company
4440 uint best_rating = 0;
4441 uint best_sum = 0; // sum of best ratings for each company
4443 for (auto &p : used_stations) {
4444 auto owner = p.first->owner;
4445 auto rating = p.first->goods[type].rating;
4446 if (rating > company_best[owner]) {
4447 best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
4448 company_best[owner] = rating;
4449 if (rating > best_rating) best_rating = rating;
4451 company_sum[owner] += rating;
4454 /* From now we'll calculate with fractional cargo amounts.
4455 * First determine how much cargo we really have. */
4456 amount *= best_rating + 1;
4458 uint moving = 0;
4459 for (auto &p : used_stations) {
4460 uint owner = p.first->owner;
4461 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4462 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4463 p.second = amount * company_best[owner] * p.first->goods[type].rating / best_sum / company_sum[owner];
4464 moving += p.second;
4467 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4468 if (amount > moving) {
4469 std::stable_sort(used_stations.begin(), used_stations.end(), [type](const StationInfo &a, const StationInfo &b) {
4470 return b.first->goods[type].rating < a.first->goods[type].rating;
4473 assert(amount - moving <= used_stations.size());
4474 for (uint i = 0; i < amount - moving; i++) {
4475 used_stations[i].second++;
4479 uint moved = 0;
4480 for (auto &p : used_stations) {
4481 moved += UpdateStationWaiting(p.first, type, p.second, source_type, source_id);
4484 return moved;
4487 void UpdateStationDockingTiles(Station *st)
4489 st->docking_station.Clear();
4491 /* For neutral stations, start with the industry area instead of dock area */
4492 const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4494 if (area->tile == INVALID_TILE) return;
4496 int x = TileX(area->tile);
4497 int y = TileY(area->tile);
4499 /* Expand the area by a tile on each side while
4500 * making sure that we remain inside the map. */
4501 int x2 = std::min<int>(x + area->w + 1, Map::SizeX());
4502 int x1 = std::max<int>(x - 1, 0);
4504 int y2 = std::min<int>(y + area->h + 1, Map::SizeY());
4505 int y1 = std::max<int>(y - 1, 0);
4507 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4508 for (TileIndex tile : ta) {
4509 if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4513 void BuildOilRig(TileIndex tile)
4515 if (!Station::CanAllocateItem()) {
4516 Debug(misc, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4517 return;
4520 Station *st = new Station(tile);
4521 _station_kdtree.Insert(st->index);
4522 st->town = ClosestTownFromTile(tile, UINT_MAX);
4524 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
4526 assert(IsTileType(tile, MP_INDUSTRY));
4527 /* Mark industry as associated both ways */
4528 st->industry = Industry::GetByTile(tile);
4529 st->industry->neutral_station = st;
4530 DeleteAnimatedTile(tile);
4531 MakeOilrig(tile, st->index, GetWaterClass(tile));
4533 st->owner = OWNER_NONE;
4534 st->airport.type = AT_OILRIG;
4535 st->airport.Add(tile);
4536 st->ship_station.Add(tile);
4537 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
4538 st->build_date = TimerGameCalendar::date;
4539 UpdateStationDockingTiles(st);
4541 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
4543 st->UpdateVirtCoord();
4545 /* An industry tile has now been replaced with a station tile, this may change the overlap between station catchments and industry tiles.
4546 * Recalculate the station catchment for all stations currently in the industry's nearby list.
4547 * Clear the industry's station nearby list first because Station::RecomputeCatchment cannot remove nearby industries in this case. */
4548 if (_settings_game.station.serve_neutral_industries) {
4549 StationList nearby = std::move(st->industry->stations_near);
4550 st->industry->stations_near.clear();
4551 for (Station *near : nearby) {
4552 near->RecomputeCatchment(true);
4553 UpdateStationAcceptance(near, true);
4557 st->RecomputeCatchment();
4558 UpdateStationAcceptance(st, false);
4561 void DeleteOilRig(TileIndex tile)
4563 Station *st = Station::GetByTile(tile);
4565 MakeWaterKeepingClass(tile, OWNER_NONE);
4567 /* The oil rig station is not supposed to be shared with anything else */
4568 assert(st->facilities == (FACIL_AIRPORT | FACIL_DOCK) && st->airport.type == AT_OILRIG);
4569 if (st->industry != nullptr && st->industry->neutral_station == st) {
4570 /* Don't leave dangling neutral station pointer */
4571 st->industry->neutral_station = nullptr;
4573 delete st;
4576 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4578 if (IsAnyRoadStopTile(tile)) {
4579 for (RoadTramType rtt : _roadtramtypes) {
4580 /* Update all roadtypes, no matter if they are present */
4581 if (GetRoadOwner(tile, rtt) == old_owner) {
4582 RoadType rt = GetRoadType(tile, rtt);
4583 if (rt != INVALID_ROADTYPE) {
4584 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4585 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4586 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4588 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4593 if (!IsTileOwner(tile, old_owner)) return;
4595 if (new_owner != INVALID_OWNER) {
4596 /* Update company infrastructure counts. Only do it here
4597 * if the new owner is valid as otherwise the clear
4598 * command will do it for us. No need to dirty windows
4599 * here, we'll redraw the whole screen anyway.*/
4600 Company *old_company = Company::Get(old_owner);
4601 Company *new_company = Company::Get(new_owner);
4603 /* Update counts for underlying infrastructure. */
4604 switch (GetStationType(tile)) {
4605 case STATION_RAIL:
4606 case STATION_WAYPOINT:
4607 if (!IsStationTileBlocked(tile)) {
4608 old_company->infrastructure.rail[GetRailType(tile)]--;
4609 new_company->infrastructure.rail[GetRailType(tile)]++;
4611 break;
4613 case STATION_BUS:
4614 case STATION_TRUCK:
4615 case STATION_ROADWAYPOINT:
4616 /* Road stops were already handled above. */
4617 break;
4619 case STATION_BUOY:
4620 case STATION_DOCK:
4621 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
4622 old_company->infrastructure.water--;
4623 new_company->infrastructure.water++;
4625 break;
4627 default:
4628 break;
4631 /* Update station tile count. */
4632 if (!IsBuoy(tile) && !IsAirport(tile)) {
4633 old_company->infrastructure.station--;
4634 new_company->infrastructure.station++;
4637 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4638 SetTileOwner(tile, new_owner);
4639 InvalidateWindowClassesData(WC_STATION_LIST, 0);
4640 } else {
4641 if (IsDriveThroughStopTile(tile)) {
4642 /* Remove the drive-through road stop */
4643 if (IsRoadWaypoint(tile)) {
4644 Command<CMD_REMOVE_FROM_ROAD_WAYPOINT>::Do(DC_EXEC | DC_BANKRUPT, tile, tile);
4645 } else {
4646 Command<CMD_REMOVE_ROAD_STOP>::Do(DC_EXEC | DC_BANKRUPT, tile, 1, 1, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, false);
4648 assert(IsTileType(tile, MP_ROAD));
4649 /* Change owner of tile and all roadtypes */
4650 ChangeTileOwner(tile, old_owner, new_owner);
4651 } else {
4652 Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_BANKRUPT, tile);
4653 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4654 * Update owner of buoy if it was not removed (was in orders).
4655 * Do not update when owned by OWNER_WATER (sea and rivers). */
4656 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4662 * Check if a drive-through road stop tile can be cleared.
4663 * Road stops built on town-owned roads check the conditions
4664 * that would allow clearing of the original road.
4665 * @param tile The road stop tile to check.
4666 * @param flags Command flags.
4667 * @return A succeeded command if the road can be removed, a failed command with the relevant error message otherwise.
4669 static CommandCost CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
4671 /* Water flooding can always clear road stops. */
4672 if (_current_company == OWNER_WATER) return CommandCost();
4674 CommandCost ret;
4676 if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4677 Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
4678 if (tram_owner != OWNER_NONE) {
4679 ret = CheckOwnership(tram_owner);
4680 if (ret.Failed()) return ret;
4684 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4685 Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
4686 if (road_owner == OWNER_TOWN) {
4687 ret = CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, RTT_ROAD), OWNER_TOWN, RTT_ROAD, flags);
4688 if (ret.Failed()) return ret;
4689 } else if (road_owner != OWNER_NONE) {
4690 ret = CheckOwnership(road_owner);
4691 if (ret.Failed()) return ret;
4695 return CommandCost();
4699 * Clear a single tile of a station.
4700 * @param tile The tile to clear.
4701 * @param flags The DoCommand flags related to the "command".
4702 * @return The cost, or error of clearing.
4704 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4706 if (flags & DC_AUTO) {
4707 switch (GetStationType(tile)) {
4708 default: break;
4709 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4710 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4711 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4712 case STATION_TRUCK: return_cmd_error(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4713 case STATION_BUS: return_cmd_error(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4714 case STATION_ROADWAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4715 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4716 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4717 case STATION_OILRIG:
4718 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4719 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4723 switch (GetStationType(tile)) {
4724 case STATION_RAIL: return RemoveRailStation(tile, flags);
4725 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4726 case STATION_AIRPORT: return RemoveAirport(tile, flags);
4727 case STATION_TRUCK: [[fallthrough]];
4728 case STATION_BUS:
4729 if (IsDriveThroughStopTile(tile)) {
4730 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4731 if (remove_road.Failed()) return remove_road;
4733 return RemoveRoadStop(tile, flags);
4734 case STATION_ROADWAYPOINT: {
4735 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4736 if (remove_road.Failed()) return remove_road;
4737 return RemoveRoadWaypointStop(tile, flags);
4739 case STATION_BUOY: return RemoveBuoy(tile, flags);
4740 case STATION_DOCK: return RemoveDock(tile, flags);
4741 default: break;
4744 return CMD_ERROR;
4747 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4749 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4750 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4751 * TTDP does not call it.
4753 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4754 switch (GetStationType(tile)) {
4755 case STATION_WAYPOINT:
4756 case STATION_RAIL: {
4757 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetRailStationAxis(tile))) break;
4758 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4761 case STATION_AIRPORT:
4762 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4764 case STATION_TRUCK:
4765 case STATION_BUS:
4766 case STATION_ROADWAYPOINT: {
4767 if (IsDriveThroughStopTile(tile)) {
4768 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetDriveThroughStopAxis(tile))) break;
4769 } else {
4770 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetBayRoadStopDir(tile))) break;
4772 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4775 default: break;
4779 return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
4783 * Get flow for a station.
4784 * @param st Station to get flow for.
4785 * @return Flow for st.
4787 uint FlowStat::GetShare(StationID st) const
4789 uint32_t prev = 0;
4790 for (const auto &it : this->shares) {
4791 if (it.second == st) {
4792 return it.first - prev;
4793 } else {
4794 prev = it.first;
4797 return 0;
4801 * Get a station a package can be routed to, but exclude the given ones.
4802 * @param excluded StationID not to be selected.
4803 * @param excluded2 Another StationID not to be selected.
4804 * @return A station ID from the shares map.
4806 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4808 if (this->unrestricted == 0) return INVALID_STATION;
4809 assert(!this->shares.empty());
4810 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4811 assert(it != this->shares.end() && it->first <= this->unrestricted);
4812 if (it->second != excluded && it->second != excluded2) return it->second;
4814 /* We've hit one of the excluded stations.
4815 * Draw another share, from outside its range. */
4817 uint end = it->first;
4818 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4819 uint interval = end - begin;
4820 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4821 uint new_max = this->unrestricted - interval;
4822 uint rand = RandomRange(new_max);
4823 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4824 this->shares.upper_bound(rand + interval);
4825 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4826 if (it2->second != excluded && it2->second != excluded2) return it2->second;
4828 /* We've hit the second excluded station.
4829 * Same as before, only a bit more complicated. */
4831 uint end2 = it2->first;
4832 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4833 uint interval2 = end2 - begin2;
4834 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4835 new_max -= interval2;
4836 if (begin > begin2) {
4837 Swap(begin, begin2);
4838 Swap(end, end2);
4839 Swap(interval, interval2);
4841 rand = RandomRange(new_max);
4842 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4843 if (rand < begin) {
4844 it3 = this->shares.upper_bound(rand);
4845 } else if (rand < begin2 - interval) {
4846 it3 = this->shares.upper_bound(rand + interval);
4847 } else {
4848 it3 = this->shares.upper_bound(rand + interval + interval2);
4850 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4851 return it3->second;
4855 * Reduce all flows to minimum capacity so that they don't get in the way of
4856 * link usage statistics too much. Keep them around, though, to continue
4857 * routing any remaining cargo.
4859 void FlowStat::Invalidate()
4861 assert(!this->shares.empty());
4862 SharesMap new_shares;
4863 uint i = 0;
4864 for (const auto &it : this->shares) {
4865 new_shares[++i] = it.second;
4866 if (it.first == this->unrestricted) this->unrestricted = i;
4868 this->shares.swap(new_shares);
4869 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4873 * Change share for specified station. By specifying INT_MIN as parameter you
4874 * can erase a share. Newly added flows will be unrestricted.
4875 * @param st Next Hop to be removed.
4876 * @param flow Share to be added or removed.
4878 void FlowStat::ChangeShare(StationID st, int flow)
4880 /* We assert only before changing as afterwards the shares can actually
4881 * be empty. In that case the whole flow stat must be deleted then. */
4882 assert(!this->shares.empty());
4884 uint removed_shares = 0;
4885 uint added_shares = 0;
4886 uint last_share = 0;
4887 SharesMap new_shares;
4888 for (const auto &it : this->shares) {
4889 if (it.second == st) {
4890 if (flow < 0) {
4891 uint share = it.first - last_share;
4892 if (flow == INT_MIN || (uint)(-flow) >= share) {
4893 removed_shares += share;
4894 if (it.first <= this->unrestricted) this->unrestricted -= share;
4895 if (flow != INT_MIN) flow += share;
4896 last_share = it.first;
4897 continue; // remove the whole share
4899 removed_shares += (uint)(-flow);
4900 } else {
4901 added_shares += (uint)(flow);
4903 if (it.first <= this->unrestricted) this->unrestricted += flow;
4905 /* If we don't continue above the whole flow has been added or
4906 * removed. */
4907 flow = 0;
4909 new_shares[it.first + added_shares - removed_shares] = it.second;
4910 last_share = it.first;
4912 if (flow > 0) {
4913 new_shares[last_share + (uint)flow] = st;
4914 if (this->unrestricted < last_share) {
4915 this->ReleaseShare(st);
4916 } else {
4917 this->unrestricted += flow;
4920 this->shares.swap(new_shares);
4924 * Restrict a flow by moving it to the end of the map and decreasing the amount
4925 * of unrestricted flow.
4926 * @param st Station of flow to be restricted.
4928 void FlowStat::RestrictShare(StationID st)
4930 assert(!this->shares.empty());
4931 uint flow = 0;
4932 uint last_share = 0;
4933 SharesMap new_shares;
4934 for (auto &it : this->shares) {
4935 if (flow == 0) {
4936 if (it.first > this->unrestricted) return; // Not present or already restricted.
4937 if (it.second == st) {
4938 flow = it.first - last_share;
4939 this->unrestricted -= flow;
4940 } else {
4941 new_shares[it.first] = it.second;
4943 } else {
4944 new_shares[it.first - flow] = it.second;
4946 last_share = it.first;
4948 if (flow == 0) return;
4949 new_shares[last_share + flow] = st;
4950 this->shares.swap(new_shares);
4951 assert(!this->shares.empty());
4955 * Release ("unrestrict") a flow by moving it to the begin of the map and
4956 * increasing the amount of unrestricted flow.
4957 * @param st Station of flow to be released.
4959 void FlowStat::ReleaseShare(StationID st)
4961 assert(!this->shares.empty());
4962 uint flow = 0;
4963 uint next_share = 0;
4964 bool found = false;
4965 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4966 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4967 if (found) {
4968 flow = next_share - it->first;
4969 this->unrestricted += flow;
4970 break;
4971 } else {
4972 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4973 if (it->second == st) found = true;
4975 next_share = it->first;
4977 if (flow == 0) return;
4978 SharesMap new_shares;
4979 new_shares[flow] = st;
4980 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4981 if (it->second != st) {
4982 new_shares[flow + it->first] = it->second;
4983 } else {
4984 flow = 0;
4987 this->shares.swap(new_shares);
4988 assert(!this->shares.empty());
4992 * Scale all shares from link graph's runtime to monthly values.
4993 * @param runtime Time the link graph has been running without compression.
4994 * @pre runtime must be greater than 0 as we don't want infinite flow values.
4996 void FlowStat::ScaleToMonthly(uint runtime)
4998 assert(runtime > 0);
4999 SharesMap new_shares;
5000 uint share = 0;
5001 for (auto i : this->shares) {
5002 share = std::max(share + 1, i.first * 30 / runtime);
5003 new_shares[share] = i.second;
5004 if (this->unrestricted == i.first) this->unrestricted = share;
5006 this->shares.swap(new_shares);
5010 * Add some flow from "origin", going via "via".
5011 * @param origin Origin of the flow.
5012 * @param via Next hop.
5013 * @param flow Amount of flow to be added.
5015 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
5017 FlowStatMap::iterator origin_it = this->find(origin);
5018 if (origin_it == this->end()) {
5019 this->emplace(origin, FlowStat(via, flow));
5020 } else {
5021 origin_it->second.ChangeShare(via, flow);
5022 assert(!origin_it->second.GetShares()->empty());
5027 * Pass on some flow, remembering it as invalid, for later subtraction from
5028 * locally consumed flow. This is necessary because we can't have negative
5029 * flows and we don't want to sort the flows before adding them up.
5030 * @param origin Origin of the flow.
5031 * @param via Next hop.
5032 * @param flow Amount of flow to be passed.
5034 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
5036 FlowStatMap::iterator prev_it = this->find(origin);
5037 if (prev_it == this->end()) {
5038 FlowStat fs(via, flow);
5039 fs.AppendShare(INVALID_STATION, flow);
5040 this->emplace(origin, fs);
5041 } else {
5042 prev_it->second.ChangeShare(via, flow);
5043 prev_it->second.ChangeShare(INVALID_STATION, flow);
5044 assert(!prev_it->second.GetShares()->empty());
5049 * Subtract invalid flows from locally consumed flow.
5050 * @param self ID of own station.
5052 void FlowStatMap::FinalizeLocalConsumption(StationID self)
5054 for (auto &i : *this) {
5055 FlowStat &fs = i.second;
5056 uint local = fs.GetShare(INVALID_STATION);
5057 if (local > INT_MAX) { // make sure it fits in an int
5058 fs.ChangeShare(self, -INT_MAX);
5059 fs.ChangeShare(INVALID_STATION, -INT_MAX);
5060 local -= INT_MAX;
5062 fs.ChangeShare(self, -(int)local);
5063 fs.ChangeShare(INVALID_STATION, -(int)local);
5065 /* If the local share is used up there must be a share for some
5066 * remote station. */
5067 assert(!fs.GetShares()->empty());
5072 * Delete all flows at a station for specific cargo and destination.
5073 * @param via Remote station of flows to be deleted.
5074 * @return IDs of source stations for which the complete FlowStat, not only a
5075 * share, has been erased.
5077 StationIDStack FlowStatMap::DeleteFlows(StationID via)
5079 StationIDStack ret;
5080 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
5081 FlowStat &s_flows = f_it->second;
5082 s_flows.ChangeShare(via, INT_MIN);
5083 if (s_flows.GetShares()->empty()) {
5084 ret.Push(f_it->first);
5085 this->erase(f_it++);
5086 } else {
5087 ++f_it;
5090 return ret;
5094 * Restrict all flows at a station for specific cargo and destination.
5095 * @param via Remote station of flows to be restricted.
5097 void FlowStatMap::RestrictFlows(StationID via)
5099 for (auto &it : *this) {
5100 it.second.RestrictShare(via);
5105 * Release all flows at a station for specific cargo and destination.
5106 * @param via Remote station of flows to be released.
5108 void FlowStatMap::ReleaseFlows(StationID via)
5110 for (auto &it : *this) {
5111 it.second.ReleaseShare(via);
5116 * Get the sum of all flows from this FlowStatMap.
5117 * @return sum of all flows.
5119 uint FlowStatMap::GetFlow() const
5121 uint ret = 0;
5122 for (const auto &it : *this) {
5123 ret += (--(it.second.GetShares()->end()))->first;
5125 return ret;
5129 * Get the sum of flows via a specific station from this FlowStatMap.
5130 * @param via Remote station to look for.
5131 * @return all flows for 'via' added up.
5133 uint FlowStatMap::GetFlowVia(StationID via) const
5135 uint ret = 0;
5136 for (const auto &it : *this) {
5137 ret += it.second.GetShare(via);
5139 return ret;
5143 * Get the sum of flows from a specific station from this FlowStatMap.
5144 * @param from Origin station to look for.
5145 * @return all flows from 'from' added up.
5147 uint FlowStatMap::GetFlowFrom(StationID from) const
5149 FlowStatMap::const_iterator i = this->find(from);
5150 if (i == this->end()) return 0;
5151 return (--(i->second.GetShares()->end()))->first;
5155 * Get the flow from a specific station via a specific other station.
5156 * @param from Origin station to look for.
5157 * @param via Remote station to look for.
5158 * @return flow share originating at 'from' and going to 'via'.
5160 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
5162 FlowStatMap::const_iterator i = this->find(from);
5163 if (i == this->end()) return 0;
5164 return i->second.GetShare(via);
5167 extern const TileTypeProcs _tile_type_station_procs = {
5168 DrawTile_Station, // draw_tile_proc
5169 GetSlopePixelZ_Station, // get_slope_z_proc
5170 ClearTile_Station, // clear_tile_proc
5171 nullptr, // add_accepted_cargo_proc
5172 GetTileDesc_Station, // get_tile_desc_proc
5173 GetTileTrackStatus_Station, // get_tile_track_status_proc
5174 ClickTile_Station, // click_tile_proc
5175 AnimateTile_Station, // animate_tile_proc
5176 TileLoop_Station, // tile_loop_proc
5177 ChangeTileOwner_Station, // change_tile_owner_proc
5178 nullptr, // add_produced_cargo_proc
5179 VehicleEnter_Station, // vehicle_enter_tile_proc
5180 GetFoundation_Station, // get_foundation_proc
5181 TerraformTile_Station, // terraform_tile_proc