Tracerestrict: Create slot/group inside selected slot group
[openttd-jgr.git] / src / station_cmd.cpp
blob5b35f89277d8536f55f563e51bc9ef03bcd48a09
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 "cmd_helper.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_func.h"
32 #include "clear_func.h"
33 #include "date_func.h"
34 #include "vehicle_func.h"
35 #include "string_func.h"
36 #include "animated_tile_func.h"
37 #include "elrail_func.h"
38 #include "station_base.h"
39 #include "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 "zoning.h"
59 #include "tunnelbridge_map.h"
60 #include "cheat_type.h"
61 #include "newgrf_roadstop.h"
62 #include "core/math_func.hpp"
64 #include "widgets/station_widget.h"
66 #include "table/strings.h"
68 #include "3rdparty/cpp-btree/btree_set.h"
69 #include "3rdparty/robin_hood/robin_hood.h"
71 #include <bitset>
73 #include "safeguards.h"
75 static StationSpec::TileFlags GetStationTileFlags(StationGfx gfx, const StationSpec *statspec);
77 bool _town_noise_no_update = false;
79 /**
80 * Check whether the given tile is a hangar.
81 * @param t the tile to of whether it is a hangar.
82 * @pre IsTileType(t, MP_STATION)
83 * @return true if and only if the tile is a hangar.
85 bool IsHangar(TileIndex t)
87 assert_tile(IsTileType(t, MP_STATION), t);
89 /* If the tile isn't an airport there's no chance it's a hangar. */
90 if (!IsAirport(t)) return false;
92 const Station *st = Station::GetByTile(t);
93 const AirportSpec *as = st->airport.GetSpec();
95 for (const auto &depot : as->depots) {
96 if (st->airport.GetRotatedTileFromOffset(depot.ti) == TileIndex(t)) return true;
99 return false;
103 * Look for a station owned by the given company around the given tile area.
104 * @param ta the area to search over
105 * @param closest_station the closest owned station found so far
106 * @param company the company whose stations to look for
107 * @param st to 'return' the found station
108 * @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
110 template <class T, class F>
111 CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st, F filter)
113 ta.Expand(1);
115 /* check around to see if there are any stations there owned by the company */
116 for (TileIndex tile_cur : ta) {
117 if (IsTileType(tile_cur, MP_STATION)) {
118 StationID t = GetStationIndex(tile_cur);
119 if (!T::IsValidID(t) || T::Get(t)->owner != company || !filter(T::Get(t))) continue;
120 if (closest_station == INVALID_STATION) {
121 closest_station = t;
122 } else if (closest_station != t) {
123 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
127 *st = (closest_station == INVALID_STATION) ? nullptr : T::Get(closest_station);
128 return CommandCost();
132 * Function to check whether the given tile matches some criterion.
133 * @param tile the tile to check
134 * @return true if it matches, false otherwise
136 typedef bool (*CMSAMatcher)(TileIndex tile);
139 * Counts the numbers of tiles matching a specific type in the area around
140 * @param tile the center tile of the 'count area'
141 * @param cmp the comparator/matcher (@see CMSAMatcher)
142 * @return the number of matching tiles around
144 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
146 int num = 0;
148 for (int dx = -3; dx <= 3; dx++) {
149 for (int dy = -3; dy <= 3; dy++) {
150 TileIndex t = TileAddWrap(tile, dx, dy);
151 if (t != INVALID_TILE && cmp(t)) num++;
155 return num;
159 * Check whether the tile is a mine.
160 * @param tile the tile to investigate.
161 * @return true if and only if the tile is a mine
163 static bool CMSAMine(TileIndex tile)
165 /* No industry */
166 if (!IsTileType(tile, MP_INDUSTRY)) return false;
168 const Industry *ind = Industry::GetByTile(tile);
170 /* No extractive industry */
171 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
173 for (const auto &p : ind->Produced()) {
174 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
175 * Also the production of passengers and mail is ignored. */
176 if (p.cargo != INVALID_CARGO &&
177 (CargoSpec::Get(p.cargo)->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
178 return true;
182 return false;
186 * Check whether the tile is water.
187 * @param tile the tile to investigate.
188 * @return true if and only if the tile is a water tile
190 static bool CMSAWater(TileIndex tile)
192 return IsTileType(tile, MP_WATER) && IsWater(tile);
196 * Check whether the tile is a tree.
197 * @param tile the tile to investigate.
198 * @return true if and only if the tile is a tree tile
200 static bool CMSATree(TileIndex tile)
202 return IsTileType(tile, MP_TREES);
205 #define M(x) ((x) - STR_SV_STNAME)
207 enum StationNaming {
208 STATIONNAMING_RAIL,
209 STATIONNAMING_ROAD,
210 STATIONNAMING_AIRPORT,
211 STATIONNAMING_OILRIG,
212 STATIONNAMING_DOCK,
213 STATIONNAMING_HELIPORT,
216 /** Information to handle station action 0 property 24 correctly */
217 struct StationNameInformation {
218 uint32_t free_names; ///< Current bitset of free names (we can remove names).
219 std::bitset<NUM_INDUSTRYTYPES> indtypes; ///< Bit set indicating when an industry type has been found.
223 * Find a station action 0 property 24 station name, or reduce the
224 * free_names if needed.
225 * @param tile the tile to search
226 * @param user_data the StationNameInformation to base the search on
227 * @return true if the tile contains an industry that has not given
228 * its name to one of the other stations in town.
230 static bool FindNearIndustryName(TileIndex tile, void *user_data)
232 /* All already found industry types */
233 StationNameInformation *sni = (StationNameInformation*)user_data;
234 if (!IsTileType(tile, MP_INDUSTRY)) return false;
236 /* If the station name is undefined it means that it doesn't name a station */
237 IndustryType indtype = GetIndustryType(tile);
238 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
240 /* In all cases if an industry that provides a name is found two of
241 * the standard names will be disabled. */
242 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
243 return !sni->indtypes[indtype];
246 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class, bool force_change = false)
248 static const uint32_t _gen_station_name_bits[] = {
249 0, // STATIONNAMING_RAIL
250 0, // STATIONNAMING_ROAD
251 1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
252 1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
253 1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
254 1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
257 const Town *t = st->town;
259 StationNameInformation sni{};
260 sni.free_names = UINT32_MAX;
262 std::bitset<MAX_EXTRA_STATION_NAMES> extra_names;
264 for (const Station *s : Station::Iterate()) {
265 if ((force_change || s != st) && s->town == t) {
266 if (s->indtype != IT_INVALID) {
267 sni.indtypes[s->indtype] = true;
268 StringID name = GetIndustrySpec(s->indtype)->station_name;
269 if (name != STR_UNDEFINED) {
270 /* Filter for other industrytypes with the same name */
271 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
272 const IndustrySpec *indsp = GetIndustrySpec(it);
273 if (indsp->enabled && indsp->station_name == name) sni.indtypes[it] = true;
276 continue;
278 if (s->extra_name_index < MAX_EXTRA_STATION_NAMES) {
279 extra_names.set(s->extra_name_index);
281 uint str = M(s->string_id);
282 if (str <= 0x20) {
283 if (str == M(STR_SV_STNAME_FOREST)) {
284 str = M(STR_SV_STNAME_WOODS);
286 ClrBit(sni.free_names, str);
291 st->extra_name_index = UINT16_MAX;
293 TileIndex indtile = tile;
294 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
295 /* An industry has been found nearby */
296 IndustryType indtype = GetIndustryType(indtile);
297 const IndustrySpec *indsp = GetIndustrySpec(indtype);
298 /* STR_NULL means it only disables oil rig/mines */
299 if (indsp->station_name != STR_NULL) {
300 st->indtype = indtype;
301 return STR_SV_STNAME_FALLBACK;
305 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
307 /* check default names */
308 uint32_t tmp = sni.free_names & _gen_station_name_bits[name_class];
309 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
311 /* check mine? */
312 if (HasBit(sni.free_names, M(STR_SV_STNAME_MINES))) {
313 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
314 return STR_SV_STNAME_MINES;
318 /* check close enough to town to get central as name? */
319 const bool is_central = DistanceMax(tile, t->xy) < 8;
320 if (HasBit(sni.free_names, M(STR_SV_STNAME)) && (is_central ||
321 DistanceSquare(tile, t->xy) <= std::max(t->cache.squared_town_zone_radius[HZB_TOWN_INNER_SUBURB], t->cache.squared_town_zone_radius[HZB_TOWN_OUTER_SUBURB]))) {
322 return STR_SV_STNAME;
325 bool use_extra_names = !_extra_station_names.empty();
326 auto check_extra_names = [&]() -> bool {
327 if (use_extra_names) {
328 use_extra_names = false;
329 const bool near_water = CountMapSquareAround(tile, CMSAWater) >= 5;
330 std::vector<uint16_t> candidates;
331 for (size_t i = 0; i < _extra_station_names.size(); i++) {
332 const ExtraStationNameInfo &info = _extra_station_names[i];
333 if (extra_names[i]) continue;
334 if (!HasBit(info.flags, name_class)) continue;
335 if (HasBit(info.flags, ESNIF_CENTRAL) && !is_central) continue;
336 if (HasBit(info.flags, ESNIF_NOT_CENTRAL) && is_central) continue;
337 if (HasBit(info.flags, ESNIF_NEAR_WATER) && !near_water) continue;
338 if (HasBit(info.flags, ESNIF_NOT_NEAR_WATER) && near_water) continue;
339 candidates.push_back(static_cast<uint16_t>(i));
342 if (!candidates.empty()) {
343 SavedRandomSeeds saved_seeds;
344 SaveRandomSeeds(&saved_seeds);
345 st->extra_name_index = candidates[RandomRange((uint)candidates.size())];
346 RestoreRandomSeeds(saved_seeds);
347 return true;
350 return false;
353 if (_extra_station_names_probability > 0) {
354 SavedRandomSeeds saved_seeds;
355 SaveRandomSeeds(&saved_seeds);
356 bool extra_name = (RandomRange(0xFF) < _extra_station_names_probability) && check_extra_names();
357 RestoreRandomSeeds(saved_seeds);
358 if (extra_name) return STR_SV_STNAME_FALLBACK;
361 /* check close enough to town to get central as name? */
362 if (is_central && HasBit(sni.free_names, M(STR_SV_STNAME_CENTRAL))) {
363 return STR_SV_STNAME_CENTRAL;
366 /* Check lakeside */
367 if (HasBit(sni.free_names, M(STR_SV_STNAME_LAKESIDE)) &&
368 DistanceFromEdge(tile) < 20 &&
369 CountMapSquareAround(tile, CMSAWater) >= 5) {
370 return STR_SV_STNAME_LAKESIDE;
373 /* Check woods */
374 if (HasBit(sni.free_names, M(STR_SV_STNAME_WOODS)) && (
375 CountMapSquareAround(tile, CMSATree) >= 8 ||
376 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
378 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
381 /* check elevation compared to town */
382 int z = GetTileZ(tile);
383 int z2 = GetTileZ(t->xy);
384 if (z < z2) {
385 if (HasBit(sni.free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
386 } else if (z > z2) {
387 if (HasBit(sni.free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
390 /* check direction compared to town */
391 static const int8_t _direction_and_table[] = {
392 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
393 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
394 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
395 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
398 sni.free_names &= _direction_and_table[
399 (TileX(tile) < TileX(t->xy)) +
400 (TileY(tile) < TileY(t->xy)) * 2];
402 /** Bitmask of remaining station names that can be used when a more specific name has not been used. */
403 static const uint32_t fallback_names = (
404 (1U << M(STR_SV_STNAME_NORTH)) |
405 (1U << M(STR_SV_STNAME_SOUTH)) |
406 (1U << M(STR_SV_STNAME_EAST)) |
407 (1U << M(STR_SV_STNAME_WEST)) |
408 (1U << M(STR_SV_STNAME_TRANSFER)) |
409 (1U << M(STR_SV_STNAME_HALT)) |
410 (1U << M(STR_SV_STNAME_EXCHANGE)) |
411 (1U << M(STR_SV_STNAME_ANNEXE)) |
412 (1U << M(STR_SV_STNAME_SIDINGS)) |
413 (1U << M(STR_SV_STNAME_BRANCH)) |
414 (1U << M(STR_SV_STNAME_UPPER)) |
415 (1U << M(STR_SV_STNAME_LOWER))
418 sni.free_names &= fallback_names;
419 if (sni.free_names != 0) return STR_SV_STNAME + FindFirstBit(sni.free_names);
421 if (check_extra_names()) return STR_SV_STNAME_FALLBACK;
423 return STR_SV_STNAME_FALLBACK;
425 #undef M
428 * Find the closest deleted station of the current company
429 * @param tile the tile to search from.
430 * @return the closest station or nullptr if too far.
432 static Station *GetClosestDeletedStation(TileIndex tile)
434 uint threshold = 8;
436 Station *best_station = nullptr;
437 ForAllStationsRadius(tile, threshold, [&](Station *st) {
438 if (!st->IsInUse() && st->owner == _current_company) {
439 uint cur_dist = DistanceManhattan(tile, st->xy);
441 if (cur_dist < threshold) {
442 threshold = cur_dist;
443 best_station = st;
444 } else if (cur_dist == threshold && best_station != nullptr) {
445 /* In case of a tie, lowest station ID wins */
446 if (st->index < best_station->index) best_station = st;
451 return best_station;
455 void Station::GetTileArea(TileArea *ta, StationType type) const
457 switch (type) {
458 case STATION_RAIL:
459 *ta = this->train_station;
460 return;
462 case STATION_AIRPORT:
463 *ta = this->airport;
464 return;
466 case STATION_TRUCK:
467 *ta = this->truck_station;
468 return;
470 case STATION_BUS:
471 *ta = this->bus_station;
472 return;
474 case STATION_DOCK:
475 case STATION_OILRIG:
476 *ta = this->docking_station;
477 return;
479 default: NOT_REACHED();
484 * Update the cargo history.
486 void Station::UpdateCargoHistory()
488 uint storage_offset = 0;
489 bool update_window = false;
490 for (const CargoSpec *cs : CargoSpec::Iterate()) {
491 uint amount = this->goods[cs->Index()].CargoTotalCount();
492 if (!HasBit(this->station_cargo_history_cargoes, cs->Index())) {
493 if (amount == 0) {
494 /* No cargo present, and no history stored for this cargo, no work to do */
495 continue;
496 } else {
497 if (this->station_cargo_history_cargoes == 0) update_window = true;
498 SetBit(this->station_cargo_history_cargoes, cs->Index());
499 this->station_cargo_history.emplace(this->station_cargo_history.begin() + storage_offset);
502 this->station_cargo_history[storage_offset][this->station_cargo_history_offset] = RXCompressUint(amount);
503 storage_offset++;
505 this->station_cargo_history_offset++;
506 if (this->station_cargo_history_offset == MAX_STATION_CARGO_HISTORY_DAYS) this->station_cargo_history_offset = 0;
507 if (update_window) InvalidateWindowData(WC_STATION_VIEW, this->index, -1);
511 * Update the virtual coords needed to draw the station sign.
513 void Station::UpdateVirtCoord()
515 if (IsHeadless()) return;
516 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
518 pt.y -= 32 * ZOOM_BASE;
519 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_BASE;
521 if (_viewport_sign_kdtree_valid && this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
523 SetDParam(0, this->index);
524 SetDParam(1, this->facilities);
525 this->sign.UpdatePosition(ShouldShowBaseStationViewportLabel(this) ? ZOOM_LVL_DRAW_SPR : ZOOM_LVL_END, pt.x, pt.y, STR_VIEWPORT_STATION, STR_VIEWPORT_STATION_TINY);
527 if (_viewport_sign_kdtree_valid) _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
529 SetWindowDirty(WC_STATION_VIEW, this->index);
533 * Move the station main coordinate somewhere else.
534 * @param new_xy new tile location of the sign
536 void Station::MoveSign(TileIndex new_xy)
538 if (this->xy == new_xy) return;
540 MarkAllViewportOverlayStationLinksDirty(this);
542 _station_kdtree.Remove(this->index);
544 this->BaseStation::MoveSign(new_xy);
546 _station_kdtree.Insert(this->index);
548 MarkAllViewportOverlayStationLinksDirty(this);
551 /** Update the virtual coords needed to draw the station sign for all stations. */
552 void UpdateAllStationVirtCoords()
554 if (IsHeadless()) return;
555 for (BaseStation *st : BaseStation::Iterate()) {
556 st->UpdateVirtCoord();
560 void BaseStation::FillCachedName() const
562 auto tmp_params = MakeParameters(this->index);
563 this->cached_name = GetStringWithArgs(Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, tmp_params);
566 void ClearAllStationCachedNames()
568 for (BaseStation *st : BaseStation::Iterate()) {
569 st->cached_name.clear();
574 * Get a mask of the cargo types that the station accepts.
575 * @param st Station to query
576 * @return the expected mask
578 CargoTypes GetAcceptanceMask(const Station *st)
580 CargoTypes mask = 0;
582 for (CargoID i = 0; i < NUM_CARGO; i++) {
583 if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) SetBit(mask, i);
585 return mask;
589 * Get a mask of the cargo types that are empty at the station.
590 * @param st Station to query
591 * @return the empty mask
593 CargoTypes GetEmptyMask(const Station *st)
595 CargoTypes mask = 0;
597 for (CargoID i = 0; i < NUM_CARGO; i++) {
598 if (st->goods[i].CargoTotalCount() == 0) SetBit(mask, i);
600 return mask;
604 * Add news item for when a station changes which cargoes it accepts.
605 * @param st Station of cargo change.
606 * @param cargoes Bit mask of cargo types to list.
607 * @param reject True iff the station rejects the cargo types.
609 static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
611 SetDParam(0, st->index);
612 SetDParam(1, cargoes);
613 StringID msg = reject ? STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_LIST : STR_NEWS_STATION_NOW_ACCEPTS_CARGO_LIST;
614 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
618 * Get the cargo types being produced around the tile (in a rectangle).
619 * @param north_tile Northern most tile of area
620 * @param w X extent of the area
621 * @param h Y extent of the area
622 * @param rad Search radius in addition to the given area
624 CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
626 CargoArray produced{};
628 btree::btree_set<IndustryID> industries;
629 TileArea ta = TileArea(north_tile, w, h).Expand(rad);
631 /* Loop over all tiles to get the produced cargo of
632 * everything except industries */
633 for (TileIndex tile : ta) {
634 if (IsTileType(tile, MP_INDUSTRY)) industries.insert(GetIndustryIndex(tile));
635 AddProducedCargo(tile, produced);
638 /* Loop over the seen industries. They produce cargo for
639 * anything that is within 'rad' of any one of their tiles.
641 for (IndustryID industry : industries) {
642 const Industry *i = Industry::Get(industry);
643 /* Skip industry with neutral station */
644 if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
646 for (const auto &p : i->Produced()) {
647 if (p.cargo != INVALID_CARGO) produced[p.cargo]++;
651 return produced;
655 * Get the acceptance of cargoes around the tile in 1/8.
656 * @param center_tile Center of the search area
657 * @param w X extent of area
658 * @param h Y extent of area
659 * @param rad Search radius in addition to given area
660 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
661 * @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
663 CargoArray GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad, CargoTypes *always_accepted)
665 CargoArray acceptance{};
666 if (always_accepted != nullptr) *always_accepted = 0;
668 TileArea ta = TileArea(center_tile, w, h).Expand(rad);
670 for (TileIndex tile : ta) {
671 /* Ignore industry if it has a neutral station. */
672 if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
674 AddAcceptedCargo(tile, acceptance, always_accepted);
677 return acceptance;
681 * Get the acceptance of cargoes around the station in.
682 * @param st Station to get acceptance of.
683 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
685 static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
687 CargoArray acceptance{};
688 if (always_accepted != nullptr) *always_accepted = 0;
690 BitmapTileIterator it(st->catchment_tiles);
691 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
692 AddAcceptedCargo(tile, acceptance, always_accepted);
695 return acceptance;
699 * Update the acceptance for a station.
700 * @param st Station to update
701 * @param show_msg controls whether to display a message that acceptance was changed.
703 void UpdateStationAcceptance(Station *st, bool show_msg)
705 /* old accepted goods types */
706 CargoTypes old_acc = GetAcceptanceMask(st);
708 /* And retrieve the acceptance. */
709 CargoArray acceptance{};
710 if (!st->rect.IsEmpty()) {
711 acceptance = GetAcceptanceAroundStation(st, &st->always_accepted);
714 /* Adjust in case our station only accepts fewer kinds of goods */
715 for (CargoID i = 0; i < NUM_CARGO; i++) {
716 uint amt = acceptance[i];
718 /* Make sure the station can accept the goods type. */
719 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
720 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
721 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
722 amt = 0;
725 GoodsEntry &ge = st->goods[i];
726 SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
727 if (LinkGraph::IsValidID(ge.link_graph)) {
728 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
732 /* Only show a message in case the acceptance was actually changed. */
733 CargoTypes new_acc = GetAcceptanceMask(st);
734 if (old_acc == new_acc) return;
736 /* show a message to report that the acceptance was changed? */
737 if (show_msg && st->owner == _local_company && st->IsInUse()) {
738 /* Combine old and new masks to get changes */
739 CargoTypes accepts = new_acc & ~old_acc;
740 CargoTypes rejects = ~new_acc & old_acc;
742 /* Show news message if there are any changes */
743 if (accepts != 0) ShowRejectOrAcceptNews(st, accepts, false);
744 if (rejects != 0) ShowRejectOrAcceptNews(st, rejects, true);
747 /* redraw the station view since acceptance changed */
748 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
751 static void UpdateStationSignCoord(BaseStation *st)
753 const StationRect *r = &st->rect;
755 if (r->IsEmpty()) return; // no tiles belong to this station
757 /* clamp sign coord to be inside the station rect */
758 TileIndex new_xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
759 st->MoveSign(new_xy);
761 if (!Station::IsExpected(st)) return;
762 Station *full_station = Station::From(st);
763 for (const GoodsEntry &ge : full_station->goods) {
764 LinkGraphID lg = ge.link_graph;
765 if (!LinkGraph::IsValidID(lg)) continue;
766 (*LinkGraph::Get(lg))[ge.node].UpdateLocation(st->xy);
771 * Common part of building various station parts and possibly attaching them to an existing one.
772 * @param[in,out] st Station to attach to
773 * @param flags Command flags
774 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
775 * @param area Area occupied by the new part
776 * @param name_class Station naming class to use to generate the new station's name
777 * @return Command error that occurred, if any
779 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
781 /* Find a deleted station close to us */
782 if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
784 if (*st != nullptr) {
785 if ((*st)->owner != _current_company) {
786 return CommandCost(CMD_ERROR);
789 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
790 if (ret.Failed()) return ret;
791 } else {
792 /* allocate and initialize new station */
793 if (!Station::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_STATIONS_LOADING);
795 if (flags & DC_EXEC) {
796 *st = new Station(area.tile);
797 _station_kdtree.Insert((*st)->index);
799 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
800 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
802 if (Company::IsValidID(_current_company)) {
803 if (_local_company == _current_company && !HasBit((*st)->town->have_ratings, _current_company)) {
804 ZoningTownAuthorityRatingChange();
806 SetBit((*st)->town->have_ratings, _current_company);
807 if (_cheats.town_rating.value) {
808 (*st)->town->ratings[_current_company] = RATING_MAXIMUM;
813 return CommandCost();
817 * This is called right after a station was deleted.
818 * It checks if the whole station is free of substations, and if so, the station will be
819 * deleted after a little while.
820 * @param st Station
822 static void DeleteStationIfEmpty(BaseStation *st)
824 if (!st->IsInUse()) {
825 st->delete_ctr = 0;
826 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
828 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
829 UpdateStationSignCoord(st);
833 * After adding/removing tiles to station, update some station-related stuff.
834 * @param adding True if adding tiles, false if removing them.
835 * @param type StationType being modified.
837 void Station::AfterStationTileSetChange(bool adding, StationType type)
839 this->UpdateVirtCoord();
840 DirtyCompanyInfrastructureWindows(this->owner);
841 if (adding) InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
843 switch (type) {
844 case STATION_RAIL:
845 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_TRAINS);
846 break;
847 case STATION_AIRPORT:
848 break;
849 case STATION_TRUCK:
850 case STATION_BUS:
851 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_ROADVEHS);
852 break;
853 case STATION_DOCK:
854 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_SHIPS);
855 break;
856 default: NOT_REACHED();
859 if (adding) {
860 this->RecomputeCatchment();
861 UpdateStationAcceptance(this, false);
862 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
863 } else {
864 DeleteStationIfEmpty(this);
865 this->RecomputeCatchment();
870 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
873 * Checks if the given tile is buildable, flat and has a certain height.
874 * @param tile TileIndex to check.
875 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
876 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
877 * @param allow_steep Whether steep slopes are allowed.
878 * @param check_bridge Check for the existence of a bridge.
879 * @return The cost in case of success, or an error code if it failed.
881 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge)
883 if (check_bridge && IsBridgeAbove(tile)) {
884 return CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
887 CommandCost ret = EnsureNoVehicleOnGround(tile);
888 if (ret.Failed()) return ret;
890 auto [tileh, z] = GetTileSlopeZ(tile);
892 /* Prohibit building if
893 * 1) The tile is "steep" (i.e. stretches two height levels).
894 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
896 if ((!allow_steep && IsSteepSlope(tileh)) ||
897 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
898 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
901 CommandCost cost(EXPENSES_CONSTRUCTION);
902 int flat_z = z + GetSlopeMaxZ(tileh);
903 if (tileh != SLOPE_FLAT) {
904 /* Forbid building if the tile faces a slope in a invalid direction. */
905 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
906 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
907 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
910 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
913 /* The level of this tile must be equal to allowed_z. */
914 if (allowed_z < 0) {
915 /* First tile. */
916 allowed_z = flat_z;
917 } else if (allowed_z != flat_z) {
918 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
921 return cost;
924 CommandCost IsRailStationBridgeAboveOk(TileIndex tile, const StationSpec *statspec, uint8_t layout, TileIndex northern_bridge_end, TileIndex southern_bridge_end, int bridge_height,
925 BridgeType bridge_type, TransportType bridge_transport_type)
927 if (statspec != nullptr && HasBit(statspec->internal_flags, SSIF_BRIDGE_HEIGHTS_SET)) {
928 int height_above = statspec->GetBridgeAboveFlags(layout).height;
929 if (height_above == 0) return CommandCost(INVALID_STRING_ID);
930 if (GetTileMaxZ(tile) + height_above > bridge_height) {
931 return CommandCost(STR_ERROR_BRIDGE_TOO_LOW_FOR_STATION);
933 } else if (!statspec) {
934 /* Default stations/waypoints */
935 const int height = layout < 4 ? 2 : 5;
936 if (GetTileMaxZ(tile) + height > bridge_height) return CommandCost(STR_ERROR_BRIDGE_TOO_LOW_FOR_STATION);
937 } else {
938 if (!_settings_game.construction.allow_stations_under_bridges) return CommandCost(INVALID_STRING_ID);
941 BridgePiecePillarFlags disallowed_pillar_flags;
942 if (statspec != nullptr && HasBit(statspec->internal_flags, SSIF_BRIDGE_DISALLOWED_PILLARS_SET)) {
943 /* Pillar flags set by NewGRF */
944 disallowed_pillar_flags = (BridgePiecePillarFlags) statspec->GetBridgeAboveFlags(layout).disallowed_pillars;
945 } else if (!statspec) {
946 /* Default stations/waypoints */
947 if (layout < 8) {
948 static const uint8_t st_flags[8] = { 0x50, 0xA0, 0x50, 0xA0, 0x50 | 0x26, 0xA0 | 0x1C, 0x50 | 0x89, 0xA0 | 0x43 };
949 disallowed_pillar_flags = (BridgePiecePillarFlags) st_flags[layout];
950 } else {
951 disallowed_pillar_flags = (BridgePiecePillarFlags) 0;
953 } else if ((GetStationTileFlags(layout, statspec) & StationSpec::TileFlags::Blocked) == StationSpec::TileFlags::Blocked) {
954 /* Non-track station tiles */
955 disallowed_pillar_flags = (BridgePiecePillarFlags) 0;
956 } else {
957 /* Tracked station tiles */
958 const Axis axis = HasBit(layout, 0) ? AXIS_Y : AXIS_X;
959 disallowed_pillar_flags = (BridgePiecePillarFlags) (axis == AXIS_X ? 0x50 : 0xA0);
962 if ((GetBridgeTilePillarFlags(tile, northern_bridge_end, southern_bridge_end, bridge_type, bridge_transport_type) & disallowed_pillar_flags) == 0) {
963 return CommandCost();
964 } else {
965 return CommandCost(STR_ERROR_BRIDGE_PILLARS_OBSTRUCT_STATION);
969 CommandCost IsRailStationBridgeAboveOk(TileIndex tile, const StationSpec *statspec, uint8_t layout)
971 if (!IsBridgeAbove(tile)) return CommandCost();
973 TileIndex southern_bridge_end = GetSouthernBridgeEnd(tile);
974 TileIndex northern_bridge_end = GetNorthernBridgeEnd(tile);
975 return IsRailStationBridgeAboveOk(tile, statspec, layout, northern_bridge_end, southern_bridge_end, GetBridgeHeight(southern_bridge_end),
976 GetBridgeType(southern_bridge_end), GetTunnelBridgeTransportType(southern_bridge_end));
979 CommandCost IsRoadStopBridgeAboveOK(TileIndex tile, const RoadStopSpec *spec, bool drive_through, DiagDirection entrance,
980 TileIndex northern_bridge_end, TileIndex southern_bridge_end, int bridge_height,
981 BridgeType bridge_type, TransportType bridge_transport_type)
983 if (spec && HasBit(spec->internal_flags, RSIF_BRIDGE_HEIGHTS_SET)) {
984 int height = spec->bridge_height[drive_through ? (GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET + DiagDirToAxis(entrance)) : entrance];
985 if (height == 0) return CommandCost(INVALID_STRING_ID);
986 if (GetTileMaxZ(tile) + height > bridge_height) {
987 return CommandCost(STR_ERROR_BRIDGE_TOO_LOW_FOR_STATION);
989 } else {
990 if (!_settings_game.construction.allow_road_stops_under_bridges) return CommandCost(INVALID_STRING_ID);
992 if (GetTileMaxZ(tile) + (drive_through ? 1 : 2) > bridge_height) {
993 return CommandCost(STR_ERROR_BRIDGE_TOO_LOW_FOR_STATION);
997 BridgePiecePillarFlags disallowed_pillar_flags = (BridgePiecePillarFlags) 0;
998 if (spec && HasBit(spec->internal_flags, RSIF_BRIDGE_DISALLOWED_PILLARS_SET)) {
999 disallowed_pillar_flags = (BridgePiecePillarFlags) spec->bridge_disallowed_pillars[drive_through ? (GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET + DiagDirToAxis(entrance)) : entrance];
1000 } else if (drive_through) {
1001 disallowed_pillar_flags = (BridgePiecePillarFlags) (DiagDirToAxis(entrance) == AXIS_X ? 0x50 : 0xA0);
1002 } else {
1003 SetBit(disallowed_pillar_flags, 4 + entrance);
1005 if ((GetBridgeTilePillarFlags(tile, northern_bridge_end, southern_bridge_end, bridge_type, bridge_transport_type) & disallowed_pillar_flags) == 0) {
1006 return CommandCost();
1007 } else {
1008 return CommandCost(STR_ERROR_BRIDGE_PILLARS_OBSTRUCT_STATION);
1013 * Checks if a rail station can be built at the given area.
1014 * @param tile_area Area to check.
1015 * @param flags Operation to perform.
1016 * @param axis Rail station axis.
1017 * @param station StationID to be queried and returned if available.
1018 * @param rt The rail type to check for (overbuilding rail stations over rail).
1019 * @param affected_vehicles List of trains with PBS reservations on the tiles
1020 * @param spec_class Station class.
1021 * @param spec_index Index into the station class.
1022 * @param plat_len Platform length.
1023 * @param numtracks Number of platforms.
1024 * @return The cost in case of success, or an error code if it failed.
1026 static CommandCost CheckFlatLandRailStation(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)
1028 CommandCost cost(EXPENSES_CONSTRUCTION);
1029 int allowed_z = -1;
1030 uint invalid_dirs = 5 << axis;
1032 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1033 bool slope_cb = statspec != nullptr && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
1035 for (TileIndex tile_cur : tile_area) {
1036 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false, false);
1037 if (ret.Failed()) return ret;
1038 cost.AddCost(ret);
1040 if (slope_cb) {
1041 /* Do slope check if requested. */
1042 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, rt, statspec, axis, plat_len, numtracks);
1043 if (ret.Failed()) return ret;
1046 /* if station is set, then we have special handling to allow building on top of already existing stations.
1047 * so station points to INVALID_STATION if we can build on any station.
1048 * Or it points to a station if we're only allowed to build on exactly that station. */
1049 if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
1050 if (!IsRailStation(tile_cur)) {
1051 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
1052 } else {
1053 StationID st = GetStationIndex(tile_cur);
1054 if (*station == INVALID_STATION) {
1055 *station = st;
1056 } else if (*station != st) {
1057 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1059 if (_settings_game.vehicle.train_braking_model == TBM_REALISTIC && HasStationReservation(tile_cur)) {
1060 CommandCost ret = CheckTrainReservationPreventsTrackModification(tile_cur, GetRailStationTrack(tile_cur));
1061 if (ret.Failed()) return ret;
1064 } else {
1065 /* If we are building a station with a valid railtype, we may be able to overbuild an existing rail tile. */
1066 if (rt != INVALID_RAILTYPE && IsPlainRailTile(tile_cur)) {
1067 /* Don't overbuild signals. */
1068 if (HasSignals(tile_cur)) return CommandCost(STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
1070 /* The current rail type must have power on the to-be-built type (e.g. convert normal rail to electrified rail). */
1071 if (HasPowerOnRail(GetRailType(tile_cur), rt)) {
1072 TrackBits tracks = GetTrackBits(tile_cur);
1073 Track track = RemoveFirstTrack(&tracks);
1074 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
1076 /* The existing track must align with the desired station axis. */
1077 if (tracks == TRACK_BIT_NONE && track == expected_track) {
1078 /* Check for trains having a reservation for this tile. */
1079 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
1080 Train *v = GetTrainForReservation(tile_cur, track);
1081 if (v != nullptr) {
1082 CommandCost ret = CheckTrainReservationPreventsTrackModification(v);
1083 if (ret.Failed()) return ret;
1084 affected_vehicles.push_back(v);
1087 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
1088 if (ret.Failed()) return ret;
1089 cost.AddCost(ret);
1090 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
1091 continue;
1095 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1096 if (ret.Failed()) return ret;
1097 cost.AddCost(ret);
1101 return cost;
1105 * Checks if a road stop can be built at the given tile.
1106 * @param tile_area Area to check.
1107 * @param spec Road stop spec.
1108 * @param flags Operation to perform.
1109 * @param invalid_dirs Prohibited directions (set of DiagDirections).
1110 * @param is_drive_through True if trying to build a drive-through station.
1111 * @param station_type Station type (bus, truck or road waypoint).
1112 * @param axis Axis of a drive-through road stop.
1113 * @param station StationID to be queried and returned if available.
1114 * @param rt Road type to build.
1115 * @param require_road Is existing road required.
1116 * @return The cost in case of success, or an error code if it failed.
1118 CommandCost CheckFlatLandRoadStop(TileArea tile_area, const RoadStopSpec *spec, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, StationType station_type, Axis axis, StationID *station, RoadType rt, bool require_road)
1120 CommandCost cost(EXPENSES_CONSTRUCTION);
1121 int allowed_z = -1;
1123 for (TileIndex cur_tile : tile_area) {
1124 bool allow_under_bridge = _settings_game.construction.allow_road_stops_under_bridges || (spec != nullptr && HasBit(spec->internal_flags, RSIF_BRIDGE_HEIGHTS_SET));
1125 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through, !allow_under_bridge);
1126 if (ret.Failed()) return ret;
1127 cost.AddCost(ret);
1129 if (allow_under_bridge && IsBridgeAbove(cur_tile)) {
1130 TileIndex southern_bridge_end = GetSouthernBridgeEnd(cur_tile);
1131 TileIndex northern_bridge_end = GetNorthernBridgeEnd(cur_tile);
1132 CommandCost bridge_ret = IsRoadStopBridgeAboveOK(cur_tile, spec, is_drive_through, (DiagDirection) FindFirstBit(invalid_dirs),
1133 northern_bridge_end, southern_bridge_end, GetBridgeHeight(southern_bridge_end),
1134 GetBridgeType(southern_bridge_end), GetTunnelBridgeTransportType(southern_bridge_end));
1135 if (bridge_ret.Failed()) return bridge_ret;
1138 /* If station is set, then we have special handling to allow building on top of already existing stations.
1139 * Station points to INVALID_STATION if we can build on any station.
1140 * Or it points to a station if we're only allowed to build on exactly that station. */
1141 if (station != nullptr && IsTileType(cur_tile, MP_STATION)) {
1142 if (!IsAnyRoadStop(cur_tile)) {
1143 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
1144 } else {
1145 if (station_type != GetStationType(cur_tile) ||
1146 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
1147 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
1149 /* Drive-through station in the wrong direction. */
1150 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && GetDriveThroughStopAxis(cur_tile) != axis) {
1151 return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1153 StationID st = GetStationIndex(cur_tile);
1154 if (*station == INVALID_STATION) {
1155 *station = st;
1156 } else if (*station != st) {
1157 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1160 } else {
1161 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
1162 /* Road bits in the wrong direction. */
1163 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
1164 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
1165 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1166 switch (CountBits(rb)) {
1167 case 1:
1168 return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1170 case 2:
1171 if (rb == ROAD_X || rb == ROAD_Y) return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1172 return CommandCost(STR_ERROR_DRIVE_THROUGH_CORNER);
1174 default: // 3 or 4
1175 return CommandCost(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1179 if (build_over_road) {
1180 /* There is a road, check if we can build road+tram stop over it. */
1181 RoadType road_rt = GetRoadType(cur_tile, RTT_ROAD);
1182 if (road_rt != INVALID_ROADTYPE) {
1183 Owner road_owner = GetRoadOwner(cur_tile, RTT_ROAD);
1184 if (road_owner == OWNER_TOWN) {
1185 if (!_settings_game.construction.road_stop_on_town_road) return CommandCost(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1186 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1187 ret = CheckOwnership(road_owner);
1188 if (ret.Failed()) return ret;
1190 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_ROAD));
1192 if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return CommandCost(STR_ERROR_NO_SUITABLE_ROAD);
1194 cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1195 } else if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt)) {
1196 cost.AddCost(RoadBuildCost(rt) * 2);
1199 /* There is a tram, check if we can build road+tram stop over it. */
1200 RoadType tram_rt = GetRoadType(cur_tile, RTT_TRAM);
1201 if (tram_rt != INVALID_ROADTYPE) {
1202 Owner tram_owner = GetRoadOwner(cur_tile, RTT_TRAM);
1203 if (Company::IsValidID(tram_owner) &&
1204 (!_settings_game.construction.road_stop_on_competitor_road ||
1205 /* Disallow breaking end-of-line of someone else
1206 * so trams can still reverse on this tile. */
1207 HasExactlyOneBit(GetRoadBits(cur_tile, RTT_TRAM)))) {
1208 ret = CheckOwnership(tram_owner);
1209 if (ret.Failed()) return ret;
1211 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_TRAM));
1213 if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return CommandCost(STR_ERROR_NO_SUITABLE_ROAD);
1215 cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1216 } else if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt)) {
1217 cost.AddCost(RoadBuildCost(rt) * 2);
1219 } else if (require_road) {
1220 return CommandCost(STR_ERROR_THERE_IS_NO_ROAD);
1221 } else {
1222 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1223 if (ret.Failed()) return ret;
1224 cost.AddCost(ret);
1225 cost.AddCost(RoadBuildCost(rt) * 2);
1230 return cost;
1234 * Checks if an airport can be built at the given location and clear the area.
1235 * @param tile_iter Airport tile iterator.
1236 * @param flags Operation to perform.
1237 * @param station StationID of airport allowed in search area.
1238 * @return The cost in case of success, or an error code if it failed.
1240 static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlag flags, StationID *station)
1242 CommandCost cost(EXPENSES_CONSTRUCTION);
1243 int allowed_z = -1;
1245 for (; tile_iter != INVALID_TILE; ++tile_iter) {
1246 const TileIndex tile_cur = tile_iter;
1247 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true, true);
1248 if (ret.Failed()) return ret;
1249 cost.AddCost(ret);
1251 /* if station is set, then allow building on top of an already
1252 * existing airport, either the one in *station if it is not
1253 * INVALID_STATION, or anyone otherwise and store which one
1254 * in *station */
1255 if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
1256 if (!IsAirport(tile_cur)) {
1257 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
1258 } else {
1259 StationID st = GetStationIndex(tile_cur);
1260 if (*station == INVALID_STATION) {
1261 *station = st;
1262 } else if (*station != st) {
1263 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1266 } else {
1267 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1268 if (ret.Failed()) return ret;
1269 cost.AddCost(ret);
1273 return cost;
1277 * Check whether we can expand the rail part of the given station.
1278 * @param st the station to expand
1279 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1280 * @return Succeeded or failed command.
1282 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta)
1284 TileArea cur_ta = st->train_station;
1286 /* determine new size of train station region.. */
1287 int x = std::min(TileX(cur_ta.tile), TileX(new_ta.tile));
1288 int y = std::min(TileY(cur_ta.tile), TileY(new_ta.tile));
1289 new_ta.w = (uint16_t)std::max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1290 new_ta.h = (uint16_t)std::max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1291 new_ta.tile = TileXY(x, y);
1293 /* make sure the final size is not too big. */
1294 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
1295 return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
1298 return CommandCost();
1301 static inline uint8_t *CreateSingle(uint8_t *layout, int n)
1303 int i = n;
1304 do *layout++ = 0; while (--i);
1305 layout[((n - 1) >> 1) - n] = 2;
1306 return layout;
1309 static inline uint8_t *CreateMulti(uint8_t *layout, int n, uint8_t b)
1311 int i = n;
1312 do *layout++ = b; while (--i);
1313 if (n > 4) {
1314 layout[0 - n] = 0;
1315 layout[n - 1 - n] = 0;
1317 return layout;
1321 * Create the station layout for the given number of tracks and platform length.
1322 * @param layout The layout to write to.
1323 * @param numtracks The number of tracks to write.
1324 * @param plat_len The length of the platforms.
1325 * @param statspec The specification of the station to (possibly) get the layout from.
1327 void GetStationLayout(uint8_t *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
1329 if (statspec != nullptr) {
1330 auto found = statspec->layouts.find(GetStationLayoutKey(numtracks, plat_len));
1331 if (found != std::end(statspec->layouts)) {
1332 /* Custom layout defined, copy to buffer. */
1333 std::copy(std::begin(found->second), std::end(found->second), layout);
1334 return;
1338 if (plat_len == 1) {
1339 CreateSingle(layout, numtracks);
1340 } else {
1341 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1342 int n = numtracks >> 1;
1344 while (--n >= 0) {
1345 layout = CreateMulti(layout, plat_len, 4);
1346 layout = CreateMulti(layout, plat_len, 6);
1352 * Find a nearby station that joins this station.
1353 * @tparam T the class to find a station for
1354 * @param existing_station an existing station we build over
1355 * @param station_to_join the station to join to
1356 * @param adjacent whether adjacent stations are allowed
1357 * @param ta the area of the newly build station
1358 * @param st 'return' pointer for the found station
1359 * @param error_message the error message when building a station on top of others
1360 * @return command cost with the error or 'okay'
1362 template <class T, class F>
1363 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, StringID error_message, F filter)
1365 assert(*st == nullptr);
1366 bool check_surrounding = true;
1368 if (existing_station != INVALID_STATION) {
1369 if (adjacent && existing_station != station_to_join) {
1370 /* You can't build an adjacent station over the top of one that
1371 * already exists. */
1372 return CommandCost(error_message);
1373 } else {
1374 /* Extend the current station, and don't check whether it will
1375 * be near any other stations. */
1376 T *candidate = T::GetIfValid(existing_station);
1377 if (candidate != nullptr && filter(candidate)) *st = candidate;
1378 check_surrounding = (*st == nullptr);
1380 } else {
1381 /* There's no station here. Don't check the tiles surrounding this
1382 * one if the company wanted to build an adjacent station. */
1383 if (adjacent) check_surrounding = false;
1386 if (check_surrounding) {
1387 /* Make sure there is no more than one other station around us that is owned by us. */
1388 CommandCost ret = GetStationAround(ta, existing_station, _current_company, st, filter);
1389 if (ret.Failed()) return ret;
1392 /* Distant join */
1393 if (*st == nullptr && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1395 return CommandCost();
1399 * Find a nearby station that joins this station.
1400 * @param existing_station an existing station we build over
1401 * @param station_to_join the station to join to
1402 * @param adjacent whether adjacent stations are allowed
1403 * @param ta the area of the newly build station
1404 * @param st 'return' pointer for the found station
1405 * @param error_message the error message when building a station on top of others
1406 * @return command cost with the error or 'okay'
1408 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st, StringID error_message = STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST)
1410 return FindJoiningBaseStation<Station>(existing_station, station_to_join, adjacent, ta, st, error_message, [](Station *st) -> bool { return true; });
1414 * Find a nearby waypoint that joins this waypoint.
1415 * @param existing_waypoint an existing waypoint we build over
1416 * @param waypoint_to_join the waypoint to join to
1417 * @param adjacent whether adjacent waypoints are allowed
1418 * @param ta the area of the newly build waypoint
1419 * @param wp 'return' pointer for the found waypoint
1420 * @return command cost with the error or 'okay'
1422 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
1424 return FindJoiningBaseStation<Waypoint>(existing_waypoint, waypoint_to_join, adjacent, ta, wp,
1425 is_road ? STR_ERROR_MUST_REMOVE_ROADWAYPOINT_FIRST : STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST,
1426 [is_road](Waypoint *wp) -> bool { return HasBit(wp->waypoint_flags, WPF_ROAD) == is_road; });
1430 * Clear any rail station platform reservation ahead of and behind train.
1431 * @param v vehicle which may hold reservations
1433 void FreeTrainStationPlatformReservation(const Train *v)
1435 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1436 v = v->Last();
1437 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
1441 * Clear platform reservation during station building/removing.
1442 * @param v vehicle which holds reservation
1444 static void FreeTrainReservation(Train *v)
1446 FreeTrainTrackReservation(v);
1447 FreeTrainStationPlatformReservation(v);
1451 * Restore platform reservation during station building/removing.
1452 * @param v vehicle which held reservation
1454 static void RestoreTrainReservation(Train *v)
1456 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1457 TryPathReserve(v, true, true);
1458 v = v->Last();
1459 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1463 * Get station tile flags for the given StationGfx.
1464 * @param gfx StationGfx of station tile.
1465 * @param statspec Station spec of station tile.
1466 * @return Tile flags to apply.
1468 static StationSpec::TileFlags GetStationTileFlags(StationGfx gfx, const StationSpec *statspec)
1470 /* Default stations do not draw pylons under roofs (gfx >= 4) */
1471 if (statspec == nullptr || gfx >= statspec->tileflags.size()) return gfx < 4 ? StationSpec::TileFlags::Pylons : StationSpec::TileFlags::None;
1472 return statspec->tileflags[gfx];
1476 * Set rail station tile flags for the given tile.
1477 * @param tile Tile to set flags on.
1478 * @param statspec Statspec of the tile.
1480 void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
1482 const auto flags = GetStationTileFlags(GetStationGfx(tile), statspec);
1483 SetStationTileBlocked(tile, HasFlag(flags, StationSpec::TileFlags::Blocked));
1484 SetStationTileHavePylons(tile, HasFlag(flags, StationSpec::TileFlags::Pylons));
1485 SetStationTileHaveWires(tile, !HasFlag(flags, StationSpec::TileFlags::NoWires));
1489 * Build rail station
1490 * @param tile_org northern most position of station dragging/placement
1491 * @param flags operation to perform
1492 * @param p1 various bitstuffed elements
1493 * - p1 = (bit 0- 5) - railtype
1494 * - p1 = (bit 6) - orientation (Axis)
1495 * - p1 = (bit 8-15) - number of tracks
1496 * - p1 = (bit 16-23) - platform length
1497 * - p1 = (bit 24) - allow stations directly adjacent to other stations.
1498 * @param p2 various bitstuffed elements
1499 * - p2 = (bit 0-15) - custom station class
1500 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
1501 * @param p3 various bitstuffed elements
1502 * - p3 = (bit 0-15) - custom station id
1503 * @param text unused
1504 * @return the cost of this operation or an error
1506 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32_t p1, uint32_t p2, uint64_t p3, const char *text, const CommandAuxiliaryBase *aux_data)
1508 /* Unpack parameters */
1509 RailType rt = Extract<RailType, 0, 6>(p1);
1510 Axis axis = Extract<Axis, 6, 1>(p1);
1511 uint8_t numtracks = GB(p1, 8, 8);
1512 uint8_t plat_len = GB(p1, 16, 8);
1513 bool adjacent = HasBit(p1, 24);
1515 StationClassID spec_class = Extract<StationClassID, 0, 16>(p2);
1516 uint16_t spec_index = GB(p3, 0, 16);
1517 StationID station_to_join = GB(p2, 16, 16);
1519 /* Does the authority allow this? */
1520 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1521 if (ret.Failed()) return ret;
1523 if (!ValParamRailType(rt)) return CMD_ERROR;
1525 /* Check if the given station class is valid */
1526 if (static_cast<uint>(spec_class) >= StationClass::GetClassCount()) return CMD_ERROR;
1527 const StationClass *cls = StationClass::Get(spec_class);
1528 if (IsWaypointClass(*cls)) return CMD_ERROR;
1529 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1530 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1532 int w_org, h_org;
1533 if (axis == AXIS_X) {
1534 w_org = plat_len;
1535 h_org = numtracks;
1536 } else {
1537 h_org = plat_len;
1538 w_org = numtracks;
1541 /* Check if the first tile and the last tile are valid */
1542 if (!IsValidTile(tile_org) || TileAddWrap(tile_org, w_org - 1, h_org - 1) == INVALID_TILE) return CMD_ERROR;
1544 bool reuse = (station_to_join != NEW_STATION);
1545 if (!reuse) station_to_join = INVALID_STATION;
1546 bool distant_join = (station_to_join != INVALID_STATION);
1548 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1550 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1552 /* these values are those that will be stored in train_tile and station_platforms */
1553 TileArea new_location(tile_org, w_org, h_org);
1555 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1556 StationID est = INVALID_STATION;
1557 std::vector<Train *> affected_vehicles;
1559 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1561 TileIndexDiff tile_delta = TileOffsByAxis(axis); // offset to go to the next platform tile
1562 TileIndexDiff track_delta = TileOffsByAxis(OtherAxis(axis)); // offset to go to the next track
1563 TempBufferST<uint8_t> layout_buffer(numtracks * plat_len);
1564 GetStationLayout(layout_buffer, numtracks, plat_len, statspec);
1567 TileIndex tile_track = tile_org;
1568 uint8_t *check_layout_ptr = layout_buffer;
1569 for (uint i = 0; i < numtracks; i++) {
1570 TileIndex tile = tile_track;
1571 for (uint j = 0; j < plat_len; j++) {
1572 CommandCost ret = IsRailStationBridgeAboveOk(tile, statspec, *check_layout_ptr++);
1573 if (ret.Failed()) {
1574 return CommandCost::DualErrorMessage(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST, ret.GetErrorMessage());
1576 tile += tile_delta;
1578 tile_track += track_delta;
1582 /* Clear the land below the station. */
1583 CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1584 if (cost.Failed()) return cost;
1585 /* Add construction expenses. */
1586 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
1587 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
1589 Station *st = nullptr;
1590 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1591 if (ret.Failed()) return ret;
1593 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1594 if (ret.Failed()) return ret;
1596 if (st != nullptr && st->train_station.tile != INVALID_TILE) {
1597 ret = CanExpandRailStation(st, new_location);
1598 if (ret.Failed()) return ret;
1601 /* Check if we can allocate a custom stationspec to this station */
1602 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1603 if (specindex == -1) return CommandCost(STR_ERROR_TOO_MANY_STATION_SPECS);
1605 if (statspec != nullptr) {
1606 /* Perform NewStation checks */
1608 /* Check if the station size is permitted */
1609 if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7))) return CommandCost(STR_ERROR_STATION_DISALLOWED_NUMBER_TRACKS);
1610 if (HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) return CommandCost(STR_ERROR_STATION_DISALLOWED_LENGTH);
1612 /* Check if the station is buildable */
1613 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1614 uint16_t cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE, rt);
1615 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1619 if (flags & DC_EXEC) {
1620 st->train_station = new_location;
1621 st->AddFacility(FACIL_TRAIN, new_location.tile);
1623 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1625 if (statspec != nullptr) {
1626 /* Include this station spec's animation trigger bitmask
1627 * in the station's cached copy. */
1628 st->cached_anim_triggers |= statspec->animation.triggers;
1631 Track track = AxisToTrack(axis);
1633 uint8_t numtracks_orig = numtracks;
1635 Company *c = Company::Get(st->owner);
1636 TileIndex tile_track = tile_org;
1637 uint8_t *layout_ptr = layout_buffer;
1638 do {
1639 TileIndex tile = tile_track;
1640 int w = plat_len;
1641 do {
1642 uint8_t layout = *layout_ptr++;
1643 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1644 /* Check for trains having a reservation for this tile. */
1645 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1646 if (v != nullptr) {
1647 affected_vehicles.push_back(v);
1648 /* Not necessary to call CheckTrainReservationPreventsTrackModification as that is done by CheckFlatLandRailStation */
1649 FreeTrainReservation(v);
1653 /* Railtype can change when overbuilding. */
1654 if (IsRailStationTile(tile)) {
1655 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1656 c->infrastructure.station--;
1659 /* Remove animation if overbuilding */
1660 DeleteAnimatedTile(tile);
1661 uint8_t old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1662 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1663 /* Free the spec if we overbuild something */
1664 if (old_specindex != specindex) DeallocateSpecFromStation(st, old_specindex);
1666 SetCustomStationSpecIndex(tile, specindex);
1667 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1668 SetAnimationFrame(tile, 0);
1670 if (statspec != nullptr) {
1671 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1672 uint32_t platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1674 /* As the station is not yet completely finished, the station does not yet exist. */
1675 uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile, rt);
1676 if (callback != CALLBACK_FAILED) {
1677 if (callback <= UINT8_MAX) {
1678 SetStationGfx(tile, (callback & ~1) + axis);
1679 } else {
1680 ErrorUnknownCallbackResult(statspec->grf_prop.grfid, CBID_STATION_BUILD_TILE_LAYOUT, callback);
1684 /* Trigger station animation -- after building? */
1685 TriggerStationAnimation(st, tile, SAT_BUILT);
1688 SetRailStationTileFlags(tile, statspec);
1690 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1691 c->infrastructure.station++;
1693 tile += tile_delta;
1694 } while (--w);
1695 AddTrackToSignalBuffer(tile_track, track, _current_company);
1696 YapfNotifyTrackLayoutChange(tile_track, track);
1697 tile_track += track_delta;
1698 } while (--numtracks);
1700 for (uint i = 0; i < affected_vehicles.size(); ++i) {
1701 /* Restore reservations of trains. */
1702 RestoreTrainReservation(affected_vehicles[i]);
1705 /* Check whether we need to expand the reservation of trains already on the station. */
1706 TileArea update_reservation_area;
1707 if (axis == AXIS_X) {
1708 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1709 } else {
1710 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1713 for (TileIndex tile : update_reservation_area) {
1714 /* Don't even try to make eye candy parts reserved. */
1715 if (IsStationTileBlocked(tile)) continue;
1717 DiagDirection dir = AxisToDiagDir(axis);
1718 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1719 TileIndex platform_begin = tile;
1720 TileIndex platform_end = tile;
1722 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1723 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1724 platform_begin = next_tile;
1726 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1727 platform_end = next_tile;
1730 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1731 bool reservation = false;
1732 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1733 reservation = HasStationReservation(t);
1736 if (reservation) {
1737 SetRailStationPlatformReservation(platform_begin, dir, true);
1741 st->MarkTilesDirty(false);
1742 st->AfterStationTileSetChange(true, STATION_RAIL);
1743 ZoningMarkDirtyStationCoverageArea(st);
1746 return cost;
1749 static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1751 restart:
1753 /* too small? */
1754 if (ta.w != 0 && ta.h != 0) {
1755 /* check the left side, x = constant, y changes */
1756 for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1757 /* the left side is unused? */
1758 if (++i == ta.h) {
1759 ta.tile += TileDiffXY(1, 0);
1760 ta.w--;
1761 goto restart;
1765 /* check the right side, x = constant, y changes */
1766 for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1767 /* the right side is unused? */
1768 if (++i == ta.h) {
1769 ta.w--;
1770 goto restart;
1774 /* check the upper side, y = constant, x changes */
1775 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1776 /* the left side is unused? */
1777 if (++i == ta.w) {
1778 ta.tile += TileDiffXY(0, 1);
1779 ta.h--;
1780 goto restart;
1784 /* check the lower side, y = constant, x changes */
1785 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1786 /* the left side is unused? */
1787 if (++i == ta.w) {
1788 ta.h--;
1789 goto restart;
1792 } else {
1793 ta.Clear();
1796 return ta;
1799 static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1801 return st->TileBelongsToRailStation(tile);
1804 static void MakeRailStationAreaSmaller(BaseStation *st)
1806 st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1809 static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1811 return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1814 static void MakeShipStationAreaSmaller(Station *st)
1816 st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1817 UpdateStationDockingTiles(st);
1820 static bool TileBelongsToRoadWaypointStation(BaseStation *st, TileIndex tile)
1822 return IsRoadWaypointTile(tile) && GetStationIndex(tile) == st->index;
1825 void MakeRoadWaypointStationAreaSmaller(BaseStation *st, TileArea &road_waypoint_area)
1827 road_waypoint_area = MakeStationAreaSmaller(st, road_waypoint_area, TileBelongsToRoadWaypointStation);
1831 * Remove a number of tiles from any rail station within the area.
1832 * @param ta the area to clear station tile from.
1833 * @param affected_stations the stations affected.
1834 * @param flags the command flags.
1835 * @param removal_cost the cost for removing the tile, including the rail.
1836 * @param keep_rail whether to keep the rail of the station.
1837 * @tparam T the type of station to remove.
1838 * @return the number of cleared tiles or an error.
1840 template <class T>
1841 CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1843 /* Count of the number of tiles removed */
1844 int quantity = 0;
1845 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1846 /* Accumulator for the errors seen during clearing. If no errors happen,
1847 * and the quantity is 0 there is no station. Otherwise it will be one
1848 * of the other error that got accumulated. */
1849 CommandCost error;
1851 /* Do the action for every tile into the area */
1852 for (TileIndex tile : ta) {
1853 /* Make sure the specified tile is a rail station */
1854 if (!HasStationTileRail(tile)) continue;
1856 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1857 CommandCost ret = EnsureNoVehicleOnGround(tile);
1858 error.AddCost(ret);
1859 if (ret.Failed()) continue;
1861 /* Check ownership of station */
1862 T *st = T::GetByTile(tile);
1863 if (st == nullptr) continue;
1865 if (_current_company != OWNER_WATER) {
1866 ret = CheckOwnership(st->owner);
1867 error.AddCost(ret);
1868 if (ret.Failed()) continue;
1871 Train *v = nullptr;
1872 Track track = GetRailStationTrack(tile);
1873 if (HasStationReservation(tile)) {
1874 v = GetTrainForReservation(tile, track);
1875 if (v != nullptr) {
1876 CommandCost ret = CheckTrainReservationPreventsTrackModification(v);
1877 error.AddCost(ret);
1878 if (ret.Failed()) continue;
1879 if (flags & DC_EXEC) FreeTrainReservation(v);
1883 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1884 quantity++;
1886 if (keep_rail || IsStationTileBlocked(tile)) {
1887 /* Don't refund the 'steel' of the track when we keep the
1888 * rail, or when the tile didn't have any rail at all. */
1889 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1892 if (flags & DC_EXEC) {
1893 bool already_affected = include(affected_stations, st);
1894 if (!already_affected) ZoningMarkDirtyStationCoverageArea(st);
1896 /* read variables before the station tile is removed */
1897 uint specindex = GetCustomStationSpecIndex(tile);
1898 Owner owner = GetTileOwner(tile);
1899 RailType rt = GetRailType(tile);
1901 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1902 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1904 DoClearSquare(tile);
1905 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1906 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1907 Company::Get(owner)->infrastructure.station--;
1908 DirtyCompanyInfrastructureWindows(owner);
1910 st->rect.AfterRemoveTile(st, tile);
1911 AddTrackToSignalBuffer(tile, track, owner);
1912 YapfNotifyTrackLayoutChange(tile, track);
1914 DeallocateSpecFromStation(st, specindex);
1916 if (v != nullptr) RestoreTrainReservation(v);
1920 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1922 for (T *st : affected_stations) {
1924 /* now we need to make the "spanned" area of the railway station smaller
1925 * if we deleted something at the edges.
1926 * we also need to adjust train_tile. */
1927 MakeRailStationAreaSmaller(st);
1928 UpdateStationSignCoord(st);
1930 /* if we deleted the whole station, delete the train facility. */
1931 if (st->train_station.tile == INVALID_TILE) {
1932 st->facilities &= ~FACIL_TRAIN;
1933 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
1934 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1935 st->UpdateVirtCoord();
1936 DeleteStationIfEmpty(st);
1940 total_cost.AddCost(quantity * removal_cost);
1941 return total_cost;
1945 * Remove a single tile from a rail station.
1946 * This allows for custom-built station with holes and weird layouts
1947 * @param start tile of station piece to remove
1948 * @param flags operation to perform
1949 * @param p1 start_tile
1950 * @param p2 various bitstuffed elements
1951 * - p2 = bit 0 - if set keep the rail
1952 * @param text unused
1953 * @return the cost of this operation or an error
1955 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32_t p1, uint32_t p2, const char *text)
1957 TileIndex end = p1 == 0 ? start : p1;
1958 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1960 TileArea ta(start, end);
1961 std::vector<Station *> affected_stations;
1963 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
1964 if (ret.Failed()) return ret;
1966 /* Do all station specific functions here. */
1967 for (Station *st : affected_stations) {
1969 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1970 st->MarkTilesDirty(false);
1971 st->RecomputeCatchment();
1974 /* Now apply the rail cost to the number that we deleted */
1975 return ret;
1979 * Remove a single tile from a waypoint.
1980 * This allows for custom-built waypoint with holes and weird layouts
1981 * @param start tile of waypoint piece to remove
1982 * @param flags operation to perform
1983 * @param p1 start_tile
1984 * @param p2 various bitstuffed elements
1985 * - p2 = bit 0 - if set keep the rail
1986 * @param text unused
1987 * @return the cost of this operation or an error
1989 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32_t p1, uint32_t p2, const char *text)
1991 TileIndex end = p1 == 0 ? start : p1;
1992 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1994 TileArea ta(start, end);
1995 std::vector<Waypoint *> affected_stations;
1997 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
2002 * Remove a rail station/waypoint
2003 * @param st The station/waypoint to remove the rail part from
2004 * @param flags operation to perform
2005 * @param removal_cost the cost for removing a tile
2006 * @tparam T the type of station to remove
2007 * @return cost or failure of operation
2009 template <class T>
2010 CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
2012 /* Current company owns the station? */
2013 if (_current_company != OWNER_WATER) {
2014 CommandCost ret = CheckOwnership(st->owner);
2015 if (ret.Failed()) return ret;
2018 /* determine width and height of platforms */
2019 TileArea ta = st->train_station;
2021 assert(ta.w != 0 && ta.h != 0);
2023 CommandCost cost(EXPENSES_CONSTRUCTION);
2024 /* clear all areas of the station */
2025 for (TileIndex tile : ta) {
2026 /* only remove tiles that are actually train station tiles */
2027 if (st->TileBelongsToRailStation(tile)) {
2028 std::vector<T*> affected_stations; // dummy
2029 CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
2030 if (ret.Failed()) return ret;
2031 cost.AddCost(ret);
2035 return cost;
2039 * Remove a rail station
2040 * @param tile Tile of the station.
2041 * @param flags operation to perform
2042 * @return cost or failure of operation
2044 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
2046 /* if there is flooding, remove platforms tile by tile */
2047 if (_current_company == OWNER_WATER) {
2048 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
2051 Station *st = Station::GetByTile(tile);
2053 if (flags & DC_EXEC) ZoningMarkDirtyStationCoverageArea(st);
2055 CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
2057 if (flags & DC_EXEC) st->RecomputeCatchment();
2059 return cost;
2063 * Remove a rail waypoint
2064 * @param tile Tile of the waypoint.
2065 * @param flags operation to perform
2066 * @return cost or failure of operation
2068 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
2070 /* if there is flooding, remove waypoints tile by tile */
2071 if (_current_company == OWNER_WATER) {
2072 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
2075 return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
2080 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
2081 * @param st The Station to do the whole procedure for
2082 * @return a pointer to where to link a new RoadStop*
2084 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
2086 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
2088 if (*primary_stop == nullptr) {
2089 /* we have no roadstop of the type yet, so write a "primary stop" */
2090 return primary_stop;
2091 } else {
2092 /* there are stops already, so append to the end of the list */
2093 RoadStop *stop = *primary_stop;
2094 while (stop->next != nullptr) stop = stop->next;
2095 return &stop->next;
2099 CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
2102 * Find a nearby station that joins this road stop.
2103 * @param existing_stop an existing road stop we build over
2104 * @param station_to_join the station to join to
2105 * @param adjacent whether adjacent stations are allowed
2106 * @param ta the area of the newly build station
2107 * @param st 'return' pointer for the found station
2108 * @return command cost with the error or 'okay'
2110 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
2112 return FindJoiningBaseStation<Station>(existing_stop, station_to_join, adjacent, ta, st, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST, [](Station *st) -> bool { return true; });
2116 * Build a bus or truck stop.
2117 * @param tile Northernmost tile of the stop.
2118 * @param flags Operation to perform.
2119 * @param p1 bit 0..7: Width of the road stop.
2120 * bit 8..15: Length of the road stop.
2121 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
2122 * bit 1: 0 For normal stops, 1 for drive-through.
2123 * bit 2: Allow stations directly adjacent to other stations.
2124 * bit 3..4: Entrance direction (#DiagDirection) for normal stops.
2125 * bit 3: #Axis of the road for drive-through stops.
2126 * bit 5..10: The roadtype.
2127 * bit 16..31: Station ID to join (NEW_STATION if build new one).
2128 * @param p3 bit 0..15: Roadstop class.
2129 * bit 16..31: Roadstopspec index.
2130 * @param text Unused.
2131 * @return The cost of this operation or an error.
2133 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32_t p1, uint32_t p2, uint64_t p3, const char *text, const CommandAuxiliaryBase *aux_data)
2135 bool type = HasBit(p2, 0);
2136 bool is_drive_through = HasBit(p2, 1);
2137 RoadType rt = Extract<RoadType, 5, 6>(p2);
2138 if (!ValParamRoadType(rt)) return CMD_ERROR;
2139 StationID station_to_join = GB(p2, 16, 16);
2140 bool reuse = (station_to_join != NEW_STATION);
2141 if (!reuse) station_to_join = INVALID_STATION;
2142 bool distant_join = (station_to_join != INVALID_STATION);
2144 uint8_t width = (uint8_t)GB(p1, 0, 8);
2145 uint8_t length = (uint8_t)GB(p1, 8, 8);
2147 RoadStopClassID spec_class = Extract<RoadStopClassID, 0, 16>(p3);
2148 uint16_t spec_index = GB(p3, 16, 16);
2150 /* Check if the given station class is valid */
2151 if (static_cast<uint>(spec_class) >= RoadStopClass::GetClassCount()) return CMD_ERROR;
2152 const RoadStopClass *cls = RoadStopClass::Get(spec_class);
2153 if (IsWaypointClass(*cls)) return CMD_ERROR;
2154 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
2156 const RoadStopSpec *roadstopspec = cls->GetSpec(spec_index);
2157 if (roadstopspec != nullptr) {
2158 if (type && roadstopspec->stop_type != ROADSTOPTYPE_FREIGHT && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
2159 if (!type && roadstopspec->stop_type != ROADSTOPTYPE_PASSENGER && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
2160 if (!is_drive_through && HasBit(roadstopspec->flags, RSF_DRIVE_THROUGH_ONLY)) return CMD_ERROR;
2163 /* Check if the requested road stop is too big */
2164 if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
2165 /* Check for incorrect width / length. */
2166 if (width == 0 || length == 0) return CMD_ERROR;
2167 /* Check if the first tile and the last tile are valid */
2168 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
2170 TileArea roadstop_area(tile, width, length);
2172 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2174 /* Trams only have drive through stops */
2175 if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
2177 DiagDirection ddir;
2178 Axis axis;
2179 if (is_drive_through) {
2180 /* By definition axis is valid, due to there being 2 axes and reading 1 bit. */
2181 axis = Extract<Axis, 3, 1>(p2);
2182 ddir = AxisToDiagDir(axis);
2183 } else {
2184 /* By definition ddir is valid, due to there being 4 diagonal directions and reading 2 bits. */
2185 ddir = Extract<DiagDirection, 3, 2>(p2);
2186 axis = DiagDirToAxis(ddir);
2189 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2190 if (ret.Failed()) return ret;
2192 /* Total road stop cost. */
2193 Money unit_cost;
2194 if (roadstopspec != nullptr) {
2195 unit_cost = roadstopspec->GetBuildCost(type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS);
2196 } else {
2197 unit_cost = _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS];
2199 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * unit_cost);
2200 StationID est = INVALID_STATION;
2201 ret = CheckFlatLandRoadStop(roadstop_area, roadstopspec, flags, is_drive_through ? 5 << axis : 1 << ddir, is_drive_through, type ? STATION_TRUCK : STATION_BUS, axis, &est, rt, false);
2202 if (ret.Failed()) return ret;
2203 cost.AddCost(ret);
2205 Station *st = nullptr;
2206 ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 2), roadstop_area, &st);
2207 if (ret.Failed()) return ret;
2209 /* Check if this number of road stops can be allocated. */
2210 if (!RoadStop::CanAllocateItem(static_cast<size_t>(roadstop_area.w) * roadstop_area.h)) return CommandCost(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
2212 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
2213 if (ret.Failed()) return ret;
2215 /* Check if we can allocate a custom stationspec to this station */
2216 int specindex = AllocateRoadStopSpecToStation(roadstopspec, st, (flags & DC_EXEC) != 0);
2217 if (specindex == -1) return CommandCost(STR_ERROR_TOO_MANY_STATION_SPECS);
2219 if (roadstopspec != nullptr) {
2220 /* Perform NewGRF checks */
2222 /* Check if the road stop is buildable */
2223 if (HasBit(roadstopspec->callback_mask, CBM_ROAD_STOP_AVAIL)) {
2224 uint16_t cb_res = GetRoadStopCallback(CBID_STATION_AVAILABILITY, 0, 0, roadstopspec, nullptr, INVALID_TILE, rt, type ? STATION_TRUCK : STATION_BUS, 0);
2225 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(roadstopspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
2229 if (flags & DC_EXEC) {
2230 /* Check every tile in the area. */
2231 for (TileIndex cur_tile : roadstop_area) {
2232 /* Get existing road types and owners before any tile clearing */
2233 RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_ROAD) : INVALID_ROADTYPE;
2234 RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_TRAM) : INVALID_ROADTYPE;
2235 Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_ROAD) : _current_company;
2236 Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_TRAM) : _current_company;
2238 DisallowedRoadDirections drd = DRD_NONE;
2239 if (road_rt != INVALID_ROADTYPE) {
2240 if (IsNormalRoadTile(cur_tile)){
2241 drd = GetDisallowedRoadDirections(cur_tile);
2242 } else if (IsDriveThroughStopTile(cur_tile)) {
2243 drd = GetDriveThroughStopDisallowedRoadDirections(cur_tile);
2247 if (IsTileType(cur_tile, MP_STATION) && IsAnyRoadStop(cur_tile)) {
2248 RemoveRoadStop(cur_tile, flags, specindex);
2251 if (roadstopspec != nullptr) {
2252 /* Include this road stop spec's animation trigger bitmask
2253 * in the station's cached copy. */
2254 st->cached_roadstop_anim_triggers |= roadstopspec->animation.triggers;
2257 RoadStop *road_stop = new RoadStop(cur_tile);
2258 /* Insert into linked list of RoadStops. */
2259 RoadStop **currstop = FindRoadStopSpot(type, st);
2260 *currstop = road_stop;
2262 if (type) {
2263 st->truck_station.Add(cur_tile);
2264 } else {
2265 st->bus_station.Add(cur_tile);
2268 /* Initialize an empty station. */
2269 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
2271 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
2273 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
2274 if (is_drive_through) {
2275 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2276 * bits first. */
2277 if (IsNormalRoadTile(cur_tile)) {
2278 UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD)));
2279 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM)));
2282 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2283 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2285 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, (rs_type == ROADSTOP_BUS ? STATION_BUS : STATION_TRUCK), road_rt, tram_rt, axis);
2286 SetDriveThroughStopDisallowedRoadDirections(cur_tile, drd);
2287 road_stop->MakeDriveThrough();
2288 } else {
2289 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2290 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2291 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
2293 UpdateCompanyRoadInfrastructure(road_rt, road_owner, ROAD_STOP_TRACKBIT_FACTOR);
2294 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, ROAD_STOP_TRACKBIT_FACTOR);
2295 Company::Get(st->owner)->infrastructure.station++;
2297 SetCustomRoadStopSpecIndex(cur_tile, specindex);
2298 if (roadstopspec != nullptr) {
2299 st->SetRoadStopRandomBits(cur_tile, GB(Random(), 0, 8));
2300 TriggerRoadStopAnimation(st, cur_tile, SAT_BUILT);
2303 MarkTileDirtyByTile(cur_tile);
2304 UpdateRoadCachedOneWayStatesAroundTile(cur_tile);
2306 ZoningMarkDirtyStationCoverageArea(st);
2307 NotifyRoadLayoutChanged(true);
2309 if (st != nullptr) {
2310 st->AfterStationTileSetChange(true, type ? STATION_TRUCK: STATION_BUS);
2313 return cost;
2317 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
2319 /* Okay... we are a road vehicle on a drive through road stop.
2320 * But that road stop has just been removed, so we need to make
2321 * sure we are in a valid state... however, vehicles can also
2322 * turn on road stop tiles, so only clear the 'road stop' state
2323 * bits and only when the state was 'in road stop', otherwise
2324 * we'll end up clearing the turn around bits. */
2325 RoadVehicle *rv = RoadVehicle::From(v);
2326 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
2328 return nullptr;
2331 CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2333 Waypoint *wp = Waypoint::GetByTile(tile);
2335 if (_current_company != OWNER_WATER) {
2336 CommandCost ret = CheckOwnership(wp->owner);
2337 if (ret.Failed()) return ret;
2340 /* don't do the check for drive-through road stops when company bankrupts */
2341 if (!(flags & DC_BANKRUPT)) {
2342 CommandCost ret = EnsureNoVehicleOnGround(tile);
2343 if (ret.Failed()) return ret;
2346 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2348 if (flags & DC_EXEC) {
2349 /* Update company infrastructure counts. */
2350 for (RoadTramType rtt : _roadtramtypes) {
2351 RoadType rt = GetRoadType(tile, rtt);
2352 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2355 Company::Get(wp->owner)->infrastructure.station--;
2356 DirtyCompanyInfrastructureWindows(wp->owner);
2358 DeleteAnimatedTile(tile);
2360 uint specindex = GetCustomRoadStopSpecIndex(tile);
2362 DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile);
2364 DoClearSquare(tile);
2366 wp->rect.AfterRemoveTile(wp, tile);
2368 wp->RemoveRoadStopTileData(tile);
2369 if ((int)specindex != replacement_spec_index) DeallocateRoadStopSpecFromStation(wp, specindex);
2371 if (replacement_spec_index < 0) {
2372 MakeRoadWaypointStationAreaSmaller(wp, wp->road_waypoint_area);
2374 UpdateStationSignCoord(wp);
2376 /* if we deleted the whole waypoint, delete the road facility. */
2377 if (wp->road_waypoint_area.tile == INVALID_TILE) {
2378 wp->facilities &= ~(FACIL_BUS_STOP | FACIL_TRUCK_STOP);
2379 SetWindowWidgetDirty(WC_STATION_VIEW, wp->index, WID_SV_ROADVEHS);
2380 wp->UpdateVirtCoord();
2381 DeleteStationIfEmpty(wp);
2385 NotifyRoadLayoutChanged(false);
2388 return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(PR_CLEAR_STATION_TRUCK) : _price[PR_CLEAR_STATION_TRUCK]);
2392 * Remove a bus station/truck stop
2393 * @param tile TileIndex been queried
2394 * @param flags operation to perform
2395 * @param replacement_spec_index replacement spec index to avoid deallocating, if < 0, tile is not being replaced
2396 * @return cost or failure of operation
2398 CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2400 if (IsRoadWaypoint(tile)) {
2401 return RemoveRoadWaypointStop(tile, flags, replacement_spec_index);
2404 Station *st = Station::GetByTile(tile);
2406 if (_current_company != OWNER_WATER) {
2407 CommandCost ret = CheckOwnership(st->owner);
2408 if (ret.Failed()) return ret;
2411 bool is_truck = IsTruckStop(tile);
2413 RoadStop **primary_stop;
2414 RoadStop *cur_stop;
2415 if (is_truck) { // truck stop
2416 primary_stop = &st->truck_stops;
2417 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
2418 } else {
2419 primary_stop = &st->bus_stops;
2420 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
2423 assert(cur_stop != nullptr);
2425 /* don't do the check for drive-through road stops when company bankrupts */
2426 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
2427 /* remove the 'going through road stop' status from all vehicles on that tile */
2428 if (flags & DC_EXEC) FindVehicleOnPos(tile, VEH_ROAD, nullptr, &ClearRoadStopStatusEnum);
2429 } else {
2430 CommandCost ret = EnsureNoVehicleOnGround(tile);
2431 if (ret.Failed()) return ret;
2434 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2436 if (flags & DC_EXEC) {
2437 ZoningMarkDirtyStationCoverageArea(st);
2438 if (*primary_stop == cur_stop) {
2439 /* removed the first stop in the list */
2440 *primary_stop = cur_stop->next;
2441 /* removed the only stop? */
2442 if (*primary_stop == nullptr) {
2443 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
2444 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2446 } else {
2447 /* tell the predecessor in the list to skip this stop */
2448 RoadStop *pred = *primary_stop;
2449 while (pred->next != cur_stop) pred = pred->next;
2450 pred->next = cur_stop->next;
2453 /* Update company infrastructure counts. */
2454 for (RoadTramType rtt : _roadtramtypes) {
2455 RoadType rt = GetRoadType(tile, rtt);
2456 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2459 Company::Get(st->owner)->infrastructure.station--;
2460 DirtyCompanyInfrastructureWindows(st->owner);
2462 DeleteAnimatedTile(tile);
2464 uint specindex = GetCustomRoadStopSpecIndex(tile);
2466 DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile);
2468 if (IsDriveThroughStopTile(tile)) {
2469 /* Clears the tile for us */
2470 cur_stop->ClearDriveThrough();
2471 } else {
2472 DoClearSquare(tile);
2475 delete cur_stop;
2477 /* Make sure no vehicle is going to the old roadstop */
2478 for (RoadVehicle *v : RoadVehicle::IterateFrontOnly()) {
2479 if (v->current_order.IsType(OT_GOTO_STATION) && v->dest_tile == tile) {
2480 v->SetDestTile(v->GetOrderStationLocation(st->index));
2484 st->rect.AfterRemoveTile(st, tile);
2486 if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? STATION_TRUCK: STATION_BUS);
2488 st->RemoveRoadStopTileData(tile);
2489 if ((int)specindex != replacement_spec_index) DeallocateRoadStopSpecFromStation(st, specindex);
2491 /* Update the tile area of the truck/bus stop */
2492 if (is_truck) {
2493 st->truck_station.Clear();
2494 for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2495 } else {
2496 st->bus_station.Clear();
2497 for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2500 NotifyRoadLayoutChanged(false);
2503 Price category = is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS;
2504 return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(category) : _price[category]);
2508 * Remove bus or truck stops.
2509 * @param tile Northernmost tile of the removal area.
2510 * @param flags Operation to perform.
2511 * @param p1 bit 0..7: Width of the removal area.
2512 * bit 8..15: Height of the removal area.
2513 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
2514 * @param p2 bit 1: 0 to keep roads of all drive-through stops, 1 to remove them.
2515 * @param p2 bit 2: 0 for bus/truck stops, 1 for road waypoints.
2516 * @param text Unused.
2517 * @return The cost of this operation or an error.
2519 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32_t p1, uint32_t p2, const char *text)
2521 uint8_t width = (uint8_t)GB(p1, 0, 8);
2522 uint8_t height = (uint8_t)GB(p1, 8, 8);
2523 bool keep_drive_through_roads = !HasBit(p2, 1) || HasBit(p2, 2);
2525 /* Check for incorrect width / height. */
2526 if (width == 0 || height == 0) return CMD_ERROR;
2527 /* Check if the first tile and the last tile are valid */
2528 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2529 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2530 if (!keep_drive_through_roads && (flags & DC_BANKRUPT)) return CMD_ERROR;
2532 TileArea roadstop_area(tile, width, height);
2534 CommandCost cost(EXPENSES_CONSTRUCTION);
2535 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2536 bool had_success = false;
2538 for (TileIndex cur_tile : roadstop_area) {
2539 if (HasBit(p2, 2)) {
2540 /* Make sure the specified tile is a road waypoint */
2541 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadWaypoint(cur_tile)) continue;
2542 } else {
2543 /* Make sure the specified tile is a road stop of the correct type */
2544 if (!IsTileType(cur_tile, MP_STATION) || !IsStationRoadStop(cur_tile) || (uint32_t)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
2547 /* Save information on to-be-restored roads before the stop is removed. */
2548 RoadBits road_bits = ROAD_NONE;
2549 RoadType road_type[] = { INVALID_ROADTYPE, INVALID_ROADTYPE };
2550 Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
2551 DisallowedRoadDirections drd = DRD_NONE;
2552 if (IsDriveThroughStopTile(cur_tile)) {
2553 for (RoadTramType rtt : _roadtramtypes) {
2554 road_type[rtt] = GetRoadType(cur_tile, rtt);
2555 if (road_type[rtt] == INVALID_ROADTYPE) continue;
2556 road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2557 /* If we don't want to preserve our roads then restore only roads of others. */
2558 if (!keep_drive_through_roads && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2560 road_bits = AxisToRoadBits(GetDriveThroughStopAxis(cur_tile));
2561 drd = GetDriveThroughStopDisallowedRoadDirections(cur_tile);
2564 CommandCost ret = RemoveRoadStop(cur_tile, flags);
2565 if (ret.Failed()) {
2566 last_error = ret;
2567 continue;
2569 cost.AddCost(ret);
2570 had_success = true;
2572 /* Restore roads. */
2573 if ((flags & DC_EXEC) && (road_type[RTT_ROAD] != INVALID_ROADTYPE || road_type[RTT_TRAM] != INVALID_ROADTYPE)) {
2574 MakeRoadNormal(cur_tile, road_bits, road_type[RTT_ROAD], road_type[RTT_TRAM], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2575 road_owner[RTT_ROAD], road_owner[RTT_TRAM]);
2576 if (drd != DRD_NONE) SetDisallowedRoadDirections(cur_tile, drd);
2578 /* Update company infrastructure counts. */
2579 int count = CountBits(road_bits);
2580 UpdateCompanyRoadInfrastructure(road_type[RTT_ROAD], road_owner[RTT_ROAD], count);
2581 UpdateCompanyRoadInfrastructure(road_type[RTT_TRAM], road_owner[RTT_TRAM], count);
2583 if (flags & DC_EXEC) UpdateRoadCachedOneWayStatesAroundTile(cur_tile);
2586 return had_success ? cost : last_error;
2590 * Get a possible noise reduction factor based on distance from town center.
2591 * The further you get, the less noise you generate.
2592 * So all those folks at city council can now happily slee... work in their offices
2593 * @param as airport information
2594 * @param distance minimum distance between town and airport
2595 * @return the noise that will be generated, according to distance
2597 uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2599 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2600 * So no need to go any further*/
2601 if (as->noise_level < 2) return as->noise_level;
2603 auto tolerance = _settings_game.difficulty.town_council_tolerance;
2604 if (tolerance == TOWN_COUNCIL_PERMISSIVE) tolerance = TOWN_COUNCIL_LENIENT;
2606 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2607 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2608 * Basically, it says that the less tolerant a town is, the bigger the distance before
2609 * an actual decrease can be granted */
2610 uint8_t town_tolerance_distance = 8 + (tolerance * 4);
2612 /* now, we want to have the distance segmented using the distance judged bareable by town
2613 * This will give us the coefficient of reduction the distance provides. */
2614 uint noise_reduction = distance / town_tolerance_distance;
2616 /* If the noise reduction equals the airport noise itself, don't give it for free.
2617 * Otherwise, simply reduce the airport's level. */
2618 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2622 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2623 * If two towns have the same distance, town with lower index is returned.
2624 * @param as airport's description
2625 * @param rotation airport's rotation
2626 * @param tile origin tile (top corner of the airport)
2627 * @param it An iterator over all airport tiles (consumed)
2628 * @param[out] mindist Minimum distance to town
2629 * @return nearest town to airport
2631 Town *AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
2633 assert(Town::GetNumItems() > 0);
2635 Town *nearest = nullptr;
2637 auto width = as->size_x;
2638 auto height = as->size_y;
2639 if (rotation == DIR_E || rotation == DIR_W) std::swap(width, height);
2641 uint perimeter_min_x = TileX(tile);
2642 uint perimeter_min_y = TileY(tile);
2643 uint perimeter_max_x = perimeter_min_x + width - 1;
2644 uint perimeter_max_y = perimeter_min_y + height - 1;
2646 mindist = UINT_MAX - 1; // prevent overflow
2648 for (TileIndex cur_tile = *it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2649 assert(IsInsideBS(TileX(cur_tile), perimeter_min_x, width));
2650 assert(IsInsideBS(TileY(cur_tile), perimeter_min_y, height));
2651 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) {
2652 Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2653 if (t == nullptr) continue;
2655 uint dist = DistanceManhattan(t->xy, cur_tile);
2656 if (dist == mindist && t->index < nearest->index) nearest = t;
2657 if (dist < mindist) {
2658 nearest = t;
2659 mindist = dist;
2664 return nearest;
2668 * Finds the town nearest to given existing airport. Based on minimal manhattan distance to any airport's tile.
2669 * If two towns have the same distance, town with lower index is returned.
2670 * @param station existing station with airport
2671 * @param[out] mindist Minimum distance to town
2672 * @return nearest town to airport
2674 static Town *AirportGetNearestTown(const Station *st, uint &mindist)
2676 return AirportGetNearestTown(st->airport.GetSpec(), st->airport.rotation, st->airport.tile, AirportTileIterator(st), mindist);
2680 /** Recalculate the noise generated by the airports of each town */
2681 void UpdateAirportsNoise()
2683 if (_town_noise_no_update) return;
2685 for (Town *t : Town::Iterate()) t->noise_reached = 0;
2687 for (const Station *st : Station::Iterate()) {
2688 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2689 uint dist;
2690 Town *nearest = AirportGetNearestTown(st, dist);
2691 nearest->noise_reached += GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2698 * Checks if an airport can be removed (no aircraft on it or landing)
2699 * @param st Station whose airport is to be removed
2700 * @param flags Operation to perform
2701 * @return Cost or failure of operation
2703 static CommandCost CanRemoveAirport(Station *st, DoCommandFlag flags)
2705 for (const Aircraft *a : Aircraft::Iterate()) {
2706 if (!a->IsNormalAircraft()) continue;
2707 if (a->targetairport == st->index && a->state != FLYING)
2708 return CommandCost(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2711 CommandCost cost(EXPENSES_CONSTRUCTION);
2713 for (TileIndex tile_cur : st->airport) {
2714 if (!st->TileBelongsToAirport(tile_cur)) continue;
2716 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2717 if (ret.Failed()) return ret;
2719 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2722 return cost;
2727 * Place an Airport.
2728 * @param tile tile where airport will be built
2729 * @param flags operation to perform
2730 * @param p1
2731 * - p1 = (bit 0- 7) - airport type, @see airport.h
2732 * - p1 = (bit 8-15) - airport layout
2733 * @param p2 various bitstuffed elements
2734 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2735 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2736 * @param text unused
2737 * @return the cost of this operation or an error
2739 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32_t p1, uint32_t p2, const char *text)
2741 StationID station_to_join = GB(p2, 16, 16);
2742 bool reuse = (station_to_join != NEW_STATION);
2743 if (!reuse) station_to_join = INVALID_STATION;
2744 bool distant_join = (station_to_join != INVALID_STATION);
2745 uint8_t airport_type = GB(p1, 0, 8);
2746 uint8_t layout = GB(p1, 8, 8);
2748 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2750 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2752 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2753 if (ret.Failed()) return ret;
2755 /* Check if a valid, buildable airport was chosen for construction */
2756 const AirportSpec *as = AirportSpec::Get(airport_type);
2757 if (!as->IsAvailable() || layout >= as->layouts.size()) return CMD_ERROR;
2758 if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2760 Direction rotation = as->layouts[layout].rotation;
2761 int w = as->size_x;
2762 int h = as->size_y;
2763 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2764 TileArea airport_area = TileArea(tile, w, h);
2766 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2767 return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
2770 StationID est = INVALID_STATION;
2771 AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile);
2772 CommandCost cost = CheckFlatLandAirport(iter, flags, &est);
2773 if (cost.Failed()) return cost;
2775 Station *st = nullptr;
2776 ret = FindJoiningStation(est, station_to_join, HasBit(p2, 0), airport_area, &st, STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
2777 if (ret.Failed()) return ret;
2779 /* Distant join */
2780 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2782 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2783 if (ret.Failed()) return ret;
2785 /* action to be performed */
2786 enum {
2787 AIRPORT_NEW, // airport is a new station
2788 AIRPORT_ADD, // add an airport to an existing station
2789 AIRPORT_UPGRADE, // upgrade the airport in a station
2790 } action =
2791 (est != INVALID_STATION) ? AIRPORT_UPGRADE :
2792 (st != nullptr) ? AIRPORT_ADD : AIRPORT_NEW;
2794 if (action == AIRPORT_ADD && st->airport.tile != INVALID_TILE) {
2795 return CommandCost(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2798 if (action == AIRPORT_UPGRADE && airport_type == st->airport.type && layout == st->airport.layout && st->airport.tile == tile) {
2799 return CommandCost(STR_ERROR_ALREADY_BUILT);
2802 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2803 AirportTileTableIterator nearest_town_iter = iter;
2804 uint dist;
2805 Town *nearest = AirportGetNearestTown(as, rotation, tile, std::move(nearest_town_iter), dist);
2806 uint newnoise_level = nearest->noise_reached + GetAirportNoiseLevelForDistance(as, dist);
2808 if (action == AIRPORT_UPGRADE) {
2809 uint old_dist;
2810 Town *old_nearest = AirportGetNearestTown(st, old_dist);
2811 if (old_nearest == nearest) {
2812 newnoise_level -= GetAirportNoiseLevelForDistance(st->airport.GetSpec(), old_dist);
2816 /* Check if local auth would allow a new airport */
2817 StringID authority_refuse_message = STR_NULL;
2818 Town *authority_refuse_town = nullptr;
2820 if (_settings_game.economy.station_noise_level) {
2821 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2822 if (newnoise_level > nearest->MaxTownNoise()) {
2823 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2824 authority_refuse_town = nearest;
2826 } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE && action != AIRPORT_UPGRADE) {
2827 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2828 uint num = 0;
2829 for (const Station *st : Station::Iterate()) {
2830 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2832 if (num >= 2) {
2833 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2834 authority_refuse_town = t;
2838 if (authority_refuse_message != STR_NULL) {
2839 SetDParam(0, authority_refuse_town->index);
2840 return CommandCost(authority_refuse_message);
2843 if (action == AIRPORT_UPGRADE) {
2844 /* check that the old airport can be removed */
2845 CommandCost r = CanRemoveAirport(st, flags);
2846 if (r.Failed()) return r;
2847 cost.AddCost(r);
2850 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2851 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2854 if (flags & DC_EXEC) {
2855 if (action == AIRPORT_UPGRADE) {
2856 /* delete old airport if upgrading */
2858 ZoningMarkDirtyStationCoverageArea(st);
2860 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2861 TileIndex tile_cur = st->airport.GetHangarTile(i);
2862 OrderBackup::Reset(tile_cur, false);
2863 CloseWindowById(WC_VEHICLE_DEPOT, tile_cur);
2866 uint old_dist;
2867 Town *old_nearest = AirportGetNearestTown(st, old_dist);
2869 if (old_nearest != nearest) {
2870 old_nearest->noise_reached -= GetAirportNoiseLevelForDistance(st->airport.GetSpec(), old_dist);
2871 if (_settings_game.economy.station_noise_level) {
2872 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2876 for (TileIndex tile_cur : st->airport) {
2877 DeleteAnimatedTile(tile_cur);
2878 DoClearSquare(tile_cur);
2879 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2882 st->rect.AfterRemoveRect(st, st->airport);
2883 st->airport.Clear();
2886 /* Always add the noise, so there will be no need to recalculate when option toggles */
2887 nearest->noise_reached = newnoise_level;
2889 st->AddFacility(FACIL_AIRPORT, tile);
2890 st->airport.type = airport_type;
2891 st->airport.layout = layout;
2892 st->airport.flags = 0;
2893 st->airport.rotation = rotation;
2895 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2897 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2898 MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2899 SetStationTileRandomBits(iter, GB(Random(), 0, 4));
2900 st->airport.Add(iter);
2902 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
2905 /* Only call the animation trigger after all tiles have been built */
2906 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2907 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2910 if (action != AIRPORT_NEW) UpdateAirplanesOnNewStation(st);
2912 if (action == AIRPORT_UPGRADE) {
2913 UpdateStationSignCoord(st);
2914 } else {
2915 Company::Get(st->owner)->infrastructure.airport++;
2918 st->AfterStationTileSetChange(true, STATION_AIRPORT);
2919 ZoningMarkDirtyStationCoverageArea(st);
2920 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2922 if (_settings_game.economy.station_noise_level) {
2923 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2927 return cost;
2931 * Remove an airport
2932 * @param tile TileIndex been queried
2933 * @param flags operation to perform
2934 * @return cost or failure of operation
2936 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2938 Station *st = Station::GetByTile(tile);
2940 if (_current_company != OWNER_WATER) {
2941 CommandCost ret = CheckOwnership(st->owner);
2942 if (ret.Failed()) return ret;
2945 CommandCost cost = CanRemoveAirport(st, flags);
2946 if (cost.Failed()) return cost;
2948 if (flags & DC_EXEC) {
2949 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2950 TileIndex tile_cur = st->airport.GetHangarTile(i);
2951 OrderBackup::Reset(tile_cur, false);
2952 CloseWindowById(WC_VEHICLE_DEPOT, tile_cur);
2955 ZoningMarkDirtyStationCoverageArea(st);
2956 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2957 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2958 * need of recalculation */
2959 uint dist;
2960 Town *nearest = AirportGetNearestTown(st, dist);
2961 nearest->noise_reached -= GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2963 if (_settings_game.economy.station_noise_level) {
2964 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2967 for (TileIndex tile_cur : st->airport) {
2968 if (!st->TileBelongsToAirport(tile_cur)) continue;
2970 DeleteAnimatedTile(tile_cur);
2971 DoClearSquare(tile_cur);
2972 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2975 /* Clear the persistent storage. */
2976 delete st->airport.psa;
2978 st->rect.AfterRemoveRect(st, st->airport);
2980 st->airport.Clear();
2981 st->facilities &= ~FACIL_AIRPORT;
2982 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2984 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2986 Company::Get(st->owner)->infrastructure.airport--;
2988 st->AfterStationTileSetChange(false, STATION_AIRPORT);
2990 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2993 return cost;
2997 * Open/close an airport to incoming aircraft.
2998 * @param tile Unused.
2999 * @param flags Operation to perform.
3000 * @param p1 Station ID of the airport.
3001 * @param p2 Unused.
3002 * @param text unused
3003 * @return the cost of this operation or an error
3005 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32_t p1, uint32_t p2, const char *text)
3007 if (!Station::IsValidID(p1)) return CMD_ERROR;
3008 Station *st = Station::Get(p1);
3010 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
3012 CommandCost ret = CheckOwnership(st->owner);
3013 if (ret.Failed()) return ret;
3015 if (flags & DC_EXEC) {
3016 st->airport.flags ^= AIRPORT_CLOSED_block;
3017 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
3019 return CommandCost();
3023 * Tests whether the company's vehicles have this station in orders
3024 * @param station station ID
3025 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
3026 * @param company company ID
3028 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
3030 bool found = false;
3031 IterateOrderRefcountMapForDestinationID(station, [&](CompanyID cid, OrderType order_type, VehicleType veh_type, uint32_t refcount) {
3032 if ((cid == company) == include_company) {
3033 if (order_type == OT_GOTO_STATION || order_type == OT_GOTO_WAYPOINT) {
3034 found = true;
3035 return false;
3038 return true;
3040 return found;
3043 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
3044 {-1, 0},
3045 { 0, 0},
3046 { 0, 0},
3047 { 0, -1}
3049 static const uint8_t _dock_w_chk[4] = { 2, 1, 2, 1 };
3050 static const uint8_t _dock_h_chk[4] = { 1, 2, 1, 2 };
3053 * Build a dock/haven.
3054 * @param tile tile where dock will be built
3055 * @param flags operation to perform
3056 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
3057 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
3058 * @param text unused
3059 * @return the cost of this operation or an error
3061 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32_t p1, uint32_t p2, const char *text)
3063 StationID station_to_join = GB(p2, 16, 16);
3064 bool reuse = (station_to_join != NEW_STATION);
3065 if (!reuse) station_to_join = INVALID_STATION;
3066 bool distant_join = (station_to_join != INVALID_STATION);
3068 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
3070 TileIndex slope_tile = tile;
3072 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(slope_tile));
3073 if (direction == INVALID_DIAGDIR) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
3074 direction = ReverseDiagDir(direction);
3076 TileIndex flat_tile = slope_tile + TileOffsByDiagDir(direction);
3078 /* Docks cannot be placed on rapids */
3079 if (HasTileWaterGround(slope_tile)) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
3081 CommandCost ret = CheckIfAuthorityAllowsNewStation(slope_tile, flags);
3082 if (ret.Failed()) return ret;
3084 if (IsBridgeAbove(slope_tile) && !_settings_game.construction.allow_docks_under_bridges) return CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
3086 CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
3087 ret = DoCommand(slope_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3088 if (ret.Failed()) return ret;
3089 cost.AddCost(ret);
3091 if (!HasTileWaterGround(flat_tile) || !IsTileFlat(flat_tile)) {
3092 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
3095 if (IsBridgeAbove(flat_tile) && !_settings_game.construction.allow_docks_under_bridges) return CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
3097 /* Get the water class of the water tile before it is cleared.*/
3098 WaterClass wc = GetWaterClass(flat_tile);
3100 bool add_cost = !IsWaterTile(flat_tile);
3101 ret = DoCommand(flat_tile, 0, 0, flags | DC_ALLOW_REMOVE_WATER, CMD_LANDSCAPE_CLEAR);
3102 if (ret.Failed()) return ret;
3103 if (add_cost) cost.AddCost(ret);
3105 TileIndex adjacent_tile = flat_tile + TileOffsByDiagDir(direction);
3106 if (!IsTileType(adjacent_tile, MP_WATER) || !IsTileFlat(adjacent_tile)) {
3107 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
3110 TileArea dock_area = TileArea(slope_tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
3111 _dock_w_chk[direction], _dock_h_chk[direction]);
3113 /* middle */
3114 Station *st = nullptr;
3115 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
3116 if (ret.Failed()) return ret;
3118 /* Distant join */
3119 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
3121 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
3122 if (ret.Failed()) return ret;
3124 if (flags & DC_EXEC) {
3125 st->ship_station.Add(tile);
3126 st->ship_station.Add(flat_tile);
3127 st->AddFacility(FACIL_DOCK, tile);
3129 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
3131 /* If the water part of the dock is on a canal, update infrastructure counts.
3132 * This is needed as we've cleared that tile before.
3133 * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
3134 * See: MakeWaterKeepingClass() */
3135 if (wc == WATER_CLASS_CANAL && !(HasTileWaterClass(flat_tile) && GetWaterClass(flat_tile) == WATER_CLASS_CANAL && IsTileOwner(flat_tile, _current_company))) {
3136 Company::Get(st->owner)->infrastructure.water++;
3138 Company::Get(st->owner)->infrastructure.station += 2;
3140 MakeDock(tile, st->owner, st->index, direction, wc);
3141 UpdateStationDockingTiles(st);
3143 st->AfterStationTileSetChange(true, STATION_DOCK);
3144 ZoningMarkDirtyStationCoverageArea(st);
3147 return cost;
3150 void RemoveDockingTile(TileIndex t)
3152 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
3153 TileIndex tile = t + TileOffsByDiagDir(d);
3154 if (!IsValidTile(tile)) continue;
3156 if (IsTileType(tile, MP_STATION)) {
3157 Station *st = Station::GetByTile(tile);
3158 if (st != nullptr) UpdateStationDockingTiles(st);
3159 } else if (IsTileType(tile, MP_INDUSTRY)) {
3160 Station *neutral = Industry::GetByTile(tile)->neutral_station;
3161 if (neutral != nullptr) UpdateStationDockingTiles(neutral);
3167 * Clear docking tile status from tiles around a removed dock, if the tile has
3168 * no neighbours which would keep it as a docking tile.
3169 * @param tile Ex-dock tile to check.
3171 void ClearDockingTilesCheckingNeighbours(TileIndex tile)
3173 assert(IsValidTile(tile));
3175 /* Clear and maybe re-set docking tile */
3176 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
3177 TileIndex docking_tile = tile + TileOffsByDiagDir(d);
3178 if (!IsValidTile(docking_tile)) continue;
3180 if (IsPossibleDockingTile(docking_tile)) {
3181 SetDockingTile(docking_tile, false);
3182 CheckForDockingTile(docking_tile);
3188 * Find the part of a dock that is land-based
3189 * @param t Dock tile to find land part of
3190 * @return tile of land part of dock
3192 static TileIndex FindDockLandPart(TileIndex t)
3194 assert(IsDockTile(t));
3196 StationGfx gfx = GetStationGfx(t);
3197 if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
3199 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
3200 TileIndex tile = t + TileOffsByDiagDir(d);
3201 if (!IsValidTile(tile)) continue;
3202 if (!IsDockTile(tile)) continue;
3203 if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
3206 return INVALID_TILE;
3210 * Remove a dock
3211 * @param tile TileIndex been queried
3212 * @param flags operation to perform
3213 * @return cost or failure of operation
3215 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
3217 Station *st = Station::GetByTile(tile);
3218 CommandCost ret = CheckOwnership(st->owner);
3219 if (ret.Failed()) return ret;
3221 if (!IsDockTile(tile)) return CMD_ERROR;
3223 TileIndex tile1 = FindDockLandPart(tile);
3224 if (tile1 == INVALID_TILE) return CMD_ERROR;
3225 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
3227 ret = EnsureNoVehicleOnGround(tile1);
3228 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
3229 if (ret.Failed()) return ret;
3231 if (flags & DC_EXEC) {
3232 ZoningMarkDirtyStationCoverageArea(st);
3234 DoClearSquare(tile1);
3235 MarkTileDirtyByTile(tile1);
3236 MakeWaterKeepingClass(tile2, st->owner);
3238 st->rect.AfterRemoveTile(st, tile1);
3239 st->rect.AfterRemoveTile(st, tile2);
3241 MakeShipStationAreaSmaller(st);
3242 if (st->ship_station.tile == INVALID_TILE) {
3243 st->ship_station.Clear();
3244 st->docking_station.Clear();
3245 st->docking_tiles.clear();
3246 st->facilities &= ~FACIL_DOCK;
3247 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
3250 Company::Get(st->owner)->infrastructure.station -= 2;
3252 st->AfterStationTileSetChange(false, STATION_DOCK);
3254 ClearDockingTilesCheckingNeighbours(tile1);
3255 ClearDockingTilesCheckingNeighbours(tile2);
3257 for (Ship *s : Ship::IterateFrontOnly()) {
3258 /* Find all ships going to our dock. */
3259 if (s->current_order.GetDestination() != st->index) {
3260 continue;
3263 /* Find ships that are marked as "loading" but are no longer on a
3264 * docking tile. Force them to leave the station (as they were loading
3265 * on the removed dock). */
3266 if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
3267 s->LeaveStation();
3270 /* If we no longer have a dock, mark the order as invalid and send
3271 * the ship to the next order (or, if there is none, make it
3272 * wander the world). */
3273 if (s->current_order.IsType(OT_GOTO_STATION) && !(st->facilities & FACIL_DOCK)) {
3274 s->SetDestTile(s->GetOrderStationLocation(st->index));
3279 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
3282 #include "table/station_land.h"
3285 * Get station tile layout for a station type and its station gfx.
3286 * @param st Station type to draw.
3287 * @param gfx StationGfx of tile to draw.
3288 * @return Tile layout to draw.
3290 const DrawTileSprites *GetStationTileLayout(StationType st, uint8_t gfx)
3292 const auto &layouts = _station_display_datas[st];
3293 if (gfx >= layouts.size()) gfx &= 1;
3294 return layouts.data() + gfx;
3298 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
3299 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
3300 * is set to the overlay to draw.
3301 * @param ti Positional info for the tile to decide snowyness etc. May be nullptr.
3302 * @param[in,out] ground Groundsprite to draw.
3303 * @param[out] overlay_offset Overlay to draw.
3304 * @return true if overlay can be drawn.
3306 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
3308 bool snow_desert;
3309 switch (*ground) {
3310 case SPR_RAIL_TRACK_X:
3311 case SPR_MONO_TRACK_X:
3312 case SPR_MGLV_TRACK_X:
3313 snow_desert = false;
3314 *overlay_offset = RTO_X;
3315 break;
3317 case SPR_RAIL_TRACK_Y:
3318 case SPR_MONO_TRACK_Y:
3319 case SPR_MGLV_TRACK_Y:
3320 snow_desert = false;
3321 *overlay_offset = RTO_Y;
3322 break;
3324 case SPR_RAIL_TRACK_X_SNOW:
3325 case SPR_MONO_TRACK_X_SNOW:
3326 case SPR_MGLV_TRACK_X_SNOW:
3327 snow_desert = true;
3328 *overlay_offset = RTO_X;
3329 break;
3331 case SPR_RAIL_TRACK_Y_SNOW:
3332 case SPR_MONO_TRACK_Y_SNOW:
3333 case SPR_MGLV_TRACK_Y_SNOW:
3334 snow_desert = true;
3335 *overlay_offset = RTO_Y;
3336 break;
3338 default:
3339 return false;
3342 if (ti != nullptr) {
3343 /* Decide snow/desert from tile */
3344 switch (_settings_game.game_creation.landscape) {
3345 case LT_ARCTIC:
3346 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
3347 break;
3349 case LT_TROPIC:
3350 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
3351 break;
3353 default:
3354 break;
3358 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
3359 return true;
3362 static void DrawTile_Station(TileInfo *ti, DrawTileProcParams params)
3364 const NewGRFSpriteLayout *layout = nullptr;
3365 DrawTileSprites tmp_rail_layout;
3366 const DrawTileSprites *t = nullptr;
3367 int32_t total_offset;
3368 const RailTypeInfo *rti = nullptr;
3369 uint32_t relocation = 0;
3370 uint32_t ground_relocation = 0;
3371 BaseStation *st = nullptr;
3372 const StationSpec *statspec = nullptr;
3373 uint tile_layout = 0;
3375 if (HasStationRail(ti->tile)) {
3376 rti = GetRailTypeInfo(GetRailType(ti->tile));
3377 total_offset = rti->GetRailtypeSpriteOffset();
3379 if (IsCustomStationSpecIndex(ti->tile)) {
3380 /* look for customization */
3381 st = BaseStation::GetByTile(ti->tile);
3382 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
3384 if (statspec != nullptr) {
3385 tile_layout = GetStationGfx(ti->tile);
3387 if (HasBit(statspec->callback_mask, CBM_STATION_DRAW_TILE_LAYOUT)) {
3388 uint16_t callback = GetStationCallback(CBID_STATION_DRAW_TILE_LAYOUT, 0, 0, statspec, st, ti->tile, INVALID_RAILTYPE);
3389 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
3392 /* Ensure the chosen tile layout is valid for this custom station */
3393 if (!statspec->renderdata.empty()) {
3394 layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
3395 if (!layout->NeedsPreprocessing()) {
3396 t = layout;
3397 layout = nullptr;
3402 } else {
3403 total_offset = 0;
3406 StationGfx gfx = GetStationGfx(ti->tile);
3407 if (IsAirport(ti->tile)) {
3408 gfx = GetAirportGfx(ti->tile);
3409 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
3410 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
3411 if (ats->grf_prop.spritegroup[0] != nullptr && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), ats)) {
3412 return;
3414 /* No sprite group (or no valid one) found, meaning no graphics associated.
3415 * Use the substitute one instead */
3416 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
3417 gfx = ats->grf_prop.subst_id;
3419 switch (gfx) {
3420 case APT_RADAR_GRASS_FENCE_SW:
3421 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
3422 break;
3423 case APT_GRASS_FENCE_NE_FLAG:
3424 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
3425 break;
3426 case APT_RADAR_FENCE_SW:
3427 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
3428 break;
3429 case APT_RADAR_FENCE_NE:
3430 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
3431 break;
3432 case APT_GRASS_FENCE_NE_FLAG_2:
3433 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
3434 break;
3438 Owner owner = GetTileOwner(ti->tile);
3440 PaletteID palette;
3441 if (Company::IsValidID(owner)) {
3442 palette = COMPANY_SPRITE_COLOUR(owner);
3443 } else {
3444 /* Some stations are not owner by a company, namely oil rigs */
3445 palette = PALETTE_TO_GREY;
3448 if (layout == nullptr && (t == nullptr || t->seq == nullptr)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
3450 /* don't show foundation for docks */
3451 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
3452 if (statspec != nullptr && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
3453 /* Station has custom foundations.
3454 * Check whether the foundation continues beyond the tile's upper sides. */
3455 uint edge_info = 0;
3456 auto [slope, z] = GetFoundationPixelSlope(ti->tile);
3457 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
3458 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
3459 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
3460 if (image == 0) goto draw_default_foundation;
3462 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
3463 /* Station provides extended foundations. */
3465 static const uint8_t foundation_parts[] = {
3466 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3467 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3468 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3469 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3472 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3473 } else {
3474 /* Draw simple foundations, built up from 8 possible foundation sprites. */
3476 /* Each set bit represents one of the eight composite sprites to be drawn.
3477 * 'Invalid' entries will not drawn but are included for completeness. */
3478 static const uint8_t composite_foundation_parts[] = {
3479 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
3480 0x00, 0xD1, 0xE4, 0xE0,
3481 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
3482 0xCA, 0xC9, 0xC4, 0xC0,
3483 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
3484 0xD2, 0x91, 0xE4, 0xA0,
3485 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
3486 0x4A, 0x09, 0x44
3489 uint8_t parts = composite_foundation_parts[ti->tileh];
3491 /* If foundations continue beyond the tile's upper sides then
3492 * mask out the last two pieces. */
3493 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
3494 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
3496 if (parts == 0) {
3497 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
3498 * correct offset for the childsprites.
3499 * So, draw the (completely empty) sprite of the default foundations. */
3500 goto draw_default_foundation;
3503 StartSpriteCombine();
3504 for (int i = 0; i < 8; i++) {
3505 if (HasBit(parts, i)) {
3506 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3509 EndSpriteCombine();
3512 OffsetGroundSprite(0, -8);
3513 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, ti->tileh);
3514 } else {
3515 draw_default_foundation:
3516 DrawFoundation(ti, FOUNDATION_LEVELED);
3520 bool draw_ground = false;
3522 if (IsBuoy(ti->tile)) {
3523 DrawWaterClassGround(ti);
3524 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
3525 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
3526 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
3527 if (ti->tileh == SLOPE_FLAT) {
3528 DrawWaterClassGround(ti);
3529 } else {
3530 assert_tile(IsDock(ti->tile), ti->tile);
3531 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
3532 WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WATER_CLASS_INVALID;
3533 if (wc == WATER_CLASS_SEA) {
3534 DrawShoreTile(ti->tileh);
3535 } else {
3536 DrawClearLandTile(ti, 3);
3539 } else if (IsRoadWaypointTile(ti->tile)) {
3540 RoadBits bits = AxisToRoadBits(GetDriveThroughStopAxis(ti->tile));
3541 extern void DrawRoadBits(TileInfo *ti, RoadBits road, RoadBits tram, Roadside roadside, bool snow_or_desert, bool draw_catenary);
3542 DrawRoadBits(ti, GetRoadTypeRoad(ti->tile) != INVALID_ROADTYPE ? bits : ROAD_NONE,
3543 GetRoadTypeTram(ti->tile) != INVALID_ROADTYPE ? bits : ROAD_NONE,
3544 GetRoadWaypointRoadside(ti->tile), IsRoadWaypointOnSnowOrDesert(ti->tile), false);
3545 } else {
3546 if (layout != nullptr) {
3547 /* Sprite layout which needs preprocessing */
3548 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
3549 uint32_t var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
3550 for (uint8_t var10 : SetBitIterator(var10_values)) {
3551 uint32_t var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, INVALID_RAILTYPE, var10);
3552 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
3554 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
3555 t = &tmp_rail_layout;
3556 total_offset = 0;
3557 } else if (statspec != nullptr) {
3558 /* Simple sprite layout */
3559 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, INVALID_RAILTYPE, 0);
3560 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
3561 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, INVALID_RAILTYPE, 1);
3563 ground_relocation += rti->fallback_railtype;
3566 draw_ground = true;
3569 if (draw_ground && !IsAnyRoadStop(ti->tile)) {
3570 SpriteID image = t->ground.sprite;
3571 PaletteID pal = t->ground.pal;
3572 RailTrackOffset overlay_offset;
3573 if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3574 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
3575 DrawGroundSprite(image, PAL_NONE);
3576 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3578 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3579 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
3580 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3582 } else {
3583 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3584 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3585 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3587 /* PBS debugging, draw reserved tracks darker */
3588 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3589 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
3594 if (HasStationRail(ti->tile) && HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
3596 if (IsAnyRoadStop(ti->tile)) {
3597 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3598 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3599 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3600 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3602 StationGfx view = GetStationGfx(ti->tile);
3603 StationType type = GetStationType(ti->tile);
3605 const RoadStopSpec *stopspec = GetRoadStopSpec(ti->tile);
3606 RoadStopDrawMode stop_draw_mode = (RoadStopDrawMode)0;
3607 if (stopspec != nullptr) {
3608 stop_draw_mode = stopspec->draw_mode;
3609 st = BaseStation::GetByTile(ti->tile);
3610 RoadStopResolverObject object(stopspec, st, ti->tile, INVALID_ROADTYPE, type, view);
3611 const SpriteGroup *group = object.Resolve();
3612 if (group != nullptr && group->type == SGT_TILELAYOUT) {
3613 const DrawTileSprites *dts = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(nullptr);
3614 if (HasBit(stopspec->flags, RSF_DRAW_MODE_REGISTER)) {
3615 stop_draw_mode = (RoadStopDrawMode)GetRegister(0x100);
3617 t = dts;
3618 if (type == STATION_ROADWAYPOINT && (stop_draw_mode & ROADSTOP_DRAW_MODE_WAYP_GROUND)) {
3619 draw_ground = true;
3624 /* Draw ground sprite */
3625 if (draw_ground) {
3626 SpriteID image = t->ground.sprite;
3627 PaletteID pal = t->ground.pal;
3628 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3629 if (GB(image, 0, SPRITE_WIDTH) != 0) {
3630 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3631 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3635 if (IsDriveThroughStopTile(ti->tile)) {
3636 if (type != STATION_ROADWAYPOINT && (stopspec == nullptr || (stop_draw_mode & ROADSTOP_DRAW_MODE_OVERLAY) != 0)) {
3637 uint sprite_offset = GetDriveThroughStopAxis(ti->tile) == AXIS_X ? 1 : 0;
3638 DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3641 DisallowedRoadDirections drd = GetDriveThroughStopDisallowedRoadDirections(ti->tile);
3642 if (drd != DRD_NONE && (stopspec == nullptr || !HasBit(stopspec->flags, RSF_NO_ONE_WAY_OVERLAY)) && road_rt != INVALID_ROADTYPE) {
3643 SpriteID oneway = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_ONEWAY);
3644 if (oneway == 0) oneway = SPR_ONEWAY_BASE;
3645 DrawGroundSpriteAt(oneway + drd - 1 + ((GetDriveThroughStopAxis(ti->tile) == AXIS_X) ? 0 : 3), PAL_NONE, 8, 8, 0);
3647 } else {
3648 /* Non-drivethrough road stops are only valid for roads. */
3649 assert_tile(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE, ti->tile);
3651 if ((stopspec == nullptr || (stop_draw_mode & ROADSTOP_DRAW_MODE_ROAD) != 0) && road_rti->UsesOverlay()) {
3652 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_ROADSTOP);
3653 DrawGroundSprite(ground + view, PAL_NONE);
3657 if (stopspec == nullptr || !HasBit(stopspec->flags, RSF_NO_CATENARY)) {
3658 /* Draw road, tram catenary */
3659 DrawRoadCatenary(ti);
3663 if (IsRailWaypoint(ti->tile)) {
3664 /* Don't offset the waypoint graphics; they're always the same. */
3665 total_offset = 0;
3668 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
3669 DrawBridgeMiddle(ti);
3672 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3674 int32_t total_offset = 0;
3675 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3676 const DrawTileSprites *t = GetStationTileLayout(st, image);
3677 const RailTypeInfo *railtype_info = nullptr;
3679 if (railtype != INVALID_RAILTYPE) {
3680 railtype_info = GetRailTypeInfo(railtype);
3681 total_offset = railtype_info->GetRailtypeSpriteOffset();
3684 SpriteID img = t->ground.sprite;
3685 RailTrackOffset overlay_offset;
3686 if (railtype_info != nullptr && railtype_info->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3687 SpriteID ground = GetCustomRailSprite(railtype_info, INVALID_TILE, RTSG_GROUND);
3688 DrawSprite(img, PAL_NONE, x, y);
3689 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3690 } else {
3691 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3694 if (roadtype != INVALID_ROADTYPE) {
3695 const RoadTypeInfo *roadtype_info = GetRoadTypeInfo(roadtype);
3696 if (image >= 4) {
3697 /* Drive-through stop */
3698 uint sprite_offset = 5 - image;
3700 /* Road underlay takes precedence over tram */
3701 if (roadtype_info->UsesOverlay()) {
3702 SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_GROUND);
3703 DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3705 SpriteID overlay = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_OVERLAY);
3706 if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3707 } else if (RoadTypeIsTram(roadtype)) {
3708 DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3710 } else {
3711 /* Bay stop */
3712 if (RoadTypeIsRoad(roadtype) && roadtype_info->UsesOverlay()) {
3713 SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_ROADSTOP);
3714 DrawSprite(ground + image, PAL_NONE, x, y);
3719 /* Default waypoint has no railtype specific sprites */
3720 DrawRailTileSeqInGUI(x, y, t, (st == STATION_WAYPOINT || st == STATION_ROADWAYPOINT) ? 0 : total_offset, 0, pal);
3723 static int GetSlopePixelZ_Station(TileIndex tile, uint, uint, bool)
3725 return GetTileMaxPixelZ(tile);
3728 static Foundation GetFoundation_Station(TileIndex, Slope tileh)
3730 return FlatteningFoundation(tileh);
3733 static void FillTileDescRoadStop(TileIndex tile, TileDesc *td)
3735 RoadType road_rt = GetRoadTypeRoad(tile);
3736 RoadType tram_rt = GetRoadTypeTram(tile);
3737 Owner road_owner = INVALID_OWNER;
3738 Owner tram_owner = INVALID_OWNER;
3739 if (road_rt != INVALID_ROADTYPE) {
3740 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3741 td->roadtype = rti->strings.name;
3742 td->road_speed = rti->max_speed / 2;
3743 road_owner = GetRoadOwner(tile, RTT_ROAD);
3746 if (tram_rt != INVALID_ROADTYPE) {
3747 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3748 td->tramtype = rti->strings.name;
3749 td->tram_speed = rti->max_speed / 2;
3750 tram_owner = GetRoadOwner(tile, RTT_TRAM);
3753 if (IsDriveThroughStopTile(tile)) {
3754 /* Is there a mix of owners? */
3755 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3756 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3757 uint i = 1;
3758 if (road_owner != INVALID_OWNER) {
3759 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3760 td->owner[i] = road_owner;
3761 i++;
3763 if (tram_owner != INVALID_OWNER) {
3764 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3765 td->owner[i] = tram_owner;
3771 void FillTileDescRailStation(TileIndex tile, TileDesc *td)
3773 const StationSpec *spec = GetStationSpec(tile);
3775 if (spec != nullptr) {
3776 td->station_class = StationClass::Get(spec->class_index)->name;
3777 td->station_name = spec->name;
3779 if (spec->grf_prop.HasGrfFile()) {
3780 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grfid);
3781 td->grf = gc->GetName();
3785 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3786 td->rail_speed = rti->max_speed;
3787 td->railtype = rti->strings.name;
3790 void FillTileDescAirport(TileIndex tile, TileDesc *td)
3792 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3793 td->airport_class = AirportClass::Get(as->class_index)->name;
3794 td->airport_name = as->name;
3796 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3797 td->airport_tile_name = ats->name;
3799 if (as->grf_prop.HasGrfFile()) {
3800 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grfid);
3801 td->grf = gc->GetName();
3802 } else if (ats->grf_prop.HasGrfFile()) {
3803 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grfid);
3804 td->grf = gc->GetName();
3808 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3810 td->owner[0] = GetTileOwner(tile);
3811 td->build_date = BaseStation::GetByTile(tile)->build_date;
3813 if (IsAnyRoadStopTile(tile)) FillTileDescRoadStop(tile, td);
3814 if (HasStationRail(tile)) FillTileDescRailStation(tile, td);
3815 if (IsAirport(tile)) FillTileDescAirport(tile, td);
3817 StringID str;
3818 switch (GetStationType(tile)) {
3819 default: NOT_REACHED();
3820 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3821 case STATION_AIRPORT:
3822 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3823 break;
3824 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3825 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3826 case STATION_OILRIG: {
3827 const Industry *i = Station::GetByTile(tile)->industry;
3828 const IndustrySpec *is = GetIndustrySpec(i->type);
3829 td->owner[0] = i->owner;
3830 str = is->name;
3831 if (is->grf_prop.HasGrfFile()) td->grf = GetGRFConfig(is->grf_prop.grfid)->GetName();
3832 break;
3834 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3835 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3836 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3837 case STATION_ROADWAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3839 td->str = str;
3843 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3845 TrackdirBits trackdirbits = TRACKDIR_BIT_NONE;
3847 switch (mode) {
3848 case TRANSPORT_RAIL:
3849 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3850 trackdirbits = TrackToTrackdirBits(GetRailStationTrack(tile));
3852 break;
3854 case TRANSPORT_WATER:
3855 /* buoy is coded as a station, it is always on open water */
3856 if (IsBuoy(tile)) {
3857 TrackBits trackbits = TRACK_BIT_ALL;
3858 /* remove tracks that connect NE map edge */
3859 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3860 /* remove tracks that connect NW map edge */
3861 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3862 trackdirbits = TrackBitsToTrackdirBits(trackbits);
3864 break;
3866 case TRANSPORT_ROAD:
3867 if (IsAnyRoadStop(tile)) {
3868 RoadTramType rtt = (RoadTramType)GB(sub_mode, 0, 8);
3869 if (!HasTileRoadType(tile, rtt)) break;
3871 if (IsBayRoadStopTile(tile)) {
3872 DiagDirection dir = GetBayRoadStopDir(tile);
3873 if (side != INVALID_DIAGDIR && dir != side) break;
3874 TrackBits trackbits = DiagDirToDiagTrackBits(dir);
3875 trackdirbits = TrackBitsToTrackdirBits(trackbits);
3876 } else {
3877 Axis axis = GetDriveThroughStopAxis(tile);
3878 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
3879 TrackBits trackbits = AxisToTrackBits(axis);
3880 const uint drd_to_multiplier[DRD_END] = { 0x101, 0x100, 0x1, 0x0 };
3881 trackdirbits = (TrackdirBits)(trackbits * drd_to_multiplier[GetDriveThroughStopDisallowedRoadDirections(tile)]);
3884 break;
3886 default:
3887 break;
3890 return CombineTrackStatus(trackdirbits, TRACKDIR_BIT_NONE);
3894 static void TileLoop_Station(TileIndex tile)
3896 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3897 * hardcoded.....not good */
3898 switch (GetStationType(tile)) {
3899 case STATION_AIRPORT:
3900 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3901 break;
3903 case STATION_DOCK:
3904 if (!IsTileFlat(tile)) break; // only handle water part
3905 [[fallthrough]];
3907 case STATION_OILRIG: //(station part)
3908 case STATION_BUOY:
3909 TileLoop_Water(tile);
3910 break;
3912 case STATION_ROADWAYPOINT: {
3913 switch (_settings_game.game_creation.landscape) {
3914 case LT_ARCTIC:
3915 if (IsRoadWaypointOnSnowOrDesert(tile) != (GetTileZ(tile) > GetSnowLine())) {
3916 ToggleRoadWaypointOnSnowOrDesert(tile);
3917 MarkTileDirtyByTile(tile, VMDF_NOT_MAP_MODE);
3919 break;
3921 case LT_TROPIC:
3922 if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsRoadWaypointOnSnowOrDesert(tile)) {
3923 ToggleRoadWaypointOnSnowOrDesert(tile);
3924 MarkTileDirtyByTile(tile, VMDF_NOT_MAP_MODE);
3926 break;
3929 HouseZonesBits grp = HZB_TOWN_EDGE;
3930 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
3931 if (t != nullptr) {
3932 grp = GetTownRadiusGroup(t, tile);
3935 /* Adjust road ground type depending on 'grp' (grp is the distance to the center) */
3936 Roadside new_rs = grp > HZB_TOWN_EDGE ? ROADSIDE_PAVED : ROADSIDE_GRASS;
3937 Roadside cur_rs = GetRoadWaypointRoadside(tile);
3939 if (new_rs != cur_rs) {
3940 SetRoadWaypointRoadside(tile, cur_rs == ROADSIDE_BARREN ? new_rs : ROADSIDE_BARREN);
3941 MarkTileDirtyByTile(tile, VMDF_NOT_MAP_MODE);
3943 break;
3946 default: break;
3951 void AnimateTile_Station(TileIndex tile)
3953 if (HasStationRail(tile)) {
3954 AnimateStationTile(tile);
3955 return;
3958 if (IsAirport(tile)) {
3959 AnimateAirportTile(tile);
3960 return;
3963 if (IsAnyRoadStopTile(tile)) {
3964 AnimateRoadStopTile(tile);
3965 return;
3969 uint8_t GetAnimatedTileSpeed_Station(TileIndex tile)
3971 if (HasStationRail(tile)) {
3972 return GetStationTileAnimationSpeed(tile);
3975 if (IsAirport(tile)) {
3976 return GetAirportTileAnimationSpeed(tile);
3979 if (IsAnyRoadStopTile(tile)) {
3980 return GetRoadStopTileAnimationSpeed(tile);
3982 return 0;
3986 static bool ClickTile_Station(TileIndex tile)
3988 const BaseStation *bst = BaseStation::GetByTile(tile);
3990 if (bst->facilities & FACIL_WAYPOINT) {
3991 ShowWaypointWindow(Waypoint::From(bst));
3992 } else if (IsHangar(tile)) {
3993 const Station *st = Station::From(bst);
3994 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3995 } else {
3996 ShowStationViewWindow(bst->index);
3998 return true;
4001 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
4003 if (v->type == VEH_TRAIN) {
4004 StationID station_id = GetStationIndex(tile);
4005 if (v->current_order.IsType(OT_GOTO_WAYPOINT) && v->current_order.GetDestination() == station_id && v->current_order.GetWaypointFlags() & OWF_REVERSE) {
4006 Train *t = Train::From(v);
4007 // reverse at waypoint
4008 if (t->reverse_distance == 0) {
4009 t->reverse_distance = t->gcache.cached_total_length;
4010 if (t->current_order.IsWaitTimetabled()) {
4011 t->DeleteUnreachedImplicitOrders();
4012 UpdateVehicleTimetable(t, true);
4013 t->last_station_visited = station_id;
4014 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
4015 t->current_order.MakeWaiting();
4016 t->current_order.SetNonStopType(ONSF_NO_STOP_AT_ANY_STATION);
4017 return VETSB_CONTINUE;
4021 if (HasBit(Train::From(v)->flags, VRF_BEYOND_PLATFORM_END)) return VETSB_CONTINUE;
4022 Train *front = Train::From(v)->First();
4023 if (!front->IsFrontEngine()) return VETSB_CONTINUE;
4024 if (!(v == front || HasBit(Train::From(v)->Previous()->flags, VRF_BEYOND_PLATFORM_END))) return VETSB_CONTINUE;
4025 if (!HasStationTileRail(tile)) return VETSB_CONTINUE;
4026 if (!front->current_order.ShouldStopAtStation(front, station_id, IsRailWaypoint(tile))) return VETSB_CONTINUE;
4028 int station_ahead;
4029 int station_length;
4030 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), true, &station_ahead, &station_length);
4032 /* Stop whenever that amount of station ahead + the distance from the
4033 * begin of the platform to the stop location is longer than the length
4034 * of the platform. Station ahead 'includes' the current tile where the
4035 * vehicle is on, so we need to subtract that. */
4036 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
4038 DiagDirection dir = DirToDiagDir(v->direction);
4040 x &= 0xF;
4041 y &= 0xF;
4043 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
4044 if (y == TILE_SIZE / 2) {
4045 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
4046 stop &= TILE_SIZE - 1;
4048 if (x == stop) {
4049 if (front->UsingRealisticBraking() && front->cur_speed > 15 && !(front->lookahead != nullptr && HasBit(front->lookahead->flags, TRLF_APPLY_ADVISORY))) {
4050 /* Travelling too fast, do not stop and report overshoot to player */
4051 if (front->owner == _local_company) {
4052 SetDParam(0, front->index);
4053 SetDParam(1, IsRailWaypointTile(tile) ? STR_WAYPOINT_NAME : STR_STATION_NAME);
4054 SetDParam(2, station_id);
4055 AddNewsItem(STR_NEWS_TRAIN_OVERSHOT_STATION, NT_ADVICE, NF_INCOLOUR | NF_SMALL | NF_VEHICLE_PARAM0,
4056 NR_VEHICLE, v->index,
4057 NR_STATION, station_id);
4059 for (Train *u = front; u != nullptr; u = u->Next()) {
4060 ClrBit(u->flags, VRF_BEYOND_PLATFORM_END);
4062 return VETSB_CONTINUE;
4064 return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
4065 } else if (x < stop) {
4066 if (front->UsingRealisticBraking() && front->cur_speed > 30) {
4067 /* Travelling too fast, take no action */
4068 return VETSB_CONTINUE;
4070 front->vehstatus |= VS_TRAIN_SLOWING;
4071 uint16_t spd = std::max(0, (stop - x) * 20 - 15);
4072 if (spd < front->cur_speed) front->cur_speed = spd;
4075 } else if (v->type == VEH_ROAD) {
4076 RoadVehicle *rv = RoadVehicle::From(v);
4077 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
4078 if (IsStationRoadStop(tile) && rv->IsFrontEngine()) {
4079 /* Attempt to allocate a parking bay in a road stop */
4080 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
4085 return VETSB_CONTINUE;
4089 * Run the watched cargo callback for all houses in the catchment area.
4090 * @param st Station.
4092 void TriggerWatchedCargoCallbacks(Station *st)
4094 /* Collect cargoes accepted since the last big tick. */
4095 CargoTypes cargoes = 0;
4096 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
4097 if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
4100 /* Anything to do? */
4101 if (cargoes == 0) return;
4103 /* Loop over all houses in the catchment. */
4104 BitmapTileIterator it(st->catchment_tiles);
4105 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
4106 if (IsTileType(tile, MP_HOUSE)) {
4107 WatchedCargoCallback(tile, cargoes);
4113 * This function is called for each station once every 250 ticks.
4114 * Not all stations will get the tick at the same time.
4115 * @param st the station receiving the tick.
4116 * @return true if the station is still valid (wasn't deleted)
4118 static bool StationHandleBigTick(BaseStation *st)
4120 if (!st->IsInUse()) {
4121 if (++st->delete_ctr >= 8) delete st;
4122 return false;
4125 if (Station::IsExpected(st)) {
4126 TriggerWatchedCargoCallbacks(Station::From(st));
4128 for (GoodsEntry &ge : Station::From(st)->goods) {
4129 ClrBit(ge.status, GoodsEntry::GES_ACCEPTED_BIGTICK);
4134 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
4136 return true;
4139 static inline void byte_inc_sat(uint8_t *p)
4141 uint8_t b = *p + 1;
4142 if (b != 0) *p = b;
4146 * Truncate the cargo by a specific amount.
4147 * @param cs The type of cargo to perform the truncation for.
4148 * @param ge The goods entry, of the station, to truncate.
4149 * @param amount The amount to truncate the cargo by.
4151 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
4153 /* If truncating also punish the source stations' ratings to
4154 * decrease the flow of incoming cargo. */
4156 if (ge->data == nullptr) return;
4158 StationCargoAmountMap waiting_per_source;
4159 ge->data->cargo.Truncate(amount, &waiting_per_source);
4160 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
4161 Station *source_station = Station::GetIfValid(i->first);
4162 if (source_station == nullptr) continue;
4164 GoodsEntry &source_ge = source_station->goods[cs->Index()];
4165 if (i->second > source_ge.max_waiting_cargo) {
4166 source_ge.max_waiting_cargo += (i->second - source_ge.max_waiting_cargo) / 4;
4171 bool GetNewGrfRating(const Station *st, const CargoSpec *cs, const GoodsEntry *ge, int *new_grf_rating)
4173 *new_grf_rating = 0;
4174 bool is_using_newgrf_rating = false;
4176 /* Perform custom station rating. If it succeeds the speed, days in transit and
4177 * waiting cargo ratings must not be executed. */
4179 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
4180 uint last_speed = ge->HasVehicleEverTriedLoading() && ge->IsSupplyAllowed() ? ge->last_speed : 0xFF;
4182 uint32_t var18 = std::min<uint>(ge->time_since_pickup, 0xFFu)
4183 | (std::min<uint>(ge->max_waiting_cargo, 0xFFFFu) << 8)
4184 | (std::min<uint>(last_speed, 0xFFu) << 24);
4185 /* Convert to the 'old' vehicle types */
4186 uint32_t var10 = (ge->last_vehicle_type == VEH_INVALID) ? 0x0 : (ge->last_vehicle_type + 0x10);
4187 uint16_t callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
4188 if (callback != CALLBACK_FAILED) {
4189 is_using_newgrf_rating = true;
4190 *new_grf_rating = GB(callback, 0, 14);
4192 /* Simulate a 15 bit signed value */
4193 if (HasBit(callback, 14)) *new_grf_rating -= 0x4000;
4196 return is_using_newgrf_rating;
4199 int GetSpeedRating(const GoodsEntry *ge)
4201 const int b = ge->last_speed - 85;
4203 return (b >= 0) ? (b >> 2) : 0;
4206 int GetWaitTimeRating(const CargoSpec *cs, const GoodsEntry *ge)
4208 int rating = 0;
4210 uint wait_time = ge->time_since_pickup;
4212 if (_settings_game.station.cargo_class_rating_wait_time) {
4213 if (cs->classes & CC_PASSENGERS) {
4214 wait_time *= 3;
4215 } else if (cs->classes & CC_REFRIGERATED) {
4216 wait_time *= 2;
4217 } else if (cs->classes & (CC_MAIL | CC_ARMOURED | CC_EXPRESS)) {
4218 wait_time += (wait_time >> 1);
4219 } else if (cs->classes & (CC_BULK | CC_LIQUID)) {
4220 wait_time >>= 2;
4224 if (ge->last_vehicle_type == VEH_SHIP) wait_time >>= 2;
4225 if (wait_time <= 21) rating += 25;
4226 if (wait_time <= 12) rating += 25;
4227 if (wait_time <= 6) rating += 45;
4228 if (wait_time <= 3) rating += 35;
4230 return rating;
4233 int GetWaitingCargoRating(const Station *st, const GoodsEntry *ge)
4235 int rating = -90;
4237 uint normalised_max_waiting_cargo = ge->max_waiting_cargo;
4239 if (_settings_game.station.station_size_rating_cargo_amount) {
4240 normalised_max_waiting_cargo *= 8;
4241 if (st->station_tiles > 1) normalised_max_waiting_cargo /= st->station_tiles;
4244 if (normalised_max_waiting_cargo <= 1500) rating += 55;
4245 if (normalised_max_waiting_cargo <= 1000) rating += 35;
4246 if (normalised_max_waiting_cargo <= 600) rating += 10;
4247 if (normalised_max_waiting_cargo <= 300) rating += 20;
4248 if (normalised_max_waiting_cargo <= 100) rating += 10;
4250 return rating;
4253 int GetStatueRating(const Station *st)
4255 return Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner) ? 26 : 0;
4258 int GetVehicleAgeRating(const GoodsEntry *ge)
4260 int rating = 0;
4262 const uint8_t age = ge->last_age;
4264 if (age < 30) rating += 10;
4265 if (age < 20) rating += 10;
4266 if (age < 10) rating += 13;
4268 return rating;
4271 int GetTargetRating(const Station *st, const CargoSpec *cs, const GoodsEntry *ge)
4273 bool skip = false;
4274 int rating = 0;
4276 if (_cheats.station_rating.value) {
4277 rating = 255;
4278 skip = true;
4279 } else if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
4281 int new_grf_rating;
4283 if (GetNewGrfRating(st, cs, ge, &new_grf_rating)) {
4284 skip = true;
4285 rating += new_grf_rating;
4289 if (!skip) {
4290 rating += GetSpeedRating(ge);
4291 rating += GetWaitTimeRating(cs, ge);
4292 rating += GetWaitingCargoRating(st, ge);
4295 rating += GetStatueRating(st);
4296 rating += GetVehicleAgeRating(ge);
4298 return ClampTo<uint8_t>(rating);
4301 static void UpdateStationRating(Station *st)
4303 bool waiting_changed = false;
4305 byte_inc_sat(&st->time_since_load);
4306 byte_inc_sat(&st->time_since_unload);
4308 for (const CargoSpec *cs : CargoSpec::Iterate()) {
4309 GoodsEntry *ge = &st->goods[cs->Index()];
4311 /* Slowly increase the rating back to its original level in the case we
4312 * didn't deliver cargo yet to this station. This happens when a bribe
4313 * failed while you didn't moved that cargo yet to a station. */
4314 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
4315 ge->rating++;
4318 /* Only change the rating if we are moving this cargo */
4319 if (ge->HasRating()) {
4320 byte_inc_sat(&ge->time_since_pickup);
4322 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
4323 ClrBit(ge->status, GoodsEntry::GES_RATING);
4324 ge->last_speed = 0;
4325 TruncateCargo(cs, ge);
4326 waiting_changed = true;
4327 continue;
4331 int rating = GetTargetRating(st, cs, ge);
4333 uint waiting = ge->CargoAvailableCount();
4335 /* num_dests is at least 1 if there is any cargo as
4336 * INVALID_STATION is also a destination.
4338 const uint num_dests = ge->data != nullptr ? (uint)ge->data->cargo.Packets()->MapSize() : 0;
4340 /* Average amount of cargo per next hop, but prefer solitary stations
4341 * with only one or two next hops. They are allowed to have more
4342 * cargo waiting per next hop.
4343 * With manual cargo distribution waiting_avg = waiting / 2 as then
4344 * INVALID_STATION is the only destination.
4346 const uint waiting_avg = waiting / (num_dests + 1);
4348 const int old_rating = ge->rating; // old rating
4350 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
4351 ge->rating = rating = old_rating + Clamp(rating - old_rating, -2, 2);
4353 /* if rating is <= 64 and more than 100 items waiting on average per destination,
4354 * remove some random amount of goods from the station */
4355 if (rating <= 64 && waiting_avg >= 100) {
4356 int dec = Random() & 0x1F;
4357 if (waiting_avg < 200) dec &= 7;
4358 waiting -= (dec + 1) * num_dests;
4359 waiting_changed = true;
4362 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
4363 if (rating <= 127 && waiting != 0) {
4364 uint32_t r = Random();
4365 if (rating <= (int)GB(r, 0, 7)) {
4366 /* Need to have int, otherwise it will just overflow etc. */
4367 waiting = std::max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
4368 waiting_changed = true;
4372 /* At some point we really must cap the cargo. Previously this
4373 * was a strict 4095, but now we'll have a less strict, but
4374 * increasingly aggressive truncation of the amount of cargo. */
4375 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
4376 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
4377 static const uint MAX_WAITING_CARGO = 1 << 15;
4379 uint normalised_waiting_cargo_threshold = WAITING_CARGO_THRESHOLD;
4380 if (_settings_game.station.station_size_rating_cargo_amount) {
4381 if (st->station_tiles > 1) normalised_waiting_cargo_threshold *= st->station_tiles;
4382 normalised_waiting_cargo_threshold /= 8;
4385 if (waiting > normalised_waiting_cargo_threshold) {
4386 const uint difference = waiting - normalised_waiting_cargo_threshold;
4387 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
4388 const uint normalised_max_waiting_cargo = normalised_waiting_cargo_threshold * (MAX_WAITING_CARGO / WAITING_CARGO_THRESHOLD);
4389 waiting = std::min(waiting, normalised_max_waiting_cargo);
4390 waiting_changed = true;
4393 /* We can't truncate cargo that's already reserved for loading.
4394 * Thus StoredCount() here. */
4395 if (waiting_changed && waiting < ge->CargoAvailableCount()) {
4396 /* Feed back the exact own waiting cargo at this station for the
4397 * next rating calculation. */
4398 ge->max_waiting_cargo = 0;
4400 TruncateCargo(cs, ge, ge->CargoAvailableCount() - waiting);
4401 } else {
4402 /* If the average number per next hop is low, be more forgiving. */
4403 ge->max_waiting_cargo = waiting_avg;
4409 StationID index = st->index;
4411 if (waiting_changed) {
4412 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
4413 } else {
4414 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
4419 * Reroute cargo of type c at station st or in any vehicles unloading there.
4420 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
4421 * @param st Station to be rerouted at.
4422 * @param c Type of cargo.
4423 * @param avoid Original next hop of cargo, avoid this.
4424 * @param avoid2 Another station to be avoided when rerouting.
4426 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
4428 GoodsEntry &ge = st->goods[c];
4430 /* Reroute cargo in station. */
4431 if (ge.data != nullptr) ge.data->cargo.Reroute(UINT_MAX, &ge.data->cargo, avoid, avoid2, &ge);
4433 /* Reroute cargo staged to be transferred. */
4434 for (Vehicle *v : st->loading_vehicles) {
4435 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
4436 if (u->cargo_type != c) continue;
4437 u->cargo.Reroute(UINT_MAX, &u->cargo, avoid, avoid2, &ge);
4443 * Reroute cargo of type c from source at station st or in any vehicles unloading there.
4444 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
4445 * @param st Station to be rerouted at.
4446 * @param c Type of cargo.
4447 * @param source Source station.
4448 * @param avoid Original next hop of cargo, avoid this.
4449 * @param avoid2 Another station to be avoided when rerouting.
4451 void RerouteCargoFromSource(Station *st, CargoID c, StationID source, StationID avoid, StationID avoid2)
4453 GoodsEntry &ge = st->goods[c];
4455 /* Reroute cargo in station. */
4456 if (ge.data != nullptr) ge.data->cargo.RerouteFromSource(UINT_MAX, &ge.data->cargo, source, avoid, avoid2, &ge);
4458 /* Reroute cargo staged to be transferred. */
4459 for (Vehicle *v : st->loading_vehicles) {
4460 for (; v != nullptr; v = v->Next()) {
4461 if (v->cargo_type != c) continue;
4462 v->cargo.RerouteFromSource(UINT_MAX, &v->cargo, source, avoid, avoid2, &ge);
4467 robin_hood::unordered_flat_set<VehicleID> _delete_stale_links_vehicle_cache;
4469 void ClearDeleteStaleLinksVehicleCache()
4471 _delete_stale_links_vehicle_cache.clear();
4475 * Check all next hops of cargo packets in this station for existence of a
4476 * a valid link they may use to travel on. Reroute any cargo not having a valid
4477 * link and remove timed out links found like this from the linkgraph. We're
4478 * not all links here as that is expensive and useless. A link no one is using
4479 * doesn't hurt either.
4480 * @param from Station to check.
4482 void DeleteStaleLinks(Station *from)
4484 for (CargoID c = 0; c < NUM_CARGO; ++c) {
4485 const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
4486 GoodsEntry &ge = from->goods[c];
4487 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
4488 if (lg == nullptr) continue;
4489 lg->MutableIterateEdgesFromNode(ge.node, [&](LinkGraph::EdgeIterationHelper edge_helper) -> LinkGraph::EdgeIterationResult {
4490 Edge edge = edge_helper.GetEdge();
4491 NodeID to_id = edge_helper.to_id;
4493 LinkGraph::EdgeIterationResult result = LinkGraph::EdgeIterationResult::None;
4495 Station *to = Station::Get((*lg)[to_id].Station());
4496 assert(to->goods[c].node == to_id);
4497 assert(EconTime::CurDate() >= edge.LastUpdate());
4498 const DateDelta timeout = DateDelta{std::max<int>((LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3)) / DayLengthFactor(), 1)};
4499 if (edge.LastAircraftUpdate() != EconTime::INVALID_DATE && (EconTime::CurDate() - edge.LastAircraftUpdate()) > timeout) {
4500 edge.ClearAircraft();
4502 if ((EconTime::CurDate() - edge.LastUpdate()) > timeout) {
4503 bool updated = false;
4505 if (auto_distributed) {
4506 /* Have all vehicles refresh their next hops before deciding to
4507 * remove the node. */
4508 std::vector<Vehicle *> vehicles;
4509 for (const OrderList *l : OrderList::Iterate()) {
4510 bool found_from = false;
4511 bool found_to = false;
4512 for (const Order *order : l->Orders()) {
4513 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
4514 if (order->GetDestination() == from->index) {
4515 found_from = true;
4516 if (found_to) break;
4517 } else if (order->GetDestination() == to->index) {
4518 found_to = true;
4519 if (found_from) break;
4522 if (!found_to || !found_from) continue;
4523 vehicles.push_back(l->GetFirstSharedVehicle());
4526 auto iter = vehicles.begin();
4527 while (iter != vehicles.end()) {
4528 Vehicle *v = *iter;
4530 auto res = _delete_stale_links_vehicle_cache.insert(v->index);
4531 // Only run LinkRefresher if vehicle was not already in the cache
4532 if (res.second) {
4533 /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
4534 if (!v->IsStoppedInDepot() || (EconTime::CurDate() - v->date_of_last_service) <=
4535 LinkGraph::STALE_LINK_DEPOT_TIMEOUT) {
4536 edge_helper.RecordSize();
4537 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
4538 if (edge_helper.RefreshIterationIfSizeChanged()) {
4539 edge = edge_helper.GetEdge();
4543 if (edge.LastUpdate() == EconTime::CurDate()) {
4544 updated = true;
4545 break;
4548 Vehicle *next_shared = v->NextShared();
4549 if (next_shared) {
4550 *iter = next_shared;
4551 ++iter;
4552 } else {
4553 iter = vehicles.erase(iter);
4556 if (iter == vehicles.end()) iter = vehicles.begin();
4560 if (!updated) {
4561 /* If it's still considered dead remove it. */
4562 result = LinkGraph::EdgeIterationResult::EraseEdge;
4563 if (ge.data != nullptr) ge.data->flows.DeleteFlows(to->index);
4564 RerouteCargo(from, c, to->index, from->index);
4566 } else if (edge.LastUnrestrictedUpdate() != EconTime::INVALID_DATE && (EconTime::CurDate() - edge.LastUnrestrictedUpdate()) > timeout) {
4567 edge.Restrict();
4568 if (ge.data != nullptr) ge.data->flows.RestrictFlows(to->index);
4569 RerouteCargo(from, c, to->index, from->index);
4570 } else if (edge.LastRestrictedUpdate() != EconTime::INVALID_DATE && (EconTime::CurDate() - edge.LastRestrictedUpdate()) > timeout) {
4571 edge.Release();
4574 return result;
4576 assert(_scaled_tick_counter >= lg->LastCompression());
4577 if ((_scaled_tick_counter - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
4578 lg->Compress();
4584 * Increase capacity for a link stat given by station cargo and next hop.
4585 * @param st Station to get the link stats from.
4586 * @param cargo Cargo to increase stat for.
4587 * @param next_station_id Station the consist will be travelling to next.
4588 * @param capacity Capacity to add to link stat.
4589 * @param usage Usage to add to link stat.
4590 * @param mode Update mode to be applied.
4592 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateMode mode)
4594 GoodsEntry &ge1 = st->goods[cargo];
4595 Station *st2 = Station::Get(next_station_id);
4596 GoodsEntry &ge2 = st2->goods[cargo];
4597 LinkGraph *lg = nullptr;
4598 if (ge1.link_graph == INVALID_LINK_GRAPH) {
4599 if (ge2.link_graph == INVALID_LINK_GRAPH) {
4600 if (LinkGraph::CanAllocateItem()) {
4601 lg = new LinkGraph(cargo);
4602 LinkGraphSchedule::instance.Queue(lg);
4603 ge2.link_graph = lg->index;
4604 ge2.node = lg->AddNode(st2);
4605 } else {
4606 Debug(misc, 0, "Can't allocate link graph");
4608 } else {
4609 lg = LinkGraph::Get(ge2.link_graph);
4611 if (lg) {
4612 ge1.link_graph = lg->index;
4613 ge1.node = lg->AddNode(st);
4615 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
4616 lg = LinkGraph::Get(ge1.link_graph);
4617 ge2.link_graph = lg->index;
4618 ge2.node = lg->AddNode(st2);
4619 } else {
4620 lg = LinkGraph::Get(ge1.link_graph);
4621 if (ge1.link_graph != ge2.link_graph) {
4622 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
4623 if (lg->Size() < lg2->Size()) {
4624 LinkGraphSchedule::instance.Unqueue(lg);
4625 lg2->Merge(lg); // Updates GoodsEntries of lg
4626 lg = lg2;
4627 } else {
4628 LinkGraphSchedule::instance.Unqueue(lg2);
4629 lg->Merge(lg2); // Updates GoodsEntries of lg2
4633 if (lg != nullptr) {
4634 lg->UpdateEdge(ge1.node, ge2.node, capacity, usage, time, mode);
4638 /* called for every station each tick */
4639 static void StationHandleSmallTick(BaseStation *st)
4641 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
4643 uint8_t b = st->delete_ctr + 1;
4644 if (b >= STATION_RATING_TICKS) b = 0;
4645 st->delete_ctr = b;
4647 if (b == 0) UpdateStationRating(Station::From(st));
4650 void UpdateAllStationRatings()
4652 for (Station *st : Station::Iterate()) {
4653 if (!st->IsInUse()) continue;
4654 UpdateStationRating(st);
4658 void OnTick_Station()
4660 if (_game_mode == GM_EDITOR) return;
4662 ClearDeleteStaleLinksVehicleCache();
4664 for (BaseStation *st : BaseStation::Iterate()) {
4665 StationHandleSmallTick(st);
4667 /* Clean up the link graph about once a week. */
4668 if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
4669 DeleteStaleLinks(Station::From(st));
4672 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
4673 * Station index is included so that triggers are not all done
4674 * at the same time. */
4675 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
4676 /* Stop processing this station if it was deleted */
4677 if (!StationHandleBigTick(st)) continue;
4678 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
4679 TriggerRoadStopAnimation(st, st->xy, SAT_250_TICKS);
4680 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
4685 /** Daily loop for stations. */
4686 void StationDailyLoop()
4688 // Only record cargo history every second day.
4689 if (EconTime::CurDate().base() % 2 != 0) {
4690 for (Station *st : Station::Iterate()) {
4691 st->UpdateCargoHistory();
4693 InvalidateWindowClassesData(WC_STATION_CARGO);
4697 /** Monthly loop for stations. */
4698 void StationMonthlyLoop()
4700 for (Station *st : Station::Iterate()) {
4701 for (GoodsEntry &ge : st->goods) {
4702 SB(ge.status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge.status, GoodsEntry::GES_CURRENT_MONTH, 1));
4703 ClrBit(ge.status, GoodsEntry::GES_CURRENT_MONTH);
4709 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
4711 ForAllStationsRadius(tile, radius, [&](Station *st) {
4712 if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
4713 for (GoodsEntry &ge : st->goods) {
4714 if (ge.status != 0) {
4715 ge.rating = ClampTo<uint8_t>(ge.rating + amount);
4722 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
4724 /* We can't allocate a CargoPacket? Then don't do anything
4725 * at all; i.e. just discard the incoming cargo. */
4726 if (!CargoPacket::CanAllocateItem()) return 0;
4728 GoodsEntry &ge = st->goods[type];
4729 amount += ge.amount_fract;
4730 ge.amount_fract = GB(amount, 0, 8);
4732 amount >>= 8;
4733 /* No new "real" cargo item yet. */
4734 if (amount == 0) return 0;
4736 StationID next = ge.GetVia(st->index);
4737 ge.CreateData().cargo.Append(new CargoPacket(st->index, amount, source_type, source_id), next);
4738 LinkGraph *lg = nullptr;
4739 if (ge.link_graph == INVALID_LINK_GRAPH) {
4740 if (LinkGraph::CanAllocateItem()) {
4741 lg = new LinkGraph(type);
4742 LinkGraphSchedule::instance.Queue(lg);
4743 ge.link_graph = lg->index;
4744 ge.node = lg->AddNode(st);
4745 } else {
4746 Debug(misc, 0, "Can't allocate link graph");
4748 } else {
4749 lg = LinkGraph::Get(ge.link_graph);
4751 if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
4753 if (!ge.HasRating()) {
4754 InvalidateWindowData(WC_STATION_LIST, st->owner);
4755 SetBit(ge.status, GoodsEntry::GES_RATING);
4758 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
4759 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
4760 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
4761 TriggerRoadStopAnimation(st, st->xy, SAT_NEW_CARGO, type);
4762 TriggerRoadStopRandomisation(st, st->xy, RSRT_NEW_CARGO, type);
4764 SetWindowDirty(WC_STATION_VIEW, st->index);
4765 st->MarkTilesDirty(true);
4766 return amount;
4769 static bool IsUniqueStationName(const char *name)
4771 for (const Station *st : Station::Iterate()) {
4772 if (!st->name.empty() && st->name == name) return false;
4775 return true;
4779 * Rename a station
4780 * @param tile unused
4781 * @param flags operation to perform
4782 * @param p1 station ID that is to be renamed
4783 * @param p2 various bitstuffed elements
4784 * - p2 = (bit 0) - whether to generate a new default name, if resetting name
4785 * @param text the new name or an empty string when resetting to the default
4786 * @return the cost of this operation or an error
4788 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32_t p1, uint32_t p2, const char *text)
4790 Station *st = Station::GetIfValid(p1);
4791 if (st == nullptr) return CMD_ERROR;
4793 CommandCost ret = CheckOwnership(st->owner);
4794 if (ret.Failed()) return ret;
4796 bool reset = StrEmpty(text);
4798 if (!reset) {
4799 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
4800 if (!IsUniqueStationName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
4803 if (flags & DC_EXEC) {
4804 st->cached_name.clear();
4805 if (reset) {
4806 st->name.clear();
4807 if (HasBit(p2, 0) && st->industry == nullptr) {
4808 StationNaming name_class;
4809 if (st->facilities & FACIL_AIRPORT) {
4810 name_class = STATIONNAMING_AIRPORT;
4811 } else if (st->facilities & FACIL_DOCK) {
4812 name_class = STATIONNAMING_DOCK;
4813 } else if (st->facilities & FACIL_TRAIN) {
4814 name_class = STATIONNAMING_RAIL;
4815 } else if (st->facilities & (FACIL_BUS_STOP | FACIL_TRUCK_STOP)) {
4816 name_class = STATIONNAMING_ROAD;
4817 } else {
4818 name_class = STATIONNAMING_RAIL;
4820 Random(); // Advance random seed each time this is called
4821 st->string_id = GenerateStationName(st, st->xy, name_class, true);
4823 } else {
4824 st->name = text;
4827 st->UpdateVirtCoord();
4828 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
4831 return CommandCost();
4835 * Exchange station names
4836 * @param tile tile of other station to exchange name with
4837 * @param flags operation to perform
4838 * @param p1 station ID to exchange name with
4839 * @param p2 unused
4840 * @param text unused
4841 * @return the cost of this operation or an error
4843 CommandCost CmdExchangeStationNames(TileIndex tile, DoCommandFlag flags, uint32_t p1, uint32_t p2, const char *text)
4845 Station *st = Station::GetIfValid(p1);
4846 if (st == nullptr) return CMD_ERROR;
4848 CommandCost ret = CheckOwnership(st->owner);
4849 if (ret.Failed()) return ret;
4851 if (st->industry != nullptr) return CommandCost(STR_ERROR_STATION_ATTACHED_TO_INDUSTRY);
4853 if (!IsTileType(tile, MP_STATION)) return CommandCost(STR_ERROR_THERE_IS_NO_STATION);
4854 Station *st2 = Station::GetByTile(tile);
4856 ret = CheckOwnership(st2->owner);
4857 if (ret.Failed()) return ret;
4859 if (st2->industry != nullptr) return CommandCost(STR_ERROR_STATION_ATTACHED_TO_INDUSTRY);
4861 if (st->town != st2->town) return CommandCost(STR_ERROR_STATIONS_NOT_IN_SAME_TOWN);
4863 if (flags & DC_EXEC) {
4864 st->cached_name.clear();
4865 st2->cached_name.clear();
4866 std::swap(st->name, st2->name);
4867 std::swap(st->string_id, st2->string_id);
4868 std::swap(st->indtype, st2->indtype);
4869 std::swap(st->extra_name_index, st2->extra_name_index);
4870 st->UpdateVirtCoord();
4871 st2->UpdateVirtCoord();
4872 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
4875 return CommandCost();
4879 * Change whether a cargo may be supplied to a station
4880 * @param tile unused
4881 * @param flags operation to perform
4882 * @param p1 station ID
4883 * @param p2 various bitstuffed elements
4884 * - p2 = (bit 0- 7) - cargo ID
4885 * - p2 = (bit 8) - whether to allow supply
4886 * @param text unused
4887 * @return the cost of this operation or an error
4889 CommandCost CmdSetStationCargoAllowedSupply(TileIndex tile, DoCommandFlag flags, uint32_t p1, uint32_t p2, const char *text)
4891 Station *st = Station::GetIfValid(p1);
4892 if (st == nullptr) return CMD_ERROR;
4894 CommandCost ret = CheckOwnership(st->owner);
4895 if (ret.Failed()) return ret;
4897 CargoID cid = GB(p2, 0, 8);
4898 if (cid >= NUM_CARGO) return CMD_ERROR;
4900 if (flags & DC_EXEC) {
4901 GoodsEntry &ge = st->goods[cid];
4902 AssignBit(ge.status, GoodsEntry::GES_NO_CARGO_SUPPLY, !HasBit(p2, 8));
4903 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
4906 return CommandCost();
4909 static void AddNearbyStationsByCatchment(TileIndex tile, StationList &stations, StationList &nearby)
4911 for (Station *st : nearby) {
4912 if (st->TileIsInCatchment(tile)) stations.insert(st);
4917 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
4918 * @return pointer to a StationList containing all stations found
4920 const StationList &StationFinder::GetStations()
4922 if (this->tile != INVALID_TILE) {
4923 if (IsTileType(this->tile, MP_HOUSE)) {
4924 /* Town nearby stations need to be filtered per tile. */
4925 assert(this->w == 1 && this->h == 1);
4926 AddNearbyStationsByCatchment(this->tile, this->stations, Town::GetByTile(this->tile)->stations_near);
4927 } else {
4928 ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex) {
4929 this->stations.insert(st);
4930 return true;
4933 this->tile = INVALID_TILE;
4935 return this->stations;
4939 static bool CanMoveGoodsToStation(const Station *st, CargoID type)
4941 /* Is the station reserved exclusively for somebody else? */
4942 if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
4944 /* Lowest possible rating, better not to give cargo anymore. */
4945 if (st->goods[type].rating == 0) return false;
4947 if (!st->goods[type].IsSupplyAllowed()) return false;
4949 /* Selectively servicing stations, and not this one. */
4950 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) return false;
4952 if (IsCargoInClass(type, CC_PASSENGERS)) {
4953 /* Passengers are never served by just a truck stop. */
4954 if (st->facilities == FACIL_TRUCK_STOP) return false;
4955 } else {
4956 /* Non-passengers are never served by just a bus stop. */
4957 if (st->facilities == FACIL_BUS_STOP) return false;
4959 return true;
4962 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList &all_stations, Owner exclusivity)
4964 /* Return if nothing to do. Also the rounding below fails for 0. */
4965 if (all_stations.empty()) return 0;
4966 if (amount == 0) return 0;
4968 Station *first_station = nullptr;
4969 typedef std::pair<Station *, uint> StationInfo;
4970 std::vector<StationInfo> used_stations;
4972 for (Station *st : all_stations) {
4973 if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4974 if (!CanMoveGoodsToStation(st, type)) continue;
4976 /* Avoid allocating a vector if there is only one station to significantly
4977 * improve performance in this common case. */
4978 if (first_station == nullptr) {
4979 first_station = st;
4980 continue;
4982 if (used_stations.empty()) {
4983 used_stations.reserve(2);
4984 used_stations.emplace_back(first_station, 0);
4986 used_stations.emplace_back(st, 0);
4989 /* no stations around at all? */
4990 if (first_station == nullptr) return 0;
4992 if (used_stations.empty()) {
4993 /* only one station around */
4994 amount *= first_station->goods[type].rating + 1;
4995 return UpdateStationWaiting(first_station, type, amount, source_type, source_id);
4998 uint company_best[OWNER_NONE + 1] = {}; // best rating for each company, including OWNER_NONE
4999 uint company_sum[OWNER_NONE + 1] = {}; // sum of ratings for each company
5000 uint best_rating = 0;
5001 uint best_sum = 0; // sum of best ratings for each company
5003 for (auto &p : used_stations) {
5004 auto owner = p.first->owner;
5005 auto rating = p.first->goods[type].rating;
5006 if (rating > company_best[owner]) {
5007 best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
5008 company_best[owner] = rating;
5009 if (rating > best_rating) best_rating = rating;
5011 company_sum[owner] += rating;
5014 /* From now we'll calculate with fractional cargo amounts.
5015 * First determine how much cargo we really have. */
5016 amount *= best_rating + 1;
5018 uint moving = 0;
5019 for (auto &p : used_stations) {
5020 uint owner = p.first->owner;
5021 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
5022 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
5023 p.second = ((uint64_t) amount) * ((uint64_t) company_best[owner]) * ((uint64_t) p.first->goods[type].rating) / (best_sum * company_sum[owner]);
5024 moving += p.second;
5027 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
5028 if (amount > moving) {
5029 std::stable_sort(used_stations.begin(), used_stations.end(), [type](const StationInfo &a, const StationInfo &b) {
5030 return b.first->goods[type].rating < a.first->goods[type].rating;
5033 uint to_deliver = amount - moving;
5034 uint step_size = CeilDivT<uint>(to_deliver, (uint)used_stations.size());
5035 for (uint i = 0; i < used_stations.size() && to_deliver > 0; i++) {
5036 uint delivery = std::min<uint>(to_deliver, step_size);
5037 used_stations[i].second += delivery;
5038 to_deliver -= delivery;
5042 uint moved = 0;
5043 for (auto &p : used_stations) {
5044 moved += UpdateStationWaiting(p.first, type, p.second, source_type, source_id);
5047 return moved;
5050 void UpdateStationDockingTiles(Station *st)
5052 st->docking_station.Clear();
5053 st->docking_tiles.clear();
5055 /* For neutral stations, start with the industry area instead of dock area */
5056 const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
5058 if (area->tile == INVALID_TILE) return;
5060 int x = TileX(area->tile);
5061 int y = TileY(area->tile);
5063 /* Expand the area by a tile on each side while
5064 * making sure that we remain inside the map. */
5065 int x2 = std::min<int>(x + area->w + 1, MapSizeX());
5066 int x1 = std::max<int>(x - 1, 0);
5068 int y2 = std::min<int>(y + area->h + 1, MapSizeY());
5069 int y1 = std::max<int>(y - 1, 0);
5071 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
5072 for (TileIndex tile : ta) {
5073 if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
5077 void BuildOilRig(TileIndex tile)
5079 if (!Station::CanAllocateItem()) {
5080 Debug(misc, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
5081 return;
5084 Station *st = new Station(tile);
5085 _station_kdtree.Insert(st->index);
5086 st->town = ClosestTownFromTile(tile, UINT_MAX);
5088 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
5090 assert_tile(IsTileType(tile, MP_INDUSTRY), tile);
5091 /* Mark industry as associated both ways */
5092 st->industry = Industry::GetByTile(tile);
5093 st->industry->neutral_station = st;
5094 DeleteAnimatedTile(tile);
5095 MakeOilrig(tile, st->index, GetWaterClass(tile));
5097 st->owner = OWNER_NONE;
5098 st->airport.type = AT_OILRIG;
5099 st->airport.Add(tile);
5100 st->ship_station.Add(tile);
5101 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
5102 st->build_date = CalTime::CurDate();
5103 UpdateStationDockingTiles(st);
5105 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
5107 st->UpdateVirtCoord();
5109 /* An industry tile has now been replaced with a station tile, this may change the overlap between station catchments and industry tiles.
5110 * Recalculate the station catchment for all stations currently in the industry's nearby list.
5111 * Clear the industry's station nearby list first because Station::RecomputeCatchment cannot remove nearby industries in this case. */
5112 if (_settings_game.station.serve_neutral_industries) {
5113 StationList nearby = std::move(st->industry->stations_near);
5114 st->industry->stations_near.clear();
5115 for (Station *st_near : nearby) {
5116 st_near->RecomputeCatchment(true);
5117 UpdateStationAcceptance(st_near, true);
5121 st->RecomputeCatchment();
5122 UpdateStationAcceptance(st, false);
5123 ZoningMarkDirtyStationCoverageArea(st);
5126 void DeleteOilRig(TileIndex tile)
5128 Station *st = Station::GetByTile(tile);
5129 ZoningMarkDirtyStationCoverageArea(st);
5131 MakeWaterKeepingClass(tile, OWNER_NONE);
5133 assert(st->facilities == (FACIL_AIRPORT | FACIL_DOCK) && st->airport.type == AT_OILRIG);
5134 if (st->industry != nullptr && st->industry->neutral_station == st) {
5135 /* Don't leave dangling neutral station pointer */
5136 st->industry->neutral_station = nullptr;
5138 delete st;
5141 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
5143 if (IsAnyRoadStopTile(tile)) {
5144 for (RoadTramType rtt : _roadtramtypes) {
5145 /* Update all roadtypes, no matter if they are present */
5146 if (GetRoadOwner(tile, rtt) == old_owner) {
5147 RoadType rt = GetRoadType(tile, rtt);
5148 if (rt != INVALID_ROADTYPE) {
5149 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
5150 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
5151 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
5153 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
5158 if (!IsTileOwner(tile, old_owner)) return;
5160 if (new_owner != INVALID_OWNER) {
5161 /* Update company infrastructure counts. Only do it here
5162 * if the new owner is valid as otherwise the clear
5163 * command will do it for us. No need to dirty windows
5164 * here, we'll redraw the whole screen anyway.*/
5165 Company *old_company = Company::Get(old_owner);
5166 Company *new_company = Company::Get(new_owner);
5168 /* Update counts for underlying infrastructure. */
5169 switch (GetStationType(tile)) {
5170 case STATION_RAIL:
5171 case STATION_WAYPOINT:
5172 if (!IsStationTileBlocked(tile)) {
5173 old_company->infrastructure.rail[GetRailType(tile)]--;
5174 new_company->infrastructure.rail[GetRailType(tile)]++;
5176 break;
5178 case STATION_BUS:
5179 case STATION_TRUCK:
5180 case STATION_ROADWAYPOINT:
5181 /* Road stops were already handled above. */
5182 break;
5184 case STATION_BUOY:
5185 case STATION_DOCK:
5186 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
5187 old_company->infrastructure.water--;
5188 new_company->infrastructure.water++;
5190 break;
5192 default:
5193 break;
5196 /* Update station tile count. */
5197 if (!IsBuoy(tile) && !IsAirport(tile)) {
5198 old_company->infrastructure.station--;
5199 new_company->infrastructure.station++;
5202 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
5203 SetTileOwner(tile, new_owner);
5204 InvalidateWindowClassesData(WC_STATION_LIST, 0);
5205 } else {
5206 if (IsDriveThroughStopTile(tile)) {
5207 /* Remove the drive-through road stop */
5208 uint p2;
5209 switch (GetStationType(tile)) {
5210 case STATION_BUS:
5211 p2 = ROADSTOP_BUS;
5212 break;
5213 case STATION_TRUCK:
5214 p2 = ROADSTOP_TRUCK;
5215 break;
5216 case STATION_ROADWAYPOINT:
5217 p2 = (1 << 2);
5218 break;
5219 default:
5220 NOT_REACHED();
5222 DoCommand(tile, 1 | 1 << 8, p2, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
5223 assert_tile(IsTileType(tile, MP_ROAD), tile);
5224 /* Change owner of tile and all roadtypes */
5225 ChangeTileOwner(tile, old_owner, new_owner);
5226 } else {
5227 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
5228 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
5229 * Update owner of buoy if it was not removed (was in orders).
5230 * Do not update when owned by OWNER_WATER (sea and rivers). */
5231 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
5237 * Check if a drive-through road stop tile can be cleared.
5238 * Road stops built on town-owned roads check the conditions
5239 * that would allow clearing of the original road.
5240 * @param tile The road stop tile to check.
5241 * @param flags Command flags.
5242 * @return A succeeded command if the road can be removed, a failed command with the relevant error message otherwise.
5244 static CommandCost CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
5246 /* Water flooding can always clear road stops. */
5247 if (_current_company == OWNER_WATER) return CommandCost();
5249 CommandCost ret;
5251 if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
5252 Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
5253 if (tram_owner != OWNER_NONE) {
5254 ret = CheckOwnership(tram_owner);
5255 if (ret.Failed()) return ret;
5259 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
5260 Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
5261 if (road_owner == OWNER_TOWN) {
5262 ret = CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, RTT_ROAD), OWNER_TOWN, RTT_ROAD, flags);
5263 if (ret.Failed()) return ret;
5264 } else if (road_owner != OWNER_NONE) {
5265 ret = CheckOwnership(road_owner);
5266 if (ret.Failed()) return ret;
5270 return CommandCost();
5273 static CommandCost RemoveRoadStopAndUpdateRoadCachedOneWayState(TileIndex tile, DoCommandFlag flags)
5275 CommandCost cost = RemoveRoadStop(tile, flags);
5276 if ((flags & DC_EXEC) && cost.Succeeded()) UpdateRoadCachedOneWayStatesAroundTile(tile);
5277 return cost;
5281 * Clear a single tile of a station.
5282 * @param tile The tile to clear.
5283 * @param flags The DoCommand flags related to the "command".
5284 * @return The cost, or error of clearing.
5286 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
5288 if (flags & DC_AUTO) {
5289 switch (GetStationType(tile)) {
5290 default: break;
5291 case STATION_RAIL: return CommandCost(STR_ERROR_MUST_DEMOLISH_RAILROAD);
5292 case STATION_WAYPOINT: return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
5293 case STATION_ROADWAYPOINT: return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
5294 case STATION_AIRPORT: return CommandCost(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
5295 case STATION_TRUCK: return CommandCost(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
5296 case STATION_BUS: return CommandCost(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
5297 case STATION_BUOY: return CommandCost(STR_ERROR_BUOY_IN_THE_WAY);
5298 case STATION_DOCK: return CommandCost(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
5299 case STATION_OILRIG:
5300 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
5301 return CommandCost(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
5305 switch (GetStationType(tile)) {
5306 case STATION_RAIL: return RemoveRailStation(tile, flags);
5307 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
5308 case STATION_AIRPORT: return RemoveAirport(tile, flags);
5309 case STATION_TRUCK: [[fallthrough]];
5310 case STATION_BUS:
5311 if (IsDriveThroughStopTile(tile)) {
5312 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
5313 if (remove_road.Failed()) return remove_road;
5315 return RemoveRoadStopAndUpdateRoadCachedOneWayState(tile, flags);
5316 case STATION_BUOY: return RemoveBuoy(tile, flags);
5317 case STATION_DOCK: return RemoveDock(tile, flags);
5318 case STATION_ROADWAYPOINT:
5319 if (IsDriveThroughStopTile(tile)) {
5320 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
5321 if (remove_road.Failed()) return remove_road;
5323 return RemoveRoadStopAndUpdateRoadCachedOneWayState(tile, flags);
5324 default: break;
5327 return CMD_ERROR;
5330 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
5332 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
5333 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
5334 * TTDP does not call it.
5336 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
5337 switch (GetStationType(tile)) {
5338 case STATION_WAYPOINT:
5339 case STATION_RAIL: {
5340 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetRailStationAxis(tile))) break;
5341 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
5344 case STATION_AIRPORT:
5345 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
5347 case STATION_TRUCK:
5348 case STATION_BUS:
5349 case STATION_ROADWAYPOINT: {
5350 if (IsDriveThroughStopTile(tile)) {
5351 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetDriveThroughStopAxis(tile))) break;
5352 } else {
5353 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetBayRoadStopDir(tile))) break;
5355 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
5358 default: break;
5362 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
5365 FlowStat::iterator FlowStat::erase_item(FlowStat::iterator iter, uint flow_reduction)
5367 assert(!this->empty());
5368 const uint offset = iter - this->begin();
5369 const iterator last = this->end() - 1;
5370 for (; iter < last; ++iter) {
5371 *iter = { (iter + 1)->first - flow_reduction, (iter + 1)->second };
5373 --this->count;
5374 if (this->count == 2) {
5375 // transition from external to internal storage
5376 ShareEntry *ptr = this->storage.ptr_shares.buffer;
5377 this->storage.inline_shares[0] = ptr[0];
5378 this->storage.inline_shares[1] = ptr[1];
5379 free(ptr);
5381 return this->begin() + offset;
5385 * Get flow for a station.
5386 * @param st Station to get flow for.
5387 * @return Flow for st.
5389 uint FlowStat::GetShare(StationID st) const
5391 uint32_t prev = 0;
5392 for (const_iterator it = this->begin(); it != this->end(); ++it) {
5393 if (it->second == st) {
5394 return it->first - prev;
5395 } else {
5396 prev = it->first;
5399 return 0;
5403 * Get a station a package can be routed to, but exclude the given ones.
5404 * @param excluded StationID not to be selected.
5405 * @param excluded2 Another StationID not to be selected.
5406 * @return A station ID from the shares map.
5408 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
5410 if (this->unrestricted == 0) return INVALID_STATION;
5411 assert(!this->empty());
5412 const_iterator it = std::upper_bound(this->data(), this->data() + this->count, RandomRange(this->unrestricted));
5413 assert(it != this->end() && it->first <= this->unrestricted);
5414 if (it->second != excluded && it->second != excluded2) return it->second;
5416 /* We've hit one of the excluded stations.
5417 * Draw another share, from outside its range. */
5419 uint end = it->first;
5420 uint begin = (it == this->begin() ? 0 : (--it)->first);
5421 uint interval = end - begin;
5422 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
5423 uint new_max = this->unrestricted - interval;
5424 uint rand = RandomRange(new_max);
5425 const_iterator it2 = (rand < begin) ? this->upper_bound(rand) :
5426 this->upper_bound(rand + interval);
5427 assert(it2 != this->end() && it2->first <= this->unrestricted);
5428 if (it2->second != excluded && it2->second != excluded2) return it2->second;
5430 /* We've hit the second excluded station.
5431 * Same as before, only a bit more complicated. */
5433 uint end2 = it2->first;
5434 uint begin2 = (it2 == this->begin() ? 0 : (--it2)->first);
5435 uint interval2 = end2 - begin2;
5436 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
5437 new_max -= interval2;
5438 if (begin > begin2) {
5439 Swap(begin, begin2);
5440 Swap(end, end2);
5441 Swap(interval, interval2);
5443 rand = RandomRange(new_max);
5444 const_iterator it3 = this->upper_bound(this->unrestricted);
5445 if (rand < begin) {
5446 it3 = this->upper_bound(rand);
5447 } else if (rand < begin2 - interval) {
5448 it3 = this->upper_bound(rand + interval);
5449 } else {
5450 it3 = this->upper_bound(rand + interval + interval2);
5452 assert(it3 != this->end() && it3->first <= this->unrestricted);
5453 return it3->second;
5457 * Change share for specified station. By specifying INT_MIN as parameter you
5458 * can erase a share. Newly added flows will be unrestricted.
5459 * @param st Next Hop to be removed.
5460 * @param flow Share to be added or removed.
5462 void FlowStat::ChangeShare(StationID st, int flow)
5464 /* We assert only before changing as afterwards the shares can actually
5465 * be empty. In that case the whole flow stat must be deleted then. */
5466 assert(!this->empty());
5468 uint last_share = 0;
5469 for (iterator it(this->begin()); it != this->end(); ++it) {
5470 if (it->second == st) {
5471 uint share = it->first - last_share;
5472 if (flow < 0 && (flow == INT_MIN || (uint)(-flow) >= share)) {
5473 if (it->first <= this->unrestricted) this->unrestricted -= share;
5474 this->erase_item(it, share);
5475 break; // remove the whole share
5477 if (it->first <= this->unrestricted) this->unrestricted += flow;
5478 for (; it != this->end(); ++it) {
5479 it->first += flow;
5481 flow = 0;
5482 break;
5484 last_share = it->first;
5486 if (flow > 0) {
5487 // must be non-empty here
5488 last_share = (this->end() - 1)->first;
5489 this->AppendShare(st, (uint)flow, true); // true to avoid changing this->unrestricted, which we fixup below
5490 if (this->unrestricted < last_share) {
5491 // Move to front to unrestrict
5492 this->ReleaseShare(st);
5493 } else {
5494 // First restricted item, so bump unrestricted count
5495 this->unrestricted += flow;
5501 * Restrict a flow by moving it to the end of the map and decreasing the amount
5502 * of unrestricted flow.
5503 * @param st Station of flow to be restricted.
5505 void FlowStat::RestrictShare(StationID st)
5507 assert(!this->empty());
5508 iterator it = this->begin();
5509 const iterator end = this->end();
5510 uint last_share = 0;
5511 for (; it != end; ++it) {
5512 if (it->first > this->unrestricted) return; // Not present or already restricted.
5513 if (it->second == st) {
5514 uint flow = it->first - last_share;
5515 this->unrestricted -= flow;
5516 if (this->unrestricted == last_share) return; // No further action required
5517 const iterator last = end - 1;
5518 for (iterator jt = it; jt != last; ++jt) {
5519 *jt = { (jt + 1)->first - flow, (jt + 1)->second };
5521 *last = { flow + (last - 1)->first, st };
5522 return;
5524 last_share = it->first;
5529 * Release ("unrestrict") a flow by moving it to the begin of the map and
5530 * increasing the amount of unrestricted flow.
5531 * @param st Station of flow to be released.
5533 void FlowStat::ReleaseShare(StationID st)
5535 assert(!this->empty());
5536 iterator it = this->end() - 1;
5537 const iterator start = this->begin();
5538 for (; it >= start; --it) {
5539 if (it->first < this->unrestricted) return; // Already unrestricted
5540 if (it->second == st) {
5541 if (it - 1 >= start) {
5542 uint flow = it->first - (it - 1)->first;
5543 this->unrestricted += flow;
5544 if (it->first == this->unrestricted) return; // No further action required
5545 for (iterator jt = it; jt != start; --jt) {
5546 *jt = { (jt - 1)->first + flow, (jt - 1)->second };
5548 *start = { flow, st };
5549 } else {
5550 // already at start
5551 this->unrestricted = it->first;
5553 return;
5559 * Scale all shares from link graph's runtime to monthly values.
5560 * @param runtime Time the link graph has been running without compression, in scaled ticks.
5561 * @param day_length_factor Day length factor to use.
5562 * @pre runtime must be greater than 0 as we don't want infinite flow values.
5564 void FlowStat::ScaleToMonthly(uint runtime, uint8_t day_length_factor)
5566 assert(runtime > 0);
5567 uint share = 0;
5568 for (iterator i = this->begin(); i != this->end(); ++i) {
5569 share = std::max(share + 1, ClampTo<uint>((static_cast<uint64_t>(i->first) * 30 * DAY_TICKS * day_length_factor) / runtime));
5570 if (this->unrestricted == i->first) this->unrestricted = share;
5571 i->first = share;
5576 * Add some flow from "origin", going via "via".
5577 * @param origin Origin of the flow.
5578 * @param via Next hop.
5579 * @param flow Amount of flow to be added.
5581 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
5583 FlowStatMap::iterator origin_it = this->find(origin);
5584 if (origin_it == this->end()) {
5585 this->insert(FlowStat(origin, via, flow));
5586 } else {
5587 origin_it->ChangeShare(via, flow);
5588 assert(!origin_it->empty());
5593 * Pass on some flow, remembering it as invalid, for later subtraction from
5594 * locally consumed flow. This is necessary because we can't have negative
5595 * flows and we don't want to sort the flows before adding them up.
5596 * @param origin Origin of the flow.
5597 * @param via Next hop.
5598 * @param flow Amount of flow to be passed.
5600 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
5602 FlowStatMap::iterator prev_it = this->find(origin);
5603 if (prev_it == this->end()) {
5604 FlowStat fs(origin, via, flow);
5605 fs.AppendShare(INVALID_STATION, flow);
5606 this->insert(std::move(fs));
5607 } else {
5608 prev_it->ChangeShare(via, flow);
5609 prev_it->ChangeShare(INVALID_STATION, flow);
5610 assert(!prev_it->empty());
5615 * Subtract invalid flows from locally consumed flow.
5616 * @param self ID of own station.
5618 void FlowStatMap::FinalizeLocalConsumption(StationID self)
5620 for (FlowStat &fs : *this) {
5621 uint local = fs.GetShare(INVALID_STATION);
5622 if (local > INT_MAX) { // make sure it fits in an int
5623 fs.ChangeShare(self, -INT_MAX);
5624 fs.ChangeShare(INVALID_STATION, -INT_MAX);
5625 local -= INT_MAX;
5627 fs.ChangeShare(self, -(int)local);
5628 fs.ChangeShare(INVALID_STATION, -(int)local);
5630 /* If the local share is used up there must be a share for some
5631 * remote station. */
5632 assert(!fs.empty());
5637 * Delete all flows at a station for specific cargo and destination.
5638 * @param via Remote station of flows to be deleted.
5639 * @return IDs of source stations for which the complete FlowStat, not only a
5640 * share, has been erased.
5642 StationIDStack FlowStatMap::DeleteFlows(StationID via)
5644 StationIDStack ret;
5645 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
5646 FlowStat &s_flows = *f_it;
5647 s_flows.ChangeShare(via, INT_MIN);
5648 if (s_flows.empty()) {
5649 ret.Push(f_it->GetOrigin());
5650 f_it = this->erase(f_it);
5651 } else {
5652 ++f_it;
5655 return ret;
5659 * Restrict all flows at a station for specific cargo and destination.
5660 * @param via Remote station of flows to be restricted.
5662 void FlowStatMap::RestrictFlows(StationID via)
5664 for (FlowStat &it : *this) {
5665 it.RestrictShare(via);
5670 * Get the sum of all flows from this FlowStatMap.
5671 * @return sum of all flows.
5673 uint FlowStatMap::GetFlow() const
5675 uint ret = 0;
5676 for (const FlowStat &it : this->IterateUnordered()) {
5677 if (it.IsInvalid()) continue;
5678 ret += (it.end() - 1)->first;
5680 return ret;
5684 * Get the sum of flows via a specific station from this FlowStatMap.
5685 * @param via Remote station to look for.
5686 * @return all flows for 'via' added up.
5688 uint FlowStatMap::GetFlowVia(StationID via) const
5690 uint ret = 0;
5691 for (const FlowStat &it : this->IterateUnordered()) {
5692 if (it.IsInvalid()) continue;
5693 ret += it.GetShare(via);
5695 return ret;
5699 * Get the sum of flows from a specific station from this FlowStatMap.
5700 * @param from Origin station to look for.
5701 * @return all flows from 'from' added up.
5703 uint FlowStatMap::GetFlowFrom(StationID from) const
5705 FlowStatMap::const_iterator i = this->find(from);
5706 if (i == this->end()) return 0;
5707 if (i->IsInvalid()) return 0;
5708 return (i->end() - 1)->first;
5712 * Get the flow from a specific station via a specific other station.
5713 * @param from Origin station to look for.
5714 * @param via Remote station to look for.
5715 * @return flow share originating at 'from' and going to 'via'.
5717 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
5719 FlowStatMap::const_iterator i = this->find(from);
5720 if (i == this->end()) return 0;
5721 if (i->IsInvalid()) return 0;
5722 return i->GetShare(via);
5725 void FlowStatMap::SortStorage()
5727 assert(this->flows_storage.size() == this->flows_index.size());
5728 std::sort(this->flows_storage.begin(), this->flows_storage.end(), [](const FlowStat &a, const FlowStat &b) -> bool {
5729 return a.origin < b.origin;
5731 uint16_t index = 0;
5732 for (auto &it : this->flows_index) {
5733 it.second = index;
5734 index++;
5738 void DumpStationFlowStats(format_target &buffer)
5740 btree::btree_map<uint, uint> count_map;
5741 btree::btree_map<uint, uint> invalid_map;
5742 for (const Station *st : Station::Iterate()) {
5743 for (CargoID i = 0; i < NUM_CARGO; i++) {
5744 const GoodsEntry &ge = st->goods[i];
5745 if (ge.data == nullptr) continue;
5746 for (FlowStatMap::const_iterator it(ge.data->flows.begin()); it != ge.data->flows.end(); ++it) {
5747 count_map[(uint32_t)it->size()]++;
5748 invalid_map[it->GetRawFlags() & 0x1F]++;
5752 buffer.append("Flow state shares size distribution:\n");
5753 for (const auto &it : count_map) {
5754 buffer.format("{:<5} {:<5}\n", it.first, it.second);
5756 buffer.append("Flow state shares invalid state distribution:\n");
5757 for (const auto &it : invalid_map) {
5758 buffer.format("{:<2} {:<5}\n", it.first, it.second);
5762 extern const TileTypeProcs _tile_type_station_procs = {
5763 DrawTile_Station, // draw_tile_proc
5764 GetSlopePixelZ_Station, // get_slope_z_proc
5765 ClearTile_Station, // clear_tile_proc
5766 nullptr, // add_accepted_cargo_proc
5767 GetTileDesc_Station, // get_tile_desc_proc
5768 GetTileTrackStatus_Station, // get_tile_track_status_proc
5769 ClickTile_Station, // click_tile_proc
5770 AnimateTile_Station, // animate_tile_proc
5771 TileLoop_Station, // tile_loop_proc
5772 ChangeTileOwner_Station, // change_tile_owner_proc
5773 nullptr, // add_produced_cargo_proc
5774 VehicleEnter_Station, // vehicle_enter_tile_proc
5775 GetFoundation_Station, // get_foundation_proc
5776 TerraformTile_Station, // terraform_tile_proc