OpenTTD Source 20261129-master-g72a8bdc861
station_cmd.cpp
Go to the documentation of this file.
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "core/flatset_type.hpp"
12#include "aircraft.h"
13#include "bridge.h"
14#include "bridge_map.h"
15#include "misc/history_func.hpp"
16#include "tilearea_spiral.h"
17#include "vehiclelist_func.h"
18#include "viewport_func.h"
19#include "viewport_kdtree.h"
20#include "command_func.h"
21#include "town.h"
22#include "news_func.h"
23#include "train.h"
24#include "ship.h"
25#include "roadveh.h"
26#include "industry.h"
27#include "newgrf_cargo.h"
28#include "newgrf_debug.h"
29#include "newgrf_station.h"
30#include "newgrf_canal.h" /* For the buoy */
32#include "road_internal.h" /* For drawing catenary/checking road removal */
33#include "autoslope.h"
34#include "water.h"
35#include "tilehighlight_func.h"
36#include "strings_func.h"
37#include "clear_func.h"
39#include "vehicle_func.h"
40#include "string_func.h"
41#include "animated_tile_func.h"
42#include "elrail_func.h"
43#include "station_base.h"
44#include "station_func.h"
45#include "station_kdtree.h"
46#include "roadstop_base.h"
47#include "newgrf_railtype.h"
48#include "newgrf_roadtype.h"
49#include "waypoint_base.h"
50#include "waypoint_func.h"
51#include "pbs.h"
52#include "debug.h"
53#include "core/random_func.hpp"
55#include "company_base.h"
57#include "newgrf_airporttiles.h"
58#include "order_backup.h"
59#include "newgrf_house.h"
60#include "company_gui.h"
62#include "linkgraph/refresh.h"
63#include "station_cmd.h"
64#include "waypoint_cmd.h"
65#include "landscape_cmd.h"
66#include "rail_cmd.h"
67#include "newgrf_roadstop.h"
68#include "timer/timer.h"
72#include "cheat_type.h"
73#include "road_func.h"
74#include "station_layout_type.h"
75#include "tilearea_airport.h"
77
79
80#include "table/strings.h"
81#include "table/station_land.h"
82
83#include <bitset>
84
85#include "safeguards.h"
86
92/* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
93
101{
102 assert(IsTileType(t, TileType::Station));
103
104 /* If the tile isn't an airport there's no chance it's a hangar. */
105 if (!IsAirport(t)) return false;
106
107 const Station *st = Station::GetByTile(t);
108 const AirportSpec *as = st->airport.GetSpec();
109
110 for (const auto &depot : as->depots) {
111 if (st->airport.GetRotatedTileFromOffset(depot.ti) == TileIndex(t)) return true;
112 }
113
114 return false;
115}
116
126template <class T, class F>
127CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st, F filter)
128{
129 ta.Expand(1);
130
131 /* check around to see if there are any stations there owned by the company */
132 for (TileIndex tile_cur : ta) {
133 if (IsTileType(tile_cur, TileType::Station)) {
134 StationID t = GetStationIndex(tile_cur);
135 if (!T::IsValidID(t) || T::Get(t)->owner != company || !filter(T::Get(t))) continue;
136 if (closest_station == StationID::Invalid()) {
137 closest_station = t;
138 } else if (closest_station != t) {
139 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
140 }
141 }
142 }
143 *st = (closest_station == StationID::Invalid()) ? nullptr : T::Get(closest_station);
144 return CommandCost();
145}
146
152typedef bool (*CMSAMatcher)(TileIndex tile);
153
161{
162 int num = 0;
163
164 for (int dx = -3; dx <= 3; dx++) {
165 for (int dy = -3; dy <= 3; dy++) {
166 TileIndex t = TileAddWrap(tile, dx, dy);
167 if (t != INVALID_TILE && cmp(t)) num++;
168 }
169 }
170
171 return num;
172}
173
179static bool CMSAMine(TileIndex tile)
180{
181 /* No industry */
182 if (!IsTileType(tile, TileType::Industry)) return false;
183
184 const Industry *ind = Industry::GetByTile(tile);
185
186 /* No extractive industry */
188
189 for (const auto &p : ind->produced) {
190 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
191 * Also the production of passengers and mail is ignored. */
192 if (IsValidCargoType(p.cargo) &&
193 !CargoSpec::Get(p.cargo)->classes.Any({CargoClass::Liquid, CargoClass::Passengers, CargoClass::Mail})) {
194 return true;
195 }
196 }
197
198 return false;
199}
200
206static bool CMSAWater(TileIndex tile)
207{
208 return IsTileType(tile, TileType::Water) && IsWater(tile);
209}
210
216static bool CMSATree(TileIndex tile)
217{
218 return IsTileType(tile, TileType::Trees);
219}
220
230
233 std::bitset<(STR_SV_STNAME_FALLBACK - STR_SV_STNAME).base()> used_names;
234 std::bitset<NUM_INDUSTRYTYPES> indtypes;
235
241 bool IsAvailable(StringID str) const
242 {
243 assert(IsInsideMM(str, STR_SV_STNAME, STR_SV_STNAME_FALLBACK));
244 return !this->used_names.test((str - STR_SV_STNAME).base());
245 }
246
252 {
253 assert(IsInsideMM(str, STR_SV_STNAME, STR_SV_STNAME_FALLBACK));
254 this->used_names.set((str - STR_SV_STNAME).base());
255 }
256};
257
267{
268 const Town *t = st->town;
269
271
272 for (const Station *s : Station::Iterate()) {
273 if (s != st && s->town == t) {
274 if (s->indtype != IT_INVALID) {
275 sni.indtypes[s->indtype] = true;
276 StringID name = GetIndustrySpec(s->indtype)->station_name;
277 if (name != STR_UNDEFINED) {
278 /* Filter for other industrytypes with the same name */
279 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
280 const IndustrySpec *indsp = GetIndustrySpec(it);
281 if (indsp->enabled && indsp->station_name == name) sni.indtypes[it] = true;
282 }
283 }
284 continue;
285 }
286 if (IsInsideMM(s->string_id, STR_SV_STNAME, STR_SV_STNAME_FALLBACK)) {
287 auto str = s->string_id;
288 if (str == STR_SV_STNAME_FOREST) str = STR_SV_STNAME_WOODS;
289 sni.SetUsed(str);
290 }
291 }
292 }
293
294 for (auto indtile : SpiralTileSequence(tile, 7)) {
295 if (!IsTileType(indtile, TileType::Industry)) continue;
296
297 /* If the station name is undefined it means that it doesn't name a station */
298 IndustryType indtype = GetIndustryType(indtile);
299 const IndustrySpec *indsp = GetIndustrySpec(indtype);
300 if (indsp->station_name == STR_UNDEFINED) continue;
301
302 /* In all cases if an industry that provides a name is found two of
303 * the standard names will be disabled. */
304 sni.SetUsed(STR_SV_STNAME_OILFIELD);
305 sni.SetUsed(STR_SV_STNAME_MINES);
306 if (sni.indtypes[indtype]) continue;
307
308 /* STR_NULL means it only disables oil rig/mines */
309 if (indsp->station_name != STR_NULL) {
310 st->indtype = indtype;
311 return STR_SV_STNAME_FALLBACK;
312 }
313 break;
314 }
315
316 /* check default names
317 * Oil rigs/mines name could be marked not free by looking for a near by industry. */
318 switch (name_class) {
320 if (sni.IsAvailable(STR_SV_STNAME_AIRPORT)) return STR_SV_STNAME_AIRPORT;
321 break;
323 if (sni.IsAvailable(STR_SV_STNAME_OILFIELD)) return STR_SV_STNAME_OILFIELD;
324 break;
326 if (sni.IsAvailable(STR_SV_STNAME_DOCKS)) return STR_SV_STNAME_DOCKS;
327 break;
329 if (sni.IsAvailable(STR_SV_STNAME_HELIPORT)) return STR_SV_STNAME_HELIPORT;
330 break;
331 default:
332 break;
333 };
334
335 /* check mine? */
336 if (sni.IsAvailable(STR_SV_STNAME_MINES)) {
337 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
338 return STR_SV_STNAME_MINES;
339 }
340 }
341
342 /* check close enough to town to get central as name? */
343 if (DistanceMax(tile, t->xy) < 8) {
344 if (sni.IsAvailable(STR_SV_STNAME)) return STR_SV_STNAME;
345 if (sni.IsAvailable(STR_SV_STNAME_CENTRAL)) return STR_SV_STNAME_CENTRAL;
346 }
347
348 /* Check lakeside */
349 if (sni.IsAvailable(STR_SV_STNAME_LAKESIDE) &&
350 DistanceFromEdge(tile) < 20 &&
351 CountMapSquareAround(tile, CMSAWater) >= 5) {
352 return STR_SV_STNAME_LAKESIDE;
353 }
354
355 /* Check woods */
356 if (sni.IsAvailable(STR_SV_STNAME_WOODS) && (
357 CountMapSquareAround(tile, CMSATree) >= 8 ||
359 ) {
360 return _settings_game.game_creation.landscape == LandscapeType::Tropic ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
361 }
362
363 /* check elevation compared to town */
364 int z = GetTileZ(tile);
365 int z2 = GetTileZ(t->xy);
366 if (z < z2) {
367 if (sni.IsAvailable(STR_SV_STNAME_VALLEY)) return STR_SV_STNAME_VALLEY;
368 } else if (z > z2) {
369 if (sni.IsAvailable(STR_SV_STNAME_HEIGHTS)) return STR_SV_STNAME_HEIGHTS;
370 }
371
372 /* check direction compared to town */
373 if (TileX(tile) < TileX(t->xy)) {
374 sni.SetUsed(STR_SV_STNAME_SOUTH);
375 sni.SetUsed(STR_SV_STNAME_WEST);
376 } else {
377 sni.SetUsed(STR_SV_STNAME_NORTH);
378 sni.SetUsed(STR_SV_STNAME_EAST);
379 }
380 if (TileY(tile) < TileY(t->xy)) {
381 sni.SetUsed(STR_SV_STNAME_SOUTH);
382 sni.SetUsed(STR_SV_STNAME_EAST);
383 } else {
384 sni.SetUsed(STR_SV_STNAME_NORTH);
385 sni.SetUsed(STR_SV_STNAME_WEST);
386 }
387
389 static const StringID fallback_names[] = {
390 STR_SV_STNAME_NORTH,
391 STR_SV_STNAME_SOUTH,
392 STR_SV_STNAME_EAST,
393 STR_SV_STNAME_WEST,
394 STR_SV_STNAME_TRANSFER,
395 STR_SV_STNAME_HALT,
396 STR_SV_STNAME_EXCHANGE,
397 STR_SV_STNAME_ANNEXE,
398 STR_SV_STNAME_SIDINGS,
399 STR_SV_STNAME_BRANCH,
400 STR_SV_STNAME_UPPER,
401 STR_SV_STNAME_LOWER,
402 };
403 for (auto str : fallback_names) {
404 if (sni.IsAvailable(str)) return str;
405 }
406 return STR_SV_STNAME_FALLBACK;
407}
408
415{
416 uint threshold = 8;
417
418 Station *best_station = nullptr;
419 ForAllStationsRadius(tile, threshold, [&](Station *st) {
420 if (!st->IsInUse() && st->owner == _current_company) {
421 uint cur_dist = DistanceManhattan(tile, st->xy);
422
423 if (cur_dist < threshold) {
424 threshold = cur_dist;
425 best_station = st;
426 } else if (cur_dist == threshold && best_station != nullptr) {
427 /* In case of a tie, lowest station ID wins */
428 if (st->index < best_station->index) best_station = st;
429 }
430 }
431 });
432
433 return best_station;
434}
435
436
438{
439 switch (type) {
440 case StationType::Rail: return this->train_station;
441 case StationType::Airport: return this->airport;
442 case StationType::Truck: return this->truck_station;
443 case StationType::Bus: return this->bus_station;
445 case StationType::Oilrig: return this->docking_station;
446 default: NOT_REACHED();
447 }
448}
449
454{
455 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
456
457 pt.y -= 32 * ZOOM_BASE;
458 if (this->facilities.Test(StationFacility::Airport) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_BASE;
459
460 if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
461
462 this->sign.UpdatePosition(pt.x, pt.y, GetString(STR_VIEWPORT_STATION, this->index, this->facilities), GetString(STR_STATION_NAME, this->index, this->facilities));
463
464 _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
465
466 SetWindowDirty(WindowClass::StationView, this->index);
467}
468
474{
475 if (this->xy == new_xy) return;
476
477 _station_kdtree.Remove(this->index);
478
479 this->BaseStation::MoveSign(new_xy);
480
481 _station_kdtree.Insert(this->index);
482}
483
486{
487 for (BaseStation *st : BaseStation::Iterate()) {
488 st->UpdateVirtCoord();
489 }
490}
491
492void BaseStation::FillCachedName() const
493{
494 auto tmp_params = MakeParameters(this->index);
495 this->cached_name = GetStringWithArgs(Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, tmp_params);
496}
497
498void ClearAllStationCachedNames()
499{
500 for (BaseStation *st : BaseStation::Iterate()) {
501 st->cached_name.clear();
502 }
503}
504
511{
512 CargoTypes mask{};
513
514 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
515 if (it->status.Test(GoodsEntry::State::Acceptance)) mask.Set(static_cast<CargoType>(std::distance(std::begin(st->goods), it)));
516 }
517 return mask;
518}
519
526{
527 CargoTypes mask{};
528
529 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
530 if (it->TotalCount() > 0) mask.Set(static_cast<CargoType>(std::distance(std::begin(st->goods), it)));
531 }
532 return mask;
533}
534
541static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
542{
543 StringID msg = reject ? STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_LIST : STR_NEWS_STATION_NOW_ACCEPTS_CARGO_LIST;
545}
546
555CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
556{
557 CargoArray produced{};
558 FlatSet<IndustryID> industries;
559 TileArea ta = TileArea(north_tile, w, h).Expand(rad);
560
561 /* Loop over all tiles to get the produced cargo of
562 * everything except industries */
563 for (TileIndex tile : ta) {
564 if (IsTileType(tile, TileType::Industry)) industries.insert(GetIndustryIndex(tile));
565 AddProducedCargo(tile, produced);
566 }
567
568 /* Loop over the seen industries. They produce cargo for
569 * anything that is within 'rad' of any one of their tiles.
570 */
571 for (IndustryID industry : industries) {
572 const Industry *i = Industry::Get(industry);
573 /* Skip industry with neutral station */
574 if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
575
576 for (const auto &p : i->produced) {
577 if (IsValidCargoType(p.cargo)) produced[p.cargo]++;
578 }
579 }
580
581 return produced;
582}
583
592std::pair<CargoArray, CargoTypes> GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad)
593{
594 CargoArray acceptance{};
595 CargoTypes always_accepted{};
596
597 TileArea ta = TileArea(center_tile, w, h).Expand(rad);
598
599 for (TileIndex tile : ta) {
600 /* Ignore industry if it has a neutral station. */
601 if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, TileType::Industry) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
602
603 AddAcceptedCargo(tile, acceptance, always_accepted);
604 }
605
606 return {acceptance, always_accepted};
607}
608
614static std::pair<CargoArray, CargoTypes> GetAcceptanceAroundStation(const Station *st)
615{
616 CargoArray acceptance{};
617 CargoTypes always_accepted{};
618
619 for (TileIndex tile : st->catchment_tiles) {
620 AddAcceptedCargo(tile, acceptance, always_accepted);
621 }
622
623 return {acceptance, always_accepted};
624}
625
631void UpdateStationAcceptance(Station *st, bool show_msg)
632{
633 /* old accepted goods types */
634 CargoTypes old_acc = GetAcceptanceMask(st);
635
636 /* And retrieve the acceptance. */
637 CargoArray acceptance{};
638 if (!st->spread.IsEmpty()) {
639 std::tie(acceptance, st->always_accepted) = GetAcceptanceAroundStation(st);
640 }
641
642 /* Adjust in case our station only accepts fewer kinds of goods */
643 for (CargoType cargo : EnumRange(NUM_CARGO)) {
644 uint amt = acceptance[cargo];
645
646 /* Make sure the station can accept the goods type. */
647 bool is_passengers = IsCargoInClass(cargo, CargoClass::Passengers);
648 if ((!is_passengers && !st->facilities.Any({StationFacility::Train, StationFacility::TruckStop, StationFacility::Airport, StationFacility::Dock})) ||
649 (is_passengers && !st->facilities.Any({StationFacility::Train, StationFacility::BusStop, StationFacility::Airport, StationFacility::Dock}))) {
650 amt = 0;
651 }
652
653 GoodsEntry &ge = st->goods[cargo];
656 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
657 }
658 }
659
660 /* Only show a message in case the acceptance was actually changed. */
661 CargoTypes new_acc = GetAcceptanceMask(st);
662 if (old_acc == new_acc) return;
663
664 /* show a message to report that the acceptance was changed? */
665 if (show_msg && st->owner == _local_company && st->IsInUse()) {
666 /* Combine old and new masks to get changes */
667 CargoTypes accepts = new_acc & CargoTypes{old_acc}.Flip();
668 CargoTypes rejects = CargoTypes{new_acc}.Flip() & old_acc;
669
670 /* Show news message if there are any changes */
671 if (accepts.Any()) ShowRejectOrAcceptNews(st, accepts, false);
672 if (rejects.Any()) ShowRejectOrAcceptNews(st, rejects, true);
673 }
674
675 /* redraw the station view since acceptance changed */
676 SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_ACCEPT_RATING_LIST);
677}
678
679static void UpdateStationSignCoord(BaseStation *st)
680{
681 if (st->spread.IsEmpty()) return; // no tiles belong to this station
682
683 /* clamp sign coord to be inside the station rect */
684 if (!st->spread.Contains(st->xy)) {
685 int left = TileX(st->spread.tile);
686 int right = left + st->spread.w - 1;
687 int top = TileY(st->spread.tile);
688 int bottom = top + st->spread.h - 1;
689
690 TileIndex new_xy = TileXY(ClampU(TileX(st->xy), left, right), ClampU(TileY(st->xy), top, bottom));
691 st->MoveSign(new_xy);
692 }
693
694 if (!Station::IsExpected(st)) return;
695 Station *full_station = Station::From(st);
696 for (const GoodsEntry &ge : full_station->goods) {
697 LinkGraphID lg = ge.link_graph;
698 if (!LinkGraph::IsValidID(lg)) continue;
699 (*LinkGraph::Get(lg))[ge.node].UpdateLocation(st->xy);
700 }
701}
702
712static CommandCost BuildStationPart(Station **st, DoCommandFlags flags, bool reuse, TileArea area, StationNaming name_class)
713{
714 /* Find a deleted station close to us */
715 if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
716
717 if (*st != nullptr) {
718 if ((*st)->owner != _current_company) {
719 return CommandCost(CMD_ERROR);
720 }
721
722 CommandCost ret = CheckStationSpread((*st)->spread, area);
723 if (ret.Failed()) return ret;
724 } else {
725 /* allocate and initialize new station */
726 if (!Station::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_STATIONS_LOADING);
727
728 if (flags.Test(DoCommandFlag::Execute)) {
729 *st = Station::Create(area.tile);
730 _station_kdtree.Insert((*st)->index);
731
732 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
733 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
734
736 (*st)->town->have_ratings.Set(_current_company);
737 }
738 }
739 }
740 return CommandCost();
741}
742
750{
751 if (!st->IsInUse()) {
752 st->delete_ctr = 0;
753 InvalidateWindowData(WindowClass::StationList, st->owner, 0);
754 }
755 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
756 UpdateStationSignCoord(st);
757}
758
765{
766 this->UpdateVirtCoord();
768
769 if (adding) {
770 this->RecomputeCatchment();
771 MarkCatchmentTilesDirty();
772 InvalidateWindowData(WindowClass::StationList, this->owner, 0);
773 } else {
774 MarkCatchmentTilesDirty();
775 }
776
777 switch (type) {
779 SetWindowWidgetDirty(WindowClass::StationView, this->index, WID_SV_TRAINS);
780 break;
782 break;
784 case StationType::Bus:
785 SetWindowWidgetDirty(WindowClass::StationView, this->index, WID_SV_ROADVEHS);
786 break;
788 SetWindowWidgetDirty(WindowClass::StationView, this->index, WID_SV_SHIPS);
789 break;
790 default: NOT_REACHED();
791 }
792
793 if (adding) {
794 UpdateStationAcceptance(this, false);
795 InvalidateWindowData(WindowClass::JoinStation, 0, 0);
796 } else {
798 this->RecomputeCatchment();
799 }
800
801}
802
804
814CommandCost CheckBuildableTile(TileIndex tile, DiagDirections invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
815{
816 if (check_bridge && IsBridgeAbove(tile)) {
817 return CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
818 }
819
821 if (ret.Failed()) return ret;
822
823 auto [tileh, z] = GetTileSlopeZ(tile);
824
825 /* Prohibit building if
826 * 1) The tile is "steep" (i.e. stretches two height levels).
827 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
828 */
829 if ((!allow_steep && IsSteepSlope(tileh)) ||
830 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
831 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
832 }
833
835 int flat_z = z + GetSlopeMaxZ(tileh);
836 if (tileh != SLOPE_FLAT) {
837 /* Forbid building if the tile faces a slope in a invalid direction. */
839 if (invalid_dirs.Test(dir) && !CanBuildDepotByTileh(dir, tileh)) {
840 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
841 }
842 }
844 }
845
846 /* The level of this tile must be equal to allowed_z. */
847 if (allowed_z < 0) {
848 /* First tile. */
849 allowed_z = flat_z;
850 } else if (allowed_z != flat_z) {
851 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
852 }
853
854 return cost;
855}
856
864{
866 int allowed_z = -1;
867
868 for (; *tile_iter != INVALID_TILE; ++tile_iter) {
870 if (!IsTileType(*tile_iter, TileType::Clear) || !IsTileFlat(*tile_iter)) {
871 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
872 }
873 } else {
874 CommandCost ret = CheckBuildableTile(*tile_iter, {}, allowed_z, true);
875 if (ret.Failed()) return ret;
876 cost.AddCost(ret.GetCost());
877
878 ret = Command<Commands::LandscapeClear>::Do(flags, *tile_iter);
879 if (ret.Failed()) return ret;
880 cost.AddCost(ret.GetCost());
881 }
882 }
883
884 return cost;
885}
886
893{
895 STR_ERROR_BRIDGE_TOO_LOW_FOR_STATION, // Rail
896 INVALID_STRING_ID, // Airport
897 STR_ERROR_BRIDGE_TOO_LOW_FOR_ROADSTOP, // Truck
898 STR_ERROR_BRIDGE_TOO_LOW_FOR_ROADSTOP, // Bus
899 INVALID_STRING_ID, // Oilrig
900 STR_ERROR_BRIDGE_TOO_LOW_FOR_DOCK, // Dock
901 STR_ERROR_BRIDGE_TOO_LOW_FOR_BUOY, // Buoy
902 STR_ERROR_BRIDGE_TOO_LOW_FOR_RAIL_WAYPOINT, // RailWaypoint
903 STR_ERROR_BRIDGE_TOO_LOW_FOR_ROAD_WAYPOINT, // RoadWaypoint
904 };
905 return too_low_msgs[type];
906};
907
918static CommandCost IsStationBridgeAboveOk(TileIndex tile, std::span<const BridgeableTileInfo> bridgeable_info, StationType type, StationGfx layout, int bridge_height, StringID disallowed_msg = INVALID_STRING_ID)
919{
920 int height = layout < std::size(bridgeable_info) ? bridgeable_info[layout].height : 0;
921
922 if (height == 0) {
923 if (disallowed_msg != INVALID_STRING_ID) return CommandCost{disallowed_msg};
924 /* Get normal error message associated with clearing the tile. */
925 return Command<Commands::LandscapeClear>::Do(DoCommandFlag::Auto, tile);
926 }
927
928 int height_diff = GetTileMaxZ(tile) + height - bridge_height;
929 if (height_diff > 0) return CommandCostWithParam(GetBridgeTooLowMessageForStationType(type), height_diff * TILE_HEIGHT_STEP);
930 return CommandCost{};
931}
932
938static std::span<const BridgeableTileInfo> GetStationBridgeableTileInfo(StationType type)
939{
940 return _station_bridgeable_info[type];
941}
942
952{
953 if (!IsBridgeAbove(tile)) return CommandCost();
954
955 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
956 auto bridgeable_info = spec == nullptr ? GetStationBridgeableTileInfo(type) : spec->bridgeable_info;
957 return IsStationBridgeAboveOk(tile, bridgeable_info, type, layout, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
958}
959
969{
970 if (!IsBridgeAbove(tile)) return CommandCost();
971
972 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
973 auto bridgeable_info = spec == nullptr ? GetStationBridgeableTileInfo(type) : spec->bridgeable_info;
974 return IsStationBridgeAboveOk(tile, bridgeable_info, type, layout, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
975}
976
984{
985 if (!IsBridgeAbove(tile)) return CommandCost();
986
987 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
988 auto bridgeable_info = GetStationBridgeableTileInfo(StationType::Dock);
989 return IsStationBridgeAboveOk(tile, bridgeable_info, StationType::Dock, layout, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
990}
991
998{
999 if (!IsBridgeAbove(tile)) return CommandCost();
1000
1001 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
1002 auto bridgeable_info = GetStationBridgeableTileInfo(StationType::Buoy);
1003 return IsStationBridgeAboveOk(tile, bridgeable_info, StationType::Buoy, 0, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1004}
1005
1022static CommandCost CheckFlatLandRailStation(TileIndex tile_cur, TileIndex north_tile, int &allowed_z, DoCommandFlags 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)
1023{
1025 DiagDirections invalid_dirs = AxisToDiagDirs(axis);
1026
1027 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1028 bool slope_cb = statspec != nullptr && statspec->callback_mask.Test(StationCallbackMask::SlopeCheck);
1029
1030 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false, false);
1031 if (ret.Failed()) return ret;
1032 cost.AddCost(ret.GetCost());
1033
1034 if (slope_cb) {
1035 /* Do slope check if requested. */
1036 ret = PerformStationTileSlopeCheck(north_tile, tile_cur, statspec, axis, plat_len, numtracks);
1037 if (ret.Failed()) return ret;
1038 }
1039
1040 /* if station is set, then we have special handling to allow building on top of already existing stations.
1041 * so station points to StationID::Invalid() if we can build on any station.
1042 * Or it points to a station if we're only allowed to build on exactly that station. */
1043 if (station != nullptr && IsTileType(tile_cur, TileType::Station)) {
1044 if (!IsRailStation(tile_cur)) {
1045 return ClearTile_Station(tile_cur, DoCommandFlag::Auto); // get error message
1046 } else {
1047 StationID st = GetStationIndex(tile_cur);
1048 if (*station == StationID::Invalid()) {
1049 *station = st;
1050 } else if (*station != st) {
1051 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1052 }
1053 }
1054 } else {
1055 /* If we are building a station with a valid railtype, we may be able to overbuild an existing rail tile. */
1056 if (rt != INVALID_RAILTYPE && IsPlainRailTile(tile_cur)) {
1057 /* Don't overbuild signals. */
1058 if (HasSignals(tile_cur)) return CommandCost(STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
1059
1060 /* The current rail type must have power on the to-be-built type (e.g. convert normal rail to electrified rail). */
1061 if (HasPowerOnRail(GetRailType(tile_cur), rt)) {
1062 /* The existing track must align with the desired station axis. */
1063 Track track = AxisToTrack(axis);
1064 if (GetTrackBits(tile_cur) == track) {
1065 /* Check for trains having a reservation for this tile. */
1066 if (GetRailReservationTrackBits(tile_cur).Test(track)) {
1067 Train *v = GetTrainForReservation(tile_cur, track);
1068 if (v != nullptr) {
1069 affected_vehicles.push_back(v);
1070 }
1071 }
1072 ret = Command<Commands::RemoveRail>::Do(flags, tile_cur, track);
1073 if (ret.Failed()) return ret;
1074 cost.AddCost(ret.GetCost());
1075 /* With DoCommandFlags{flags}.Reset(DoCommandFlag::Execute) CmdLandscapeClear would fail since the rail still exists */
1076 return cost;
1077 }
1078 }
1079 }
1080 ret = Command<Commands::LandscapeClear>::Do(flags, tile_cur);
1081 if (ret.Failed()) return ret;
1082 cost.AddCost(ret.GetCost());
1083 }
1084
1085 return cost;
1086}
1087
1102static CommandCost CheckFlatLandRoadStop(TileIndex cur_tile, int &allowed_z, const RoadStopSpec *spec, DoCommandFlags flags, DiagDirections invalid_dirs, bool is_drive_through, StationType station_type, Axis axis, StationID *station, RoadType rt)
1103{
1105
1106 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through, false);
1107 if (ret.Failed()) return ret;
1108 cost.AddCost(ret.GetCost());
1109
1110 ret = IsRoadStationBridgeAboveOk(cur_tile, spec, station_type, is_drive_through ? GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET + to_underlying(axis) : FindFirstBit(invalid_dirs.base()));
1111 if (ret.Failed()) return ret;
1112
1113 /* If station is set, then we have special handling to allow building on top of already existing stations.
1114 * Station points to StationID::Invalid() if we can build on any station.
1115 * Or it points to a station if we're only allowed to build on exactly that station. */
1116 if (station != nullptr && IsTileType(cur_tile, TileType::Station)) {
1117 if (!IsAnyRoadStop(cur_tile)) {
1118 return ClearTile_Station(cur_tile, DoCommandFlag::Auto); // Get error message.
1119 } else {
1120 if (station_type != GetStationType(cur_tile) ||
1121 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
1122 return ClearTile_Station(cur_tile, DoCommandFlag::Auto); // Get error message.
1123 }
1124 /* Drive-through station in the wrong direction. */
1125 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && GetDriveThroughStopAxis(cur_tile) != axis) {
1126 return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1127 }
1128 StationID st = GetStationIndex(cur_tile);
1129 if (*station == StationID::Invalid()) {
1130 *station = st;
1131 } else if (*station != st) {
1132 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1133 }
1134 }
1135 } else {
1136 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
1137 /* Road bits in the wrong direction. */
1138 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : RoadBits{};
1139 if (build_over_road && rb.Any(AxisToRoadBits(OtherAxis(axis)))) {
1140 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1141 switch (rb.Count()) {
1142 case 1:
1143 return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1144
1145 case 2:
1146 if (rb == ROAD_X || rb == ROAD_Y) return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1147 return CommandCost(STR_ERROR_DRIVE_THROUGH_CORNER);
1148
1149 default: // 3 or 4
1150 return CommandCost(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1151 }
1152 }
1153
1154 if (build_over_road) {
1155 /* There is a road, check if we can build road+tram stop over it. */
1156 RoadType road_rt = GetRoadType(cur_tile, RoadTramType::Road);
1157 if (road_rt != INVALID_ROADTYPE) {
1158 Owner road_owner = GetRoadOwner(cur_tile, RoadTramType::Road);
1159 if (road_owner == OWNER_TOWN) {
1160 if (!_settings_game.construction.road_stop_on_town_road) return CommandCost(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1161 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1162 ret = CheckOwnership(road_owner);
1163 if (ret.Failed()) return ret;
1164 }
1165 uint num_pieces = GetRoadBits(cur_tile, RoadTramType::Road).Count();
1166
1167 if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return CommandCost(STR_ERROR_NO_SUITABLE_ROAD);
1168
1169 if (GetDisallowedRoadDirections(cur_tile).Any() && road_owner != OWNER_TOWN && road_owner != OWNER_NONE) {
1170 ret = CheckOwnership(road_owner);
1171 if (ret.Failed()) return ret;
1172 }
1173
1174 cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1175 } else if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt)) {
1176 cost.AddCost(RoadBuildCost(rt) * 2);
1177 }
1178
1179 /* There is a tram, check if we can build road+tram stop over it. */
1180 RoadType tram_rt = GetRoadType(cur_tile, RoadTramType::Tram);
1181 if (tram_rt != INVALID_ROADTYPE) {
1182 Owner tram_owner = GetRoadOwner(cur_tile, RoadTramType::Tram);
1183 if (Company::IsValidID(tram_owner) &&
1184 (!_settings_game.construction.road_stop_on_competitor_road ||
1185 /* Disallow breaking end-of-line of someone else
1186 * so trams can still reverse on this tile. */
1187 GetRoadBits(cur_tile, RoadTramType::Tram).Count() == 1)) {
1188 ret = CheckOwnership(tram_owner);
1189 if (ret.Failed()) return ret;
1190 }
1191 uint num_pieces = GetRoadBits(cur_tile, RoadTramType::Tram).Count();
1192
1193 if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return CommandCost(STR_ERROR_NO_SUITABLE_ROAD);
1194
1195 cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1196 } else if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt)) {
1197 cost.AddCost(RoadBuildCost(rt) * 2);
1198 }
1199 } else if (rt == INVALID_ROADTYPE) {
1200 return CommandCost(STR_ERROR_THERE_IS_NO_ROAD);
1201 } else {
1202 ret = Command<Commands::LandscapeClear>::Do(flags, cur_tile);
1203 if (ret.Failed()) return ret;
1204 cost.AddCost(ret.GetCost());
1205 cost.AddCost(RoadBuildCost(rt) * 2);
1206 }
1207 }
1208
1209 return cost;
1210}
1211
1213template <>
1215{
1216 /* Use predefined layout if it exists. Mask bit zero which will indicate axis. */
1217 if (!stl.layout.empty()) return this->stl.layout[this->position] & ~1;
1218
1219 if (this->stl.length == 1) {
1220 /* Special case for 1-long platforms, all bare platforms except one small building. */
1221 return this->position == ((this->stl.platforms - 1) / 2) ? 2 : 0;
1222 }
1223
1224 if ((this->position < this->stl.length && (this->stl.platforms % 2 == 1))) {
1225 /* Number of tracks is odd, make the first platform bare with a small building. */
1226 return this->position == ((this->stl.length - 1) / 2) ? 2 : 0;
1227 }
1228
1229 if (this->stl.length > 4 && ((this->position % this->stl.length) == 0 || (this->position % this->stl.length) == this->stl.length - 1)) {
1230 /* Station is longer than 4 tiles, place bare platforms at either end. */
1231 return 0;
1232 }
1233
1234 /* None of the above so must be north or south part of larger station. */
1235 return (((this->position / this->stl.length) % 2) == (this->stl.platforms % 2)) ? 4 : 6;
1236}
1237
1251template <class T, class F>
1252CommandCost FindJoiningBaseStation(StringID error_message, StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
1253{
1254 assert(*st == nullptr);
1255 bool check_surrounding = true;
1256
1257 if (existing_station != StationID::Invalid()) {
1258 if (adjacent && existing_station != station_to_join) {
1259 /* You can't build an adjacent station over the top of one that
1260 * already exists. */
1261 return CommandCost(error_message);
1262 } else {
1263 /* Extend the current station, and don't check whether it will
1264 * be near any other stations. */
1265 T *candidate = T::GetIfValid(existing_station);
1266 if (candidate != nullptr && filter(candidate)) *st = candidate;
1267 check_surrounding = (*st == nullptr);
1268 }
1269 } else {
1270 /* There's no station here. Don't check the tiles surrounding this
1271 * one if the company wanted to build an adjacent station. */
1272 if (adjacent) check_surrounding = false;
1273 }
1274
1275 if (check_surrounding) {
1276 /* Make sure there is no more than one other station around us that is owned by us. */
1277 CommandCost ret = GetStationAround(ta, existing_station, _current_company, st, filter);
1278 if (ret.Failed()) return ret;
1279 }
1280
1281 /* Distant join */
1282 if (*st == nullptr && station_to_join != StationID::Invalid()) *st = T::GetIfValid(station_to_join);
1283
1284 return CommandCost();
1285}
1286
1296static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1297{
1298 return FindJoiningBaseStation<Station>(STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST, existing_station, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1299}
1300
1311CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
1312{
1313 if (is_road) {
1314 return FindJoiningBaseStation<Waypoint>(STR_ERROR_MUST_REMOVE_ROADWAYPOINT_FIRST, existing_waypoint, waypoint_to_join, adjacent, ta, wp, [](const Waypoint *wp) -> bool { return HasBit(wp->waypoint_flags, WPF_ROAD); });
1315 } else {
1316 return FindJoiningBaseStation<Waypoint>(STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST, existing_waypoint, waypoint_to_join, adjacent, ta, wp, [](const Waypoint *wp) -> bool { return !HasBit(wp->waypoint_flags, WPF_ROAD); });
1317 }
1318}
1319
1331
1343
1358static CommandCost CalculateRailStationCost(TileArea tile_area, DoCommandFlags 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)
1359{
1361 bool length_price_ready = true;
1362 uint8_t tracknum = 0;
1363 int allowed_z = -1;
1364 for (TileIndex cur_tile : tile_area) {
1365 /* Clear the land below the station. */
1366 CommandCost ret = CheckFlatLandRailStation(cur_tile, tile_area.tile, allowed_z, flags, axis, station, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1367 if (ret.Failed()) return ret;
1368
1369 /* Only add _price[Price::BuildStationRailLength] once for each valid plat_len. */
1370 if (tracknum == numtracks) {
1371 length_price_ready = true;
1372 tracknum = 0;
1373 } else {
1374 tracknum++;
1375 }
1376
1377 /* AddCost for new or rotated rail stations. */
1378 if (!IsRailStationTile(cur_tile) || (IsRailStationTile(cur_tile) && GetRailStationAxis(cur_tile) != axis)) {
1379 cost.AddCost(ret.GetCost());
1381 cost.AddCost(RailBuildCost(rt));
1382
1383 if (length_price_ready) {
1385 length_price_ready = false;
1386 }
1387 }
1388 }
1389
1390 return cost;
1391}
1392
1400{
1401 /* Default stations do not draw pylons under roofs (gfx >= 4) */
1402 if (statspec == nullptr || gfx >= statspec->tileflags.size()) return gfx < 4 ? StationSpec::TileFlag::Pylons : StationSpec::TileFlags{};
1403 return statspec->tileflags[gfx];
1404}
1405
1412{
1413 const auto flags = GetStationTileFlags(GetStationGfx(tile), statspec);
1417}
1418
1433CommandCost CmdBuildRailStation(DoCommandFlags flags, TileIndex tile_org, RailType rt, Axis axis, uint8_t numtracks, uint8_t plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1434{
1435 /* Does the authority allow this? */
1436 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1437 if (ret.Failed()) return ret;
1438
1439 if (!ValParamRailType(rt) || !IsValidAxis(axis)) return CMD_ERROR;
1440
1441 /* Check if the given station class is valid */
1442 if (spec_class.base() >= StationClass::GetClassCount()) return CMD_ERROR;
1443 const StationClass *cls = StationClass::Get(spec_class);
1444 if (IsWaypointClass(*cls)) return CMD_ERROR;
1445 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1446 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1447
1448 int w_org, h_org;
1449 if (axis == Axis::X) {
1450 w_org = plat_len;
1451 h_org = numtracks;
1452 } else {
1453 h_org = plat_len;
1454 w_org = numtracks;
1455 }
1456
1457 /* Check if the first tile and the last tile are valid */
1458 if (!IsValidTile(tile_org) || TileAddWrap(tile_org, w_org - 1, h_org - 1) == INVALID_TILE) return CMD_ERROR;
1459
1460 bool reuse = (station_to_join != NEW_STATION);
1461 if (!reuse) station_to_join = StationID::Invalid();
1462 bool distant_join = (station_to_join != StationID::Invalid());
1463
1464 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1465
1466 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1467
1468 /* these values are those that will be stored in train_tile and station_platforms */
1469 TileArea new_location(tile_org, w_org, h_org);
1470 ret = CheckStationSpread({}, new_location);
1471 if (ret.Failed()) return ret;
1472
1473 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1474 StationID est = StationID::Invalid();
1475 std::vector<Train *> affected_vehicles;
1476 /* Add construction and clearing expenses. */
1477 CommandCost cost = CalculateRailStationCost(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1478 if (cost.Failed()) return cost;
1479
1480 Station *st = nullptr;
1481 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1482 if (ret.Failed()) return ret;
1483
1484 ret = BuildStationPart(&st, flags, reuse, new_location, StationNaming::Rail);
1485 if (ret.Failed()) return ret;
1486
1487 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1488 TileIndexDiff tile_delta = TileOffsByAxis(axis); // offset to go to the next platform tile
1489 TileIndexDiff track_delta = TileOffsByAxis(OtherAxis(axis)); // offset to go to the next track
1490
1491 RailStationTileLayout<StationType::Rail> stl{statspec, numtracks, plat_len};
1492 for (auto [i, it, tile_track] = std::make_tuple(0, stl.begin(), tile_org); i != numtracks; ++i, tile_track += track_delta) {
1493 for (auto [j, tile] = std::make_tuple(0, tile_track); j != plat_len; ++j, tile += tile_delta, ++it) {
1494 /* Don't check the layout if there's no bridge above anyway. */
1495 if (!IsBridgeAbove(tile)) continue;
1496
1497 StationGfx gfx = *it + to_underlying(axis);
1498 if (statspec != nullptr) {
1499 uint32_t platinfo = GetPlatformInfo(gfx, numtracks, plat_len, i, j, false);
1500 /* As the station is not yet completely finished, the station does not yet exist. */
1501 uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, INVALID_TILE);
1502 if (callback != CALLBACK_FAILED && callback <= UINT8_MAX) gfx = (callback & ~1) + to_underlying(axis);
1503 }
1504
1505 ret = IsRailStationBridgeAboveOk(tile, statspec, StationType::Rail, gfx);
1506 if (ret.Failed()) return ret;
1507 }
1508 }
1509
1510 /* Check if we can allocate a custom stationspec to this station */
1511 auto specindex = AllocateSpecToStation(statspec, st);
1512 if (!specindex.has_value()) return CommandCost(STR_ERROR_TOO_MANY_STATION_SPECS);
1513
1514 if (statspec != nullptr) {
1515 /* Perform NewStation checks */
1516
1517 /* Check if the station size is permitted */
1518 if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7))) return CommandCost(STR_ERROR_STATION_DISALLOWED_NUMBER_TRACKS);
1519 if (HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) return CommandCost(STR_ERROR_STATION_DISALLOWED_LENGTH);
1520
1521 /* Check if the station is buildable */
1523 uint16_t cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1525 }
1526 }
1527
1528 if (flags.Test(DoCommandFlag::Execute)) {
1529 st->AddFacility(StationFacility::Train, new_location.tile);
1530
1531 st->train_station.Add(new_location);
1532 st->spread.Add(new_location);
1533
1534 if (specindex.has_value()) AssignSpecToStation(statspec, st, *specindex);
1535 if (statspec != nullptr) {
1536 /* Include this station spec's animation trigger bitmask
1537 * in the station's cached copy. */
1538 st->cached_anim_triggers.Set(statspec->animation.triggers);
1539 }
1540
1541 Track track = AxisToTrack(axis);
1542 Company *c = Company::Get(st->owner);
1543 for (auto [i, it, tile_track] = std::make_tuple(0, stl.begin(), tile_org); i != numtracks; ++i, tile_track += track_delta) {
1544 for (auto [j, tile] = std::make_tuple(0, tile_track); j != plat_len; ++j, tile += tile_delta, ++it) {
1545 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1546 /* Check for trains having a reservation for this tile. */
1548 if (v != nullptr) {
1549 affected_vehicles.push_back(v);
1551 }
1552 }
1553
1554 /* Railtype can change when overbuilding. */
1555 if (IsRailStationTile(tile)) {
1556 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1558 }
1559
1560 /* Remove animation if overbuilding */
1561 DeleteAnimatedTile(tile);
1562 uint8_t old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1563
1564 MakeRailStation(tile, st->owner, st->index, axis, *it, rt);
1565 /* Free the spec if we overbuild something */
1566 DeallocateSpecFromStation(st, old_specindex);
1567 if (statspec == nullptr) DeleteNewGRFInspectWindow(GrfSpecFeature::Stations, tile);
1568
1569 SetCustomStationSpecIndex(tile, *specindex);
1570 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1571 SetAnimationFrame(tile, 0);
1572
1573 if (statspec != nullptr) {
1574 uint32_t platinfo = GetPlatformInfo(*it + to_underlying(axis), numtracks, plat_len, i, j, false);
1575
1576 /* As the station is not yet completely finished, the station does not yet exist. */
1577 uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1578 if (callback != CALLBACK_FAILED) {
1579 if (callback <= UINT8_MAX) {
1580 SetStationGfx(tile, (callback & ~1) + to_underlying(axis));
1581 } else {
1583 }
1584 }
1585
1586 /* Trigger station animation -- after building? */
1587 TriggerStationAnimation(st, tile, StationAnimationTrigger::Built);
1588 }
1589
1590 SetRailStationTileFlags(tile, statspec);
1591
1592 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1594 }
1595 AddTrackToSignalBuffer(tile_track, track, _current_company);
1596 YapfNotifyTrackLayoutChange(tile_track, track);
1597 }
1598
1599 for (uint i = 0; i < affected_vehicles.size(); ++i) {
1600 /* Restore reservations of trains. */
1601 RestoreTrainReservation(affected_vehicles[i]);
1602 }
1603
1604 /* Check whether we need to expand the reservation of trains already on the station. */
1605 TileArea update_reservation_area;
1606 if (axis == Axis::X) {
1607 update_reservation_area = TileArea(tile_org, 1, numtracks);
1608 } else {
1609 update_reservation_area = TileArea(tile_org, numtracks, 1);
1610 }
1611
1612 for (TileIndex tile : update_reservation_area) {
1613 /* Don't even try to make eye candy parts reserved. */
1614 if (IsStationTileBlocked(tile)) continue;
1615
1616 DiagDirection dir = AxisToDiagDir(axis);
1617 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1618 TileIndex platform_begin = tile;
1619 TileIndex platform_end = tile;
1620
1621 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1622 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1623 platform_begin = next_tile;
1624 }
1625 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1626 platform_end = next_tile;
1627 }
1628
1629 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1630 bool reservation = false;
1631 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1632 reservation = HasStationReservation(t);
1633 }
1634
1635 if (reservation) {
1636 SetRailStationPlatformReservation(platform_begin, dir, true);
1637 }
1638 }
1639
1640 st->MarkTilesDirty(false);
1642 }
1643
1644 return cost;
1645}
1646
1647static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1648{
1649restart:
1650
1651 /* too small? */
1652 if (ta.w != 0 && ta.h != 0) {
1653 /* check the left side, x = constant, y changes */
1654 for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1655 /* the left side is unused? */
1656 if (++i == ta.h) {
1657 ta.tile += TileDiffXY(1, 0);
1658 ta.w--;
1659 goto restart;
1660 }
1661 }
1662
1663 /* check the right side, x = constant, y changes */
1664 for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1665 /* the right side is unused? */
1666 if (++i == ta.h) {
1667 ta.w--;
1668 goto restart;
1669 }
1670 }
1671
1672 /* check the upper side, y = constant, x changes */
1673 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1674 /* the left side is unused? */
1675 if (++i == ta.w) {
1676 ta.tile += TileDiffXY(0, 1);
1677 ta.h--;
1678 goto restart;
1679 }
1680 }
1681
1682 /* check the lower side, y = constant, x changes */
1683 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1684 /* the left side is unused? */
1685 if (++i == ta.w) {
1686 ta.h--;
1687 goto restart;
1688 }
1689 }
1690 } else {
1691 ta.Clear();
1692 }
1693
1694 return ta;
1695}
1696
1702{
1703 static constexpr auto func = [](BaseStation *st, TileIndex tile) { return IsTileType(tile, TileType::Station) && GetStationIndex(tile) == st->index; };
1704 st->spread = MakeStationAreaSmaller(st, st->spread, func);
1705}
1706
1707static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1708{
1709 return st->TileBelongsToRailStation(tile);
1710}
1711
1712static void MakeRailStationAreaSmaller(BaseStation *st)
1713{
1714 st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1715}
1716
1717static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1718{
1719 return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1720}
1721
1722static void MakeShipStationAreaSmaller(Station *st)
1723{
1724 st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1725 UpdateStationDockingTiles(st);
1726}
1727
1728static bool TileBelongsToRoadWaypointStation(BaseStation *st, TileIndex tile)
1729{
1730 return IsRoadWaypointTile(tile) && GetStationIndex(tile) == st->index;
1731}
1732
1733void MakeRoadWaypointStationAreaSmaller(BaseStation *st, TileArea &road_waypoint_area)
1734{
1735 road_waypoint_area = MakeStationAreaSmaller(st, road_waypoint_area, TileBelongsToRoadWaypointStation);
1736}
1737
1748template <class T>
1749CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlags flags, Money removal_cost, bool keep_rail)
1750{
1751 /* Count of the number of tiles removed */
1752 int quantity = 0;
1754 /* Accumulator for the errors seen during clearing. If no errors happen,
1755 * and the quantity is 0 there is no station. Otherwise it will be one
1756 * of the other error that got accumulated. */
1757 CommandCost error;
1758
1759 /* Do the action for every tile into the area */
1760 for (TileIndex tile : ta) {
1761 /* Make sure the specified tile is a rail station */
1762 if (!HasStationTileRail(tile)) continue;
1763
1764 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1766 error.AddCost(std::move(ret));
1767 if (error.Failed()) continue;
1768
1769 /* Check ownership of station */
1770 T *st = T::GetByTile(tile);
1771 if (st == nullptr) continue;
1772
1774 ret = CheckOwnership(st->owner);
1775 error.AddCost(std::move(ret));
1776 if (error.Failed()) continue;
1777 }
1778
1779 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1780 quantity++;
1781
1782 if (keep_rail || IsStationTileBlocked(tile)) {
1783 /* Don't refund the 'steel' of the track when we keep the
1784 * rail, or when the tile didn't have any rail at all. */
1785 total_cost.AddCost(-_price[Price::ClearRail]);
1786 }
1787
1788 if (flags.Test(DoCommandFlag::Execute)) {
1789 /* read variables before the station tile is removed */
1790 uint specindex = GetCustomStationSpecIndex(tile);
1791 Track track = GetRailStationTrack(tile);
1792 Owner owner = GetTileOwner(tile);
1793 RailType rt = GetRailType(tile);
1794 Train *v = nullptr;
1795
1796 if (HasStationReservation(tile)) {
1797 v = GetTrainForReservation(tile, track);
1798 if (v != nullptr) FreeTrainReservation(v);
1799 }
1800
1801 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1802 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1803
1804 DoClearSquare(tile);
1806 if (build_rail) MakeRailNormal(tile, owner, track, rt);
1807 Company::Get(owner)->infrastructure.station--;
1809
1810 st->tile_waiting_random_triggers.erase(tile);
1811 AddTrackToSignalBuffer(tile, track, owner);
1812 YapfNotifyTrackLayoutChange(tile, track);
1813
1814 DeallocateSpecFromStation(st, specindex);
1815
1816 include(affected_stations, st);
1817
1818 if (v != nullptr) RestoreTrainReservation(v);
1819 }
1820 }
1821
1822 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1823
1824 for (T *st : affected_stations) {
1825
1826 /* now we need to make the "spanned" area of the railway station smaller
1827 * if we deleted something at the edges.
1828 * we also need to adjust train_tile. */
1829 MakeRailStationAreaSmaller(st);
1831 UpdateStationSignCoord(st);
1832
1833 /* if we deleted the whole station, delete the train facility. */
1834 if (st->train_station.IsEmpty()) {
1836 SetWindowClassesDirty(WindowClass::VehicleOrders);
1837 SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_TRAINS);
1838 MarkCatchmentTilesDirty();
1839 st->UpdateVirtCoord();
1841 }
1842 }
1843
1844 total_cost.AddCost(quantity * removal_cost);
1845 return total_cost;
1846}
1847
1858{
1859 if (end == 0) end = start;
1860 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1861
1862 TileArea ta(start, end);
1863 std::vector<Station *> affected_stations;
1864
1865 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[Price::ClearStationRail], keep_rail);
1866 if (ret.Failed()) return ret;
1867
1868 /* Do all station specific functions here. */
1869 for (Station *st : affected_stations) {
1870
1871 if (st->train_station.IsEmpty()) SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_TRAINS);
1872 st->MarkTilesDirty(false);
1873 MarkCatchmentTilesDirty();
1874 st->RecomputeCatchment();
1875 }
1876
1877 /* Now apply the rail cost to the number that we deleted */
1878 return ret;
1879}
1880
1891{
1892 if (end == 0) end = start;
1893 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1894
1895 TileArea ta(start, end);
1896 std::vector<Waypoint *> affected_stations;
1897
1898 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[Price::ClearWaypointRail], keep_rail);
1899}
1900
1901
1910template <class T>
1911CommandCost RemoveRailStation(T *st, DoCommandFlags flags, Money removal_cost)
1912{
1913 /* Current company owns the station? */
1915 CommandCost ret = CheckOwnership(st->owner);
1916 if (ret.Failed()) return ret;
1917 }
1918
1919 /* determine width and height of platforms */
1920 TileArea ta = st->train_station;
1921
1922 assert(ta.w != 0 && ta.h != 0);
1923
1925 /* clear all areas of the station */
1926 for (TileIndex tile : ta) {
1927 /* only remove tiles that are actually train station tiles */
1928 if (st->TileBelongsToRailStation(tile)) {
1929 std::vector<T*> affected_stations; // dummy
1930 CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1931 if (ret.Failed()) return ret;
1932 cost.AddCost(ret.GetCost());
1933 }
1934 }
1935
1936 return cost;
1937}
1938
1946{
1947 /* if there is flooding, remove platforms tile by tile */
1949 return Command<Commands::RemoveFromRailStation>::Do(DoCommandFlag::Execute, tile, TileIndex{}, false);
1950 }
1951
1952 Station *st = Station::GetByTile(tile);
1954
1956
1957 return cost;
1958}
1959
1967{
1968 /* if there is flooding, remove waypoints tile by tile */
1970 return Command<Commands::RemoveFromRailWaypoint>::Do(DoCommandFlag::Execute, tile, TileIndex{}, false);
1971 }
1972
1974}
1975
1976
1982static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1983{
1984 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1985
1986 if (*primary_stop == nullptr) {
1987 /* we have no roadstop of the type yet, so write a "primary stop" */
1988 return primary_stop;
1989 } else {
1990 /* there are stops already, so append to the end of the list */
1991 RoadStop *stop = *primary_stop;
1992 while (stop->next != nullptr) stop = stop->next;
1993 return &stop->next;
1994 }
1995}
1996
1997static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index = -1);
1998CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index = -1);
1999
2009static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
2010{
2011 return FindJoiningBaseStation<Station>(STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST, existing_stop, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
2012}
2013
2028CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlags flags, bool is_drive_through, StationType station_type, const RoadStopSpec *roadstopspec, Axis axis, DiagDirection ddir, StationID *station, RoadType rt, Money unit_cost)
2029{
2030 DiagDirections invalid_dirs = is_drive_through ? AxisToDiagDirs(axis) : ddir;
2031
2032 /* Check every tile in the area. */
2033 int allowed_z = -1;
2035 for (TileIndex cur_tile : tile_area) {
2036 CommandCost ret = CheckFlatLandRoadStop(cur_tile, allowed_z, roadstopspec, flags, invalid_dirs, is_drive_through, station_type, axis, station, rt);
2037 if (ret.Failed()) return ret;
2038
2039 bool is_preexisting_roadstop = IsTileType(cur_tile, TileType::Station) && IsAnyRoadStop(cur_tile);
2040
2041 /* Only add costs if a stop doesn't already exist in the location */
2042 if (!is_preexisting_roadstop) {
2043 cost.AddCost(ret.GetCost());
2044 cost.AddCost(unit_cost);
2045 }
2046 }
2047
2048 return cost;
2049}
2050
2067CommandCost CmdBuildRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through,
2068 DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
2069{
2070 if (!ValParamRoadType(rt) || !IsValidDiagDirection(ddir) || stop_type >= RoadStopType::End) return CMD_ERROR;
2071 bool reuse = (station_to_join != NEW_STATION);
2072 if (!reuse) station_to_join = StationID::Invalid();
2073 bool distant_join = (station_to_join != StationID::Invalid());
2074
2075 /* Check if the given station class is valid */
2076 if (spec_class.base() >= RoadStopClass::GetClassCount()) return CMD_ERROR;
2077 const RoadStopClass *cls = RoadStopClass::Get(spec_class);
2078 if (IsWaypointClass(*cls)) return CMD_ERROR;
2079 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
2080
2081 const RoadStopSpec *roadstopspec = cls->GetSpec(spec_index);
2082 if (roadstopspec != nullptr) {
2083 if (stop_type == RoadStopType::Truck && roadstopspec->stop_type != ROADSTOPTYPE_FREIGHT && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
2084 if (stop_type == RoadStopType::Bus && roadstopspec->stop_type != ROADSTOPTYPE_PASSENGER && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
2085 if (!is_drive_through && roadstopspec->flags.Test(RoadStopSpecFlag::DriveThroughOnly)) return CMD_ERROR;
2086 }
2087
2088 /* Check if the requested road stop is too big */
2089 if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
2090 /* Check for incorrect width / length. */
2091 if (width == 0 || length == 0) return CMD_ERROR;
2092 /* Check if the first tile and the last tile are valid */
2093 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
2094
2095 TileArea roadstop_area(tile, width, length);
2096 if (CommandCost ret = CheckStationSpread({}, roadstop_area); ret.Failed()) return ret;
2097
2098 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2099
2100 /* Trams only have drive through stops */
2101 if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
2102
2103 Axis axis = DiagDirToAxis(ddir);
2104
2106 if (ret.Failed()) return ret;
2107
2108 bool is_truck_stop = stop_type != RoadStopType::Bus;
2109
2110 /* Total road stop cost. */
2111 Money unit_cost;
2112 if (roadstopspec != nullptr) {
2113 unit_cost = roadstopspec->GetBuildCost(is_truck_stop ? Price::BuildStationTruck : Price::BuildStationBus);
2114 } else {
2115 unit_cost = _price[is_truck_stop ? Price::BuildStationTruck : Price::BuildStationBus];
2116 }
2117 StationID est = StationID::Invalid();
2118 CommandCost cost = CalculateRoadStopCost(roadstop_area, flags, is_drive_through, is_truck_stop ? StationType::Truck : StationType::Bus, roadstopspec, axis, ddir, &est, rt, unit_cost);
2119 if (cost.Failed()) return cost;
2120
2121 Station *st = nullptr;
2122 ret = FindJoiningRoadStop(est, station_to_join, adjacent, roadstop_area, &st);
2123 if (ret.Failed()) return ret;
2124
2125 /* Check if this number of road stops can be allocated. */
2126 if (!RoadStop::CanAllocateItem(static_cast<size_t>(roadstop_area.w) * roadstop_area.h)) return CommandCost(is_truck_stop ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
2127
2128 ret = BuildStationPart(&st, flags, reuse, roadstop_area, StationNaming::Road);
2129 if (ret.Failed()) return ret;
2130
2131 /* Check if we can allocate a custom stationspec to this station */
2132 auto specindex = AllocateSpecToRoadStop(roadstopspec, st);
2133 if (!specindex.has_value()) return CommandCost(STR_ERROR_TOO_MANY_STATION_SPECS);
2134
2135 if (roadstopspec != nullptr) {
2136 /* Perform NewGRF checks */
2137
2138 /* Check if the road stop is buildable */
2139 if (roadstopspec->callback_mask.Test(RoadStopCallbackMask::Avail)) {
2140 uint16_t cb_res = GetRoadStopCallback(CBID_STATION_AVAILABILITY, 0, 0, roadstopspec, nullptr, INVALID_TILE, rt, is_truck_stop ? StationType::Truck : StationType::Bus, 0);
2141 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(roadstopspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
2142 }
2143 }
2144
2145 if (flags.Test(DoCommandFlag::Execute)) {
2146 if (specindex.has_value()) AssignSpecToRoadStop(roadstopspec, st, *specindex);
2147 /* Check every tile in the area. */
2148 for (TileIndex cur_tile : roadstop_area) {
2149 /* Get existing road types and owners before any tile clearing */
2150 RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RoadTramType::Road) : INVALID_ROADTYPE;
2151 RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RoadTramType::Tram) : INVALID_ROADTYPE;
2152 Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RoadTramType::Road) : _current_company;
2153 Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RoadTramType::Tram) : _current_company;
2154
2155 if (IsTileType(cur_tile, TileType::Station) && IsStationRoadStop(cur_tile)) {
2156 RemoveRoadStop(cur_tile, flags, *specindex);
2157 }
2158
2159 if (roadstopspec != nullptr) {
2160 /* Include this road stop spec's animation trigger bitmask
2161 * in the station's cached copy. */
2162 st->cached_roadstop_anim_triggers.Set(roadstopspec->animation.triggers);
2163 }
2164
2165 RoadStop *road_stop = RoadStop::Create(cur_tile);
2166 /* Insert into linked list of RoadStops. */
2167 RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
2168 *currstop = road_stop;
2169
2170 if (is_truck_stop) {
2171 st->truck_station.Add(cur_tile);
2172 } else {
2173 st->bus_station.Add(cur_tile);
2174 }
2175
2176 /* Initialize an empty station. */
2177 st->AddFacility(is_truck_stop ? StationFacility::TruckStop : StationFacility::BusStop, cur_tile);
2178
2179 st->spread.Add(cur_tile);
2180
2181 RoadStopType rs_type = is_truck_stop ? RoadStopType::Truck : RoadStopType::Bus;
2182 if (is_drive_through) {
2183 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2184 * bits first. */
2185 if (IsNormalRoadTile(cur_tile)) {
2186 UpdateCompanyRoadInfrastructure(road_rt, road_owner, -static_cast<int>(GetRoadBits(cur_tile, RoadTramType::Road).Count()));
2187 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -static_cast<int>(GetRoadBits(cur_tile, RoadTramType::Tram).Count()));
2188 }
2189
2190 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2191 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2192
2193 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, (rs_type == RoadStopType::Bus ? StationType::Bus : StationType::Truck), road_rt, tram_rt, axis);
2194 road_stop->MakeDriveThrough();
2195 } else {
2196 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2197 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2198 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
2199 }
2202 Company::Get(st->owner)->infrastructure.station++;
2203
2204 SetCustomRoadStopSpecIndex(cur_tile, *specindex);
2205 if (roadstopspec != nullptr) {
2206 st->SetRoadStopRandomBits(cur_tile, GB(Random(), 0, 8));
2207 TriggerRoadStopAnimation(st, cur_tile, StationAnimationTrigger::Built);
2208 }
2209
2210 MarkTileDirtyByTile(cur_tile);
2211 }
2212
2213 if (st != nullptr) {
2215 }
2216 }
2217 return cost;
2218}
2219
2227static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index)
2228{
2229 Station *st = Station::GetByTile(tile);
2230
2232 CommandCost ret = CheckOwnership(st->owner);
2233 if (ret.Failed()) return ret;
2234 }
2235
2236 bool is_truck = IsTruckStop(tile);
2237
2238 RoadStop **primary_stop;
2239 RoadStop *cur_stop;
2240 if (is_truck) { // truck stop
2241 primary_stop = &st->truck_stops;
2242 cur_stop = RoadStop::GetByTile(tile, RoadStopType::Truck);
2243 } else {
2244 primary_stop = &st->bus_stops;
2245 cur_stop = RoadStop::GetByTile(tile, RoadStopType::Bus);
2246 }
2247
2248 assert(cur_stop != nullptr);
2249
2250 /* don't do the check for drive-through road stops when company bankrupts */
2252 /* remove the 'going through road stop' status from all vehicles on that tile */
2253 if (flags.Test(DoCommandFlag::Execute)) {
2254 for (Vehicle *v : VehiclesOnTile(tile)) {
2255 if (v->type != VehicleType::Road) continue;
2256 /* Okay... we are a road vehicle on a drive through road stop.
2257 * But that road stop has just been removed, so we need to make
2258 * sure we are in a valid state... however, vehicles can also
2259 * turn on road stop tiles, so only clear the 'road stop' state
2260 * bits and only when the state was 'in road stop', otherwise
2261 * we'll end up clearing the turn around bits. */
2264 }
2265 }
2266 } else {
2268 if (ret.Failed()) return ret;
2269 }
2270
2271 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2272
2273 if (flags.Test(DoCommandFlag::Execute)) {
2274 if (*primary_stop == cur_stop) {
2275 /* removed the first stop in the list */
2276 *primary_stop = cur_stop->next;
2277 /* removed the only stop? */
2278 if (*primary_stop == nullptr) {
2280 SetWindowClassesDirty(WindowClass::VehicleOrders);
2281 }
2282 } else {
2283 /* tell the predecessor in the list to skip this stop */
2284 RoadStop *pred = *primary_stop;
2285 while (pred->next != cur_stop) pred = pred->next;
2286 pred->next = cur_stop->next;
2287 }
2288
2289 /* Update company infrastructure counts. */
2290 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
2291 RoadType rt = GetRoadType(tile, rtt);
2293 }
2294
2295 Company::Get(st->owner)->infrastructure.station--;
2297
2298 uint specindex = GetCustomRoadStopSpecIndex(tile);
2299
2301
2302 if (IsDriveThroughStopTile(tile)) {
2303 /* Clears the tile for us */
2304 cur_stop->ClearDriveThrough();
2305 DeleteAnimatedTile(tile);
2306 } else {
2307 DoClearSquare(tile);
2308 }
2309
2310 delete cur_stop;
2311
2312 /* Make sure no vehicle is going to the old roadstop. Narrow the search to any road vehicles with an order to
2313 * this station, then look for any currently heading to the tile. */
2314 StationID station_id = st->index;
2316 [](const Vehicle *v) { return v->type == VehicleType::Road; },
2317 [station_id](const Order *order) { return order->IsType(OT_GOTO_STATION) && order->GetDestination() == station_id; },
2318 [station_id, tile](Vehicle *v) {
2319 if (v->current_order.IsType(OT_GOTO_STATION) && v->dest_tile == tile) {
2320 v->SetDestTile(v->GetOrderStationLocation(station_id));
2321 }
2322 }
2323 );
2324
2326
2327 if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? StationType::Truck: StationType::Bus);
2328
2329 st->tile_waiting_random_triggers.erase(tile);
2330 st->RemoveRoadStopTileData(tile);
2331 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex);
2332
2333 /* Update the tile area of the truck/bus stop */
2334 if (is_truck) {
2335 st->truck_station.Clear();
2336 for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2337 } else {
2338 st->bus_station.Clear();
2339 for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2340 }
2341 }
2342
2344 return CommandCost(ExpensesType::Construction, spec != nullptr ? spec->GetClearCost(category) : _price[category]);
2345}
2346
2354CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index)
2355{
2356 Waypoint *wp = Waypoint::GetByTile(tile);
2357
2359 CommandCost ret = CheckOwnership(wp->owner);
2360 if (ret.Failed()) return ret;
2361 }
2362
2363 /* Ignore vehicles when the company goes bankrupt. The road will remain, any vehicles going to the waypoint will be removed. */
2364 if (!flags.Test(DoCommandFlag::Bankrupt)) {
2366 if (ret.Failed()) return ret;
2367 }
2368
2369 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2370
2371 if (flags.Test(DoCommandFlag::Execute)) {
2372 /* Update company infrastructure counts. */
2373 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
2374 RoadType rt = GetRoadType(tile, rtt);
2376 }
2377
2378 Company::Get(wp->owner)->infrastructure.station--;
2380
2381 uint specindex = GetCustomRoadStopSpecIndex(tile);
2382
2384
2385 DoClearSquare(tile);
2386
2388
2389 wp->tile_waiting_random_triggers.erase(tile);
2390 wp->RemoveRoadStopTileData(tile);
2391 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(wp, specindex);
2392
2393 if (replacement_spec_index < 0) {
2394 MakeRoadWaypointStationAreaSmaller(wp, wp->road_waypoint_area);
2395
2396 UpdateStationSignCoord(wp);
2397
2398 /* if we deleted the whole waypoint, delete the road facility. */
2399 if (wp->road_waypoint_area.IsEmpty()) {
2401 SetWindowWidgetDirty(WindowClass::StationView, wp->index, WID_SV_ROADVEHS);
2402 wp->UpdateVirtCoord();
2404 }
2405 }
2406 }
2407
2409}
2410
2419static CommandCost RemoveGenericRoadStop(DoCommandFlags flags, const TileArea &roadstop_area, bool road_waypoint, bool remove_road)
2420{
2422 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2423 bool had_success = false;
2424
2425 for (TileIndex cur_tile : roadstop_area) {
2426 /* Make sure the specified tile is a road stop of the correct type */
2427 if (!IsTileType(cur_tile, TileType::Station) || !IsAnyRoadStop(cur_tile) || IsRoadWaypoint(cur_tile) != road_waypoint) continue;
2428
2429 /* Save information on to-be-restored roads before the stop is removed. */
2430 RoadBits road_bits{};
2433 if (IsDriveThroughStopTile(cur_tile)) {
2434 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
2435 road_type[rtt] = GetRoadType(cur_tile, rtt);
2436 if (road_type[rtt] == INVALID_ROADTYPE) continue;
2437 road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2438 /* If we don't want to preserve our roads then restore only roads of others. */
2439 if (remove_road && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2440 }
2441 road_bits = AxisToRoadBits(GetDriveThroughStopAxis(cur_tile));
2442 }
2443
2444 CommandCost ret;
2445 if (road_waypoint) {
2446 ret = RemoveRoadWaypointStop(cur_tile, flags);
2447 } else {
2448 ret = RemoveRoadStop(cur_tile, flags);
2449 }
2450 if (ret.Failed()) {
2451 last_error = std::move(ret);
2452 continue;
2453 }
2454 cost.AddCost(ret.GetCost());
2455 had_success = true;
2456
2457 /* Restore roads. */
2459 MakeRoadNormal(cur_tile, road_bits, road_type[RoadTramType::Road], road_type[RoadTramType::Tram], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2460 road_owner[RoadTramType::Road], road_owner[RoadTramType::Tram]);
2461
2462 /* Update company infrastructure counts. */
2463 int count = road_bits.Count();
2466 }
2467 }
2468
2469 return had_success ? cost : last_error;
2470}
2471
2482CommandCost CmdRemoveRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
2483{
2484 if (stop_type >= RoadStopType::End) return CMD_ERROR;
2485 /* Check for incorrect width / height. */
2486 if (width == 0 || height == 0) return CMD_ERROR;
2487 /* Check if the first tile and the last tile are valid */
2488 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2489 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2490 if (remove_road && flags.Test(DoCommandFlag::Bankrupt)) return CMD_ERROR;
2491
2492 TileArea roadstop_area(tile, width, height);
2493
2494 return RemoveGenericRoadStop(flags, roadstop_area, false, remove_road);
2495}
2496
2505{
2506 if (end == 0) end = start;
2507 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
2508
2509 TileArea roadstop_area(start, end);
2510
2511 return RemoveGenericRoadStop(flags, roadstop_area, true, false);
2512}
2513
2522uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2523{
2524 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2525 * So no need to go any further*/
2526 if (as->noise_level < 2) return as->noise_level;
2527
2528 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2529 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2530 * Basically, it says that the less tolerant a town is, the bigger the distance before
2531 * an actual decrease can be granted */
2532 uint8_t town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2533
2534 /* now, we want to have the distance segmented using the distance judged bareable by town
2535 * This will give us the coefficient of reduction the distance provides. */
2536 uint noise_reduction = distance / town_tolerance_distance;
2537
2538 /* If the noise reduction equals the airport noise itself, don't give it for free.
2539 * Otherwise, simply reduce the airport's level. */
2540 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2541}
2542
2554{
2555 assert(Town::GetNumItems() > 0);
2556
2557 Town *nearest = nullptr;
2558
2559 auto width = as->size_x;
2560 auto height = as->size_y;
2561 if (rotation == Direction::E || rotation == Direction::W) std::swap(width, height);
2562
2563 uint perimeter_min_x = TileX(tile);
2564 uint perimeter_min_y = TileY(tile);
2565 uint perimeter_max_x = perimeter_min_x + width - 1;
2566 uint perimeter_max_y = perimeter_min_y + height - 1;
2567
2568 mindist = UINT_MAX - 1; // prevent overflow
2569
2570 for (; *iter != INVALID_TILE; ++iter) {
2571 TileIndex cur_tile = *iter;
2572 assert(IsInsideBS(TileX(cur_tile), perimeter_min_x, width));
2573 assert(IsInsideBS(TileY(cur_tile), perimeter_min_y, height));
2574 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) {
2575 Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2576 if (t == nullptr) continue;
2577
2578 uint dist = DistanceManhattan(t->xy, cur_tile);
2579 if (dist == mindist && t->index < nearest->index) nearest = t;
2580 if (dist < mindist) {
2581 nearest = t;
2582 mindist = dist;
2583 }
2584 }
2585 }
2586
2587 return nearest;
2588}
2589
2597static Town *AirportGetNearestTown(const Station *st, uint &mindist)
2598{
2600}
2601
2602
2605{
2606 for (Town *t : Town::Iterate()) t->noise_reached = 0;
2607
2608 for (const Station *st : Station::Iterate()) {
2609 if (!st->airport.IsEmpty() && st->airport.type != AT_OILRIG) {
2610 uint dist;
2611 Town *nearest = AirportGetNearestTown(st, dist);
2612 nearest->noise_reached += GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2613 }
2614 }
2615}
2616
2627CommandCost CmdBuildAirport(DoCommandFlags flags, TileIndex tile, uint8_t airport_type, uint8_t layout, StationID station_to_join, bool allow_adjacent)
2628{
2629 bool reuse = (station_to_join != NEW_STATION);
2630 if (!reuse) station_to_join = StationID::Invalid();
2631 bool distant_join = (station_to_join != StationID::Invalid());
2632
2633 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2634
2635 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2636
2638 if (ret.Failed()) return ret;
2639
2640 /* Check if a valid, buildable airport was chosen for construction */
2641 const AirportSpec *as = AirportSpec::Get(airport_type);
2642 if (!as->IsAvailable() || layout >= as->layouts.size()) return CMD_ERROR;
2643 if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2644
2645 Direction rotation = as->layouts[layout].rotation;
2646 int w = as->size_x;
2647 int h = as->size_y;
2648 if (rotation == Direction::E || rotation == Direction::W) std::swap(w, h);
2649 TileArea airport_area = TileArea(tile, w, h);
2650
2651 ret = CheckStationSpread({}, airport_area);
2652 if (ret.Failed()) return ret;
2653
2654 CommandCost cost = CheckFlatLandAirport(AirportTileTableIterator{as->layouts[layout].tiles, tile, true}, flags);
2655 if (cost.Failed()) return cost;
2656
2657 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2658 uint dist;
2659 Town *nearest = AirportGetNearestTown(as, rotation, tile, AirportTileTableIterator{as->layouts[layout].tiles, tile, false}, dist);
2660 uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2661
2662 /* Check if local auth would allow a new airport */
2663 StringID authority_refuse_message = STR_NULL;
2664 Town *authority_refuse_town = nullptr;
2665
2666 if (_settings_game.economy.station_noise_level) {
2667 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2668 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2669 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2670 authority_refuse_town = nearest;
2671 }
2672 } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
2673 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2674 uint num = 0;
2675 for (const Station *st : Station::Iterate()) {
2676 if (st->town == t && st->facilities.Test(StationFacility::Airport) && st->airport.type != AT_OILRIG) num++;
2677 }
2678 if (num >= 2) {
2679 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2680 authority_refuse_town = t;
2681 }
2682 }
2683
2684 if (authority_refuse_message != STR_NULL) {
2685 return CommandCostWithParam(authority_refuse_message, authority_refuse_town->index);
2686 }
2687
2688 Station *st = nullptr;
2689 ret = FindJoiningStation(StationID::Invalid(), station_to_join, allow_adjacent, airport_area, &st);
2690 if (ret.Failed()) return ret;
2691
2692 /* Distant join */
2693 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2694
2695 ret = BuildStationPart(&st, flags, reuse, airport_area, GetAirport(airport_type)->flags.Test(AirportFTAClass::Flag::Airplanes) ? StationNaming::Airport : StationNaming::Heliport);
2696 if (ret.Failed()) return ret;
2697
2698 if (st != nullptr && !st->airport.IsEmpty()) {
2699 return CommandCost(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2700 }
2701
2702 for (AirportTileTableIterator iter{as->layouts[layout].tiles, tile, false}; *iter != INVALID_TILE; ++iter) {
2704 }
2705
2706 if (flags.Test(DoCommandFlag::Execute)) {
2707 /* Always add the noise, so there will be no need to recalculate when option toggles */
2708 nearest->noise_reached += newnoise_level;
2709
2711 st->airport.type = airport_type;
2712 st->airport.layout = layout;
2713 st->airport.blocks = {};
2714 st->airport.rotation = rotation;
2715
2716 st->spread.Add(airport_area);
2717
2718 for (AirportTileTableIterator iter{as->layouts[layout].tiles, tile, false}; *iter != INVALID_TILE; ++iter) {
2719 StationGfx gfx = static_cast<StationGfx>(iter.GetAirportGfx());
2720
2721 MakeAirport(*iter, st->owner, st->index, gfx, WaterClass::Invalid);
2722 SetStationTileRandomBits(*iter, GB(Random(), 0, 4));
2723 st->airport.Add(*iter);
2724
2726 }
2727
2728 /* Only call the animation trigger after all tiles have been built */
2729 for (AirportTileTableIterator iter{as->layouts[layout].tiles, tile, false}; *iter != INVALID_TILE; ++iter) {
2730 TriggerAirportTileAnimation(st, *iter, AirportAnimationTrigger::Built);
2731 }
2732
2734
2735 Company::Get(st->owner)->infrastructure.airport++;
2736
2738 InvalidateWindowData(WindowClass::StationView, st->index, -1);
2739
2740 if (_settings_game.economy.station_noise_level) {
2741 SetWindowDirty(WindowClass::TownView, nearest->index);
2742 }
2743 }
2744
2745 return cost;
2746}
2747
2755{
2756 Station *st = Station::GetByTile(tile);
2757
2759 CommandCost ret = CheckOwnership(st->owner);
2760 if (ret.Failed()) return ret;
2761 }
2762
2763 tile = st->airport.tile;
2764
2766
2767 for (const Aircraft *a : Aircraft::Iterate()) {
2768 if (!a->IsNormalAircraft()) continue;
2769 if (a->targetairport == st->index && a->state != FLYING) {
2770 return CommandCost(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2771 }
2772 }
2773
2774 if (flags.Test(DoCommandFlag::Execute)) {
2775 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2776 TileIndex tile_cur = st->airport.GetHangarTile(i);
2777 OrderBackup::Reset(tile_cur, false);
2778 CloseWindowById(WindowClass::VehicleDepot, tile_cur);
2779 }
2780
2781 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2782 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2783 * need of recalculation */
2784 uint dist;
2785 Town *nearest = AirportGetNearestTown(st, dist);
2787
2788 if (_settings_game.economy.station_noise_level) {
2789 SetWindowDirty(WindowClass::TownView, nearest->index);
2790 }
2791 }
2792
2793 for (TileIndex tile_cur : st->airport) {
2794 if (!st->TileBelongsToAirport(tile_cur)) continue;
2795
2796 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2797 if (ret.Failed()) return ret;
2798
2800
2801 if (flags.Test(DoCommandFlag::Execute)) {
2802 DoClearSquare(tile_cur);
2804 }
2805 }
2806
2807 if (flags.Test(DoCommandFlag::Execute)) {
2808 /* Clear the persistent storage. */
2809 delete st->airport.psa;
2810
2812
2813 st->airport.Clear();
2815 SetWindowClassesDirty(WindowClass::VehicleOrders);
2816
2817 InvalidateWindowData(WindowClass::StationView, st->index, -1);
2818
2819 Company::Get(st->owner)->infrastructure.airport--;
2820
2822
2824 }
2825
2826 return cost;
2827}
2828
2836{
2837 if (!Station::IsValidID(station_id)) return CMD_ERROR;
2838 Station *st = Station::Get(station_id);
2839
2841
2842 CommandCost ret = CheckOwnership(st->owner);
2843 if (ret.Failed()) return ret;
2844
2845 if (flags.Test(DoCommandFlag::Execute)) {
2847 SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_CLOSE_AIRPORT);
2848 }
2849 return CommandCost();
2850}
2851
2859bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2860{
2861 for (const OrderList *orderlist : OrderList::Iterate()) {
2862 const Vehicle *v = orderlist->GetFirstSharedVehicle();
2863 assert(v != nullptr);
2864 if ((v->owner == company) != include_company) continue;
2865
2866 for (const Order &order : orderlist->GetOrders()) {
2867 if (order.GetDestination() == station && (order.IsType(OT_GOTO_STATION) || order.IsType(OT_GOTO_WAYPOINT))) {
2868 return true;
2869 }
2870 }
2871 }
2872 return false;
2873}
2874
2877 {-1, 0},
2878 { 0, 0},
2879 { 0, 0},
2880 { 0, -1}
2881}}};
2882
2886
2895CommandCost CmdBuildDock(DoCommandFlags flags, TileIndex tile, StationID station_to_join, bool adjacent)
2896{
2897 bool reuse = (station_to_join != NEW_STATION);
2898 if (!reuse) station_to_join = StationID::Invalid();
2899 bool distant_join = (station_to_join != StationID::Invalid());
2900
2901 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2902
2904 if (direction == DiagDirection::Invalid) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2905 direction = ReverseDiagDir(direction);
2906
2907 /* Docks cannot be placed on rapids */
2908 if (HasTileWaterGround(tile)) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2909
2911 if (ret.Failed()) return ret;
2912
2913 ret = IsDockBridgeAboveOk(tile, to_underlying(direction));
2914 if (ret.Failed()) return ret;
2915
2917 ret = Command<Commands::LandscapeClear>::Do(flags, tile);
2918 if (ret.Failed()) return ret;
2919 cost.AddCost(ret.GetCost());
2920
2921 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2922
2923 if (!HasTileWaterGround(tile_cur) || !IsTileFlat(tile_cur)) {
2924 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2925 }
2926
2928 if (ret.Failed()) return ret;
2929
2930 /* Get the water class of the water tile before it is cleared.*/
2931 WaterClass wc = GetWaterClass(tile_cur);
2932
2933 bool add_cost = !IsWaterTile(tile_cur);
2934 ret = Command<Commands::LandscapeClear>::Do(flags, tile_cur);
2935 if (ret.Failed()) return ret;
2936 if (add_cost) cost.AddCost(ret.GetCost());
2937
2938 tile_cur += TileOffsByDiagDir(direction);
2939 if (!IsTileType(tile_cur, TileType::Water) || !IsTileFlat(tile_cur)) {
2940 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2941 }
2942
2943 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2944 _dock_w_chk[direction], _dock_h_chk[direction]);
2945
2946 /* middle */
2947 Station *st = nullptr;
2948 ret = FindJoiningStation(StationID::Invalid(), station_to_join, adjacent, dock_area, &st);
2949 if (ret.Failed()) return ret;
2950
2951 /* Distant join */
2952 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2953
2954 ret = BuildStationPart(&st, flags, reuse, dock_area, StationNaming::Dock);
2955 if (ret.Failed()) return ret;
2956
2957 if (flags.Test(DoCommandFlag::Execute)) {
2958 st->ship_station.Add(tile);
2959 TileIndex flat_tile = tile + TileOffsByDiagDir(direction);
2960 st->ship_station.Add(flat_tile);
2962
2963 st->spread.Add(dock_area);
2964
2965 /* If the water part of the dock is on a canal, update infrastructure counts.
2966 * This is needed as we've cleared that tile before.
2967 * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
2968 * See: MakeWaterKeepingClass() */
2969 if (wc == WaterClass::Canal && !(HasTileWaterClass(flat_tile) && GetWaterClass(flat_tile) == WaterClass::Canal && IsTileOwner(flat_tile, _current_company))) {
2970 Company::Get(st->owner)->infrastructure.water++;
2971 }
2972 Company::Get(st->owner)->infrastructure.station += 2;
2973
2974 MakeDock(tile, st->owner, st->index, direction, wc);
2975 UpdateStationDockingTiles(st);
2976
2978 }
2979
2980 return cost;
2981}
2982
2983void RemoveDockingTile(TileIndex t)
2984{
2985 for (DiagDirection d : EnumRange(DiagDirection::End)) {
2986 TileIndex tile = t + TileOffsByDiagDir(d);
2987 if (!IsValidTile(tile)) continue;
2988
2989 if (IsTileType(tile, TileType::Station)) {
2990 Station *st = Station::GetByTile(tile);
2991 if (st != nullptr) UpdateStationDockingTiles(st);
2992 } else if (IsTileType(tile, TileType::Industry)) {
2994 if (neutral != nullptr) UpdateStationDockingTiles(neutral);
2995 }
2996 }
2997}
2998
3005{
3006 assert(IsValidTile(tile));
3007
3008 /* Clear and maybe re-set docking tile */
3010 TileIndex docking_tile = tile + TileOffsByDiagDir(d);
3011 if (!IsValidTile(docking_tile)) continue;
3012
3013 if (IsPossibleDockingTile(docking_tile)) {
3014 SetDockingTile(docking_tile, false);
3015 CheckForDockingTile(docking_tile);
3016 }
3017 }
3018}
3019
3026{
3027 assert(IsDockTile(t));
3028
3029 StationGfx gfx = GetStationGfx(t);
3030 if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
3031
3033 TileIndex tile = t + TileOffsByDiagDir(d);
3034 if (!IsValidTile(tile)) continue;
3035 if (!IsDockTile(tile)) continue;
3036 if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
3037 }
3038
3039 return INVALID_TILE;
3040}
3041
3049{
3050 Station *st = Station::GetByTile(tile);
3051 CommandCost ret = CheckOwnership(st->owner);
3052 if (ret.Failed()) return ret;
3053
3054 if (!IsDockTile(tile)) return CMD_ERROR;
3055
3056 TileIndex tile1 = FindDockLandPart(tile);
3057 if (tile1 == INVALID_TILE) return CMD_ERROR;
3058 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
3059
3060 ret = EnsureNoVehicleOnGround(tile1);
3061 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
3062 if (ret.Failed()) return ret;
3063
3064 if (flags.Test(DoCommandFlag::Execute)) {
3065 DoClearSquare(tile1);
3066 MarkTileDirtyByTile(tile1);
3067 MakeWaterKeepingClass(tile2, st->owner);
3068
3069 MakeShipStationAreaSmaller(st);
3071
3072 if (st->ship_station.IsEmpty()) {
3073 st->docking_station.Clear();
3075 SetWindowClassesDirty(WindowClass::VehicleOrders);
3076 }
3077
3078 Company::Get(st->owner)->infrastructure.station -= 2;
3079
3081
3084
3085 for (Ship *s : Ship::Iterate()) {
3086 /* Find all ships going to our dock. */
3087 if (s->current_order.GetDestination() != st->index) {
3088 continue;
3089 }
3090
3091 /* Find ships that are marked as "loading" but are no longer on a
3092 * docking tile. Force them to leave the station (as they were loading
3093 * on the removed dock). */
3094 if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
3095 s->LeaveStation();
3096 }
3097
3098 /* If we no longer have a dock, mark the order as invalid and send
3099 * the ship to the next order (or, if there is none, make it
3100 * wander the world). */
3101 if (s->current_order.IsType(OT_GOTO_STATION) && !st->facilities.Test(StationFacility::Dock)) {
3102 s->SetDestTile(s->GetOrderStationLocation(st->index));
3103 }
3104 }
3105 }
3106
3108}
3109
3117{
3118 const auto &layouts = _station_display_datas[st];
3119 if (gfx >= layouts.size()) gfx &= 1;
3120 return layouts.data() + gfx;
3121}
3122
3132bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
3133{
3134 bool snow_desert;
3135 switch (*ground) {
3136 case SPR_RAIL_TRACK_X:
3137 case SPR_MONO_TRACK_X:
3138 case SPR_MGLV_TRACK_X:
3139 snow_desert = false;
3140 *overlay_offset = RailTrackOffset::X;
3141 break;
3142
3143 case SPR_RAIL_TRACK_Y:
3144 case SPR_MONO_TRACK_Y:
3145 case SPR_MGLV_TRACK_Y:
3146 snow_desert = false;
3147 *overlay_offset = RailTrackOffset::Y;
3148 break;
3149
3153 snow_desert = true;
3154 *overlay_offset = RailTrackOffset::X;
3155 break;
3156
3160 snow_desert = true;
3161 *overlay_offset = RailTrackOffset::Y;
3162 break;
3163
3164 default:
3165 return false;
3166 }
3167
3168 if (ti != nullptr) {
3169 /* Decide snow/desert from tile */
3170 switch (_settings_game.game_creation.landscape) {
3172 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
3173 break;
3174
3176 snow_desert = GetTropicZone(ti->tile) == TropicZone::Desert;
3177 break;
3178
3179 default:
3180 break;
3181 }
3182 }
3183
3184 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
3185 return true;
3186}
3187
3194static BridgePillarFlags GetStationBlockedPillars(std::span<const BridgeableTileInfo> bridgeable_info, uint8_t layout)
3195{
3196 if (layout < std::size(bridgeable_info)) return bridgeable_info[layout].disallowed_pillars;
3197 return BRIDGEPILLARFLAGS_ALL;
3198}
3199
3209{
3210 if (statspec == nullptr || !statspec->flags.Test(StationSpecFlag::CustomFoundations)) return false;
3211
3212 /* Station has custom foundations.
3213 * Check whether the foundation continues beyond the tile's upper sides. */
3214 uint edge_info = GetFoundationSpriteBlock(ti->tile);
3215 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, gfx, edge_info);
3216 if (image == 0) return false;
3217
3219 /* Station provides extended foundations. */
3220 static constexpr uint8_t foundation_parts[] = {
3221 UINT8_MAX, UINT8_MAX, UINT8_MAX, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3222 UINT8_MAX, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3223 UINT8_MAX, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3224 7, 8, 9, // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3225 };
3226 assert(ti->tileh < std::size(foundation_parts));
3227 if (foundation_parts[ti->tileh] == UINT8_MAX) return false;
3228
3229 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, *ti, {{}, {TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1}, {}});
3230 } else {
3231 /* Draw simple foundations, built up from 8 possible foundation sprites.
3232 * Each set bit represents one of the eight composite sprites to be drawn.
3233 * 'Invalid' entries will not drawn but are included for completeness. */
3234 static constexpr uint8_t composite_foundation_parts[] = {
3235 0b0000'0000, 0b1101'0001, 0b1110'0100, 0b1110'0000, // Invalid, Invalid, Invalid, SLOPE_SW
3236 0b1100'1010, 0b1100'1001, 0b1100'0100, 0b1100'0000, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3237 0b1101'0010, 0b1001'0001, 0b1110'0100, 0b1010'0000, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3238 0b0100'1010, 0b0000'1001, 0b0100'0100, // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3239 };
3240 assert(ti->tileh < std::size(composite_foundation_parts));
3241
3242 uint8_t parts = composite_foundation_parts[ti->tileh];
3243
3244 /* If foundations continue beyond the tile's upper sides then mask out the last two pieces. */
3245 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
3246 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
3247
3248 /* We always have to draw at least one sprite, so if we have no parts to draw fall back to default foundation. */
3249 if (parts == 0) return false;
3250
3252 for (uint i : SetBitIterator(parts)) {
3253 AddSortableSpriteToDraw(image + i, PAL_NONE, *ti, {{}, {TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1}, {}});
3254 }
3256 }
3257
3258 OffsetGroundSprite(0, -static_cast<int>(TILE_HEIGHT));
3260
3261 return true;
3262}
3263
3266{
3267 const NewGRFSpriteLayout *layout = nullptr;
3268 SpriteLayoutProcessor processor; // owns heap, borrowed by tmp_layout and t
3269 DrawTileSpriteSpan tmp_layout;
3270 const DrawTileSprites *t = nullptr;
3271 int32_t total_offset;
3272 const RailTypeInfo *rti = nullptr;
3273 uint32_t relocation = 0;
3274 uint32_t ground_relocation = 0;
3275 BaseStation *st = nullptr;
3276 const StationSpec *statspec = nullptr;
3277 uint tile_layout = 0;
3278 auto bridgeable_info = GetStationBridgeableTileInfo(GetStationType(ti->tile));
3279
3280 if (HasStationRail(ti->tile)) {
3281 rti = GetRailTypeInfo(GetRailType(ti->tile));
3282 total_offset = rti->GetRailtypeSpriteOffset();
3283
3284 if (IsCustomStationSpecIndex(ti->tile)) {
3285 /* look for customization */
3286 st = BaseStation::GetByTile(ti->tile);
3287 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
3288
3289 if (statspec != nullptr) {
3290 tile_layout = GetStationGfx(ti->tile);
3291
3293 uint16_t callback = GetStationCallback(CBID_STATION_DRAW_TILE_LAYOUT, 0, 0, statspec, st, ti->tile);
3294 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + to_underlying(GetRailStationAxis(ti->tile));
3295 }
3296
3297 /* Ensure the chosen tile layout is valid for this custom station */
3298 if (!statspec->renderdata.empty()) {
3299 layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
3300 if (!layout->NeedsPreprocessing()) {
3301 t = layout;
3302 layout = nullptr;
3303 }
3304 }
3305 }
3306 }
3307 if (statspec != nullptr) bridgeable_info = statspec->bridgeable_info;
3308 } else {
3309 total_offset = 0;
3310 }
3311
3312 StationGfx gfx = GetStationGfx(ti->tile);
3313 if (IsAirport(ti->tile)) {
3314 gfx = GetAirportGfx(ti->tile);
3315 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
3316 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
3317 if (ats->grf_prop.HasSpriteGroups() && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), ats)) {
3318 return;
3319 }
3320 /* No sprite group (or no valid one) found, meaning no graphics associated.
3321 * Use the substitute one instead */
3322 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
3323 gfx = ats->grf_prop.subst_id;
3324 }
3325 switch (gfx) {
3326 case APT_RADAR_GRASS_FENCE_SW:
3327 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
3328 break;
3329 case APT_GRASS_FENCE_NE_FLAG:
3330 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
3331 break;
3332 case APT_RADAR_FENCE_SW:
3333 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
3334 break;
3335 case APT_RADAR_FENCE_NE:
3336 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
3337 break;
3338 case APT_GRASS_FENCE_NE_FLAG_2:
3339 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
3340 break;
3341 }
3342 }
3343
3344 Owner owner = GetTileOwner(ti->tile);
3345
3346 PaletteID palette;
3347 if (Company::IsValidID(owner)) {
3348 palette = GetCompanyPalette(owner);
3349 } else {
3350 /* Some stations are not owner by a company, namely oil rigs */
3351 palette = PALETTE_TO_GREY;
3352 }
3353
3354 if (layout == nullptr && t == nullptr) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
3355
3356 /* don't show foundation for docks */
3357 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
3358 if (!DrawCustomStationFoundations(statspec, st, ti, tile_layout)) {
3360 }
3361 }
3362
3363 bool draw_ground = false;
3364
3365 if (IsBuoy(ti->tile)) {
3366 DrawWaterClassGround(ti);
3368 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
3369 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
3370 if (ti->tileh == SLOPE_FLAT) {
3371 DrawWaterClassGround(ti);
3372 } else {
3373 assert(IsDock(ti->tile));
3374 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
3375 WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WaterClass::Invalid;
3376 if (wc == WaterClass::Sea) {
3377 DrawShoreTile(ti->tileh);
3378 } else {
3379 DrawClearLandTile(ti, 3);
3380 }
3381 }
3382 } else if (IsRoadWaypointTile(ti->tile)) {
3384 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3385 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3386 RoadBits road = (road_rt != INVALID_ROADTYPE) ? bits : RoadBits{};
3387 RoadBits tram = (tram_rt != INVALID_ROADTYPE) ? bits : RoadBits{};
3388 const RoadTypeInfo *road_rti = (road_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(road_rt) : nullptr;
3389 const RoadTypeInfo *tram_rti = (tram_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(tram_rt) : nullptr;
3390
3391 if (ti->tileh != SLOPE_FLAT) {
3393 }
3394
3395 DrawRoadGroundSprites(ti, road, tram, road_rti, tram_rti, GetRoadWaypointRoadside(ti->tile), IsRoadWaypointOnSnowOrDesert(ti->tile));
3396 } else {
3397 if (layout != nullptr) {
3398 /* Sprite layout which needs preprocessing */
3399 bool separate_ground = statspec->flags.Test(StationSpecFlag::SeparateGround);
3400 processor = SpriteLayoutProcessor(*layout, total_offset, rti->fallback_railtype, 0, 0, separate_ground);
3401 GetCustomStationRelocation(processor, statspec, st, ti->tile);
3402 tmp_layout = processor.GetLayout();
3403 t = &tmp_layout;
3404 total_offset = 0;
3405 } else if (statspec != nullptr) {
3406 /* Simple sprite layout */
3407 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
3409 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
3410 }
3411 ground_relocation += rti->fallback_railtype;
3412 }
3413
3414 draw_ground = true;
3415 }
3416
3417 if (draw_ground && !IsAnyRoadStop(ti->tile)) {
3418 SpriteID image = t->ground.sprite;
3419 PaletteID pal = t->ground.pal;
3420 RailTrackOffset overlay_offset;
3421 if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3423 DrawGroundSprite(image, PAL_NONE);
3424 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3425
3426 if (_game_mode != GameMode::Menu && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3428 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3429 }
3430 } else {
3431 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3432 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3433 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3434
3435 /* PBS debugging, draw reserved tracks darker */
3436 if (_game_mode != GameMode::Menu && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3438 }
3439 }
3440 }
3441
3443
3444 if (IsAnyRoadStop(ti->tile)) {
3445 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3446 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3447 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3448 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3449
3450 StationGfx view = GetStationGfx(ti->tile);
3451 StationType type = GetStationType(ti->tile);
3452
3453 const RoadStopSpec *stopspec = GetRoadStopSpec(ti->tile);
3454 RoadStopDrawModes stop_draw_mode{};
3455 if (stopspec != nullptr) {
3456 stop_draw_mode = stopspec->draw_mode;
3457 st = BaseStation::GetByTile(ti->tile);
3458 std::array<int32_t, 1> regs100;
3459 auto result = GetRoadStopLayout(ti, stopspec, st, type, view, regs100);
3460 if (result.has_value()) {
3461 if (stopspec->flags.Test(RoadStopSpecFlag::DrawModeRegister)) {
3462 stop_draw_mode = static_cast<RoadStopDrawModes>(regs100[0]);
3463 }
3464 if (type == StationType::RoadWaypoint && stop_draw_mode.Test(RoadStopDrawMode::WaypGround)) {
3465 draw_ground = true;
3466 }
3467 processor = std::move(*result);
3468 tmp_layout = processor.GetLayout();
3469 t = &tmp_layout;
3470 }
3471 }
3472
3473 /* Draw ground sprite */
3474 if (draw_ground) {
3475 SpriteID image = t->ground.sprite;
3476 PaletteID pal = t->ground.pal;
3477 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3478 if (GB(image, 0, SPRITE_WIDTH) != 0) {
3479 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3480 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3481 }
3482 }
3483
3484 if (IsDriveThroughStopTile(ti->tile)) {
3485 if (type != StationType::RoadWaypoint && (stopspec == nullptr || stop_draw_mode.Test(RoadStopDrawMode::Overlay))) {
3486 uint sprite_offset = GetDriveThroughStopAxis(ti->tile) == Axis::X ? 1 : 0;
3487 DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3488 }
3489 } else {
3490 /* Non-drivethrough road stops are only valid for roads. */
3491 assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3492
3493 if ((stopspec == nullptr || stop_draw_mode.Test(RoadStopDrawMode::Road)) && road_rti->UsesOverlay()) {
3495 DrawGroundSprite(ground + view, PAL_NONE);
3496 }
3497 }
3498 if (stopspec != nullptr) bridgeable_info = stopspec->bridgeable_info;
3499
3500 if (stopspec == nullptr || !stopspec->flags.Test(RoadStopSpecFlag::NoCatenary)) {
3501 /* Draw road, tram catenary */
3502 DrawRoadCatenary(ti);
3503 }
3504 }
3505
3506 if (IsRailWaypoint(ti->tile)) {
3507 /* Don't offset the waypoint graphics; they're always the same. */
3508 total_offset = 0;
3509 }
3510
3511 DrawRailTileSeq(ti, t, TransparencyOption::Buildings, total_offset, relocation, palette);
3512 DrawBridgeMiddle(ti, GetStationBlockedPillars(bridgeable_info, GetStationGfx(ti->tile)));
3513}
3514
3515void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3516{
3517 int32_t total_offset = 0;
3519 const DrawTileSprites *t = GetStationTileLayout(st, image);
3520 const RailTypeInfo *railtype_info = nullptr;
3521
3522 if (railtype != INVALID_RAILTYPE) {
3523 railtype_info = GetRailTypeInfo(railtype);
3524 total_offset = railtype_info->GetRailtypeSpriteOffset();
3525 }
3526
3527 SpriteID img = t->ground.sprite;
3528 RailTrackOffset overlay_offset;
3529 if (railtype_info != nullptr && railtype_info->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3531 DrawSprite(img, PAL_NONE, x, y);
3532 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3533 } else {
3534 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3535 }
3536
3537 if (roadtype != INVALID_ROADTYPE) {
3538 const RoadTypeInfo *roadtype_info = GetRoadTypeInfo(roadtype);
3539 if (image >= 4) {
3540 /* Drive-through stop */
3541 uint sprite_offset = 5 - image;
3542
3543 /* Road underlay takes precedence over tram */
3544 if (roadtype_info->UsesOverlay()) {
3546 DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3547
3549 if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3550 } else if (RoadTypeIsTram(roadtype)) {
3551 DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3552 }
3553 } else {
3554 /* Bay stop */
3555 if (RoadTypeIsRoad(roadtype) && roadtype_info->UsesOverlay()) {
3557 DrawSprite(ground + image, PAL_NONE, x, y);
3558 }
3559 }
3560 }
3561
3562 /* Default waypoint has no railtype specific sprites */
3563 DrawRailTileSeqInGUI(x, y, t, (st == StationType::RailWaypoint || st == StationType::RoadWaypoint) ? 0 : total_offset, 0, pal);
3564}
3565
3566
3567static void FillTileDescRoadStop(TileIndex tile, TileDesc &td)
3568{
3569 RoadType road_rt = GetRoadTypeRoad(tile);
3570 RoadType tram_rt = GetRoadTypeTram(tile);
3571 Owner road_owner = INVALID_OWNER;
3572 Owner tram_owner = INVALID_OWNER;
3573 if (road_rt != INVALID_ROADTYPE) {
3574 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3575 td.roadtype = rti->strings.name;
3576 td.road_speed = rti->max_speed / 2;
3577 road_owner = GetRoadOwner(tile, RoadTramType::Road);
3578 }
3579
3580 if (tram_rt != INVALID_ROADTYPE) {
3581 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3582 td.tramtype = rti->strings.name;
3583 td.tram_speed = rti->max_speed / 2;
3584 tram_owner = GetRoadOwner(tile, RoadTramType::Tram);
3585 }
3586
3587 if (IsDriveThroughStopTile(tile)) {
3588 /* Is there a mix of owners? */
3589 if ((tram_owner != INVALID_OWNER && tram_owner != td.owner[0]) ||
3590 (road_owner != INVALID_OWNER && road_owner != td.owner[0])) {
3591 uint i = 1;
3592 if (road_owner != INVALID_OWNER) {
3593 td.owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3594 td.owner[i] = road_owner;
3595 i++;
3596 }
3597 if (tram_owner != INVALID_OWNER) {
3598 td.owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3599 td.owner[i] = tram_owner;
3600 }
3601 }
3602 }
3603}
3604
3605void FillTileDescRailStation(TileIndex tile, TileDesc &td)
3606{
3607 const StationSpec *spec = GetStationSpec(tile);
3608
3609 if (spec != nullptr) {
3611 td.station_name = spec->name;
3612
3613 if (spec->grf_prop.HasGrfFile()) {
3614 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grfid);
3615 td.grf = gc->GetName();
3616 }
3617 }
3618
3619 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3620 td.rail_speed = rti->max_speed;
3621 td.railtype = rti->strings.name;
3622}
3623
3624void FillTileDescAirport(TileIndex tile, TileDesc &td)
3625{
3626 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3628 td.airport_name = as->name;
3629
3630 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3631 td.airport_tile_name = ats->name;
3632
3633 if (as->grf_prop.HasGrfFile()) {
3634 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grfid);
3635 td.grf = gc->GetName();
3636 } else if (ats->grf_prop.HasGrfFile()) {
3637 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grfid);
3638 td.grf = gc->GetName();
3639 }
3640}
3641
3644{
3645 td.owner[0] = GetTileOwner(tile);
3647
3648 if (IsAnyRoadStop(tile)) FillTileDescRoadStop(tile, td);
3649 if (HasStationRail(tile)) FillTileDescRailStation(tile, td);
3650 if (IsAirport(tile)) FillTileDescAirport(tile, td);
3651
3652 StringID str;
3653 switch (GetStationType(tile)) {
3654 default: NOT_REACHED();
3655 case StationType::Rail: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3657 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3658 break;
3659 case StationType::Truck: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3660 case StationType::Bus: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3661 case StationType::Oilrig: {
3662 const Industry *i = Station::GetByTile(tile)->industry;
3663 const IndustrySpec *is = GetIndustrySpec(i->type);
3664 td.owner[0] = i->owner;
3665 str = is->name;
3666 if (is->grf_prop.HasGrfFile()) td.grf = GetGRFConfig(is->grf_prop.grfid)->GetName();
3667 break;
3668 }
3669 case StationType::Dock: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3670 case StationType::Buoy: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3671 case StationType::RailWaypoint: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3672 case StationType::RoadWaypoint: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3673 }
3674 td.str = str;
3675}
3676
3677
3680{
3681 TrackBits trackbits{};
3682
3683 switch (mode) {
3685 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3686 trackbits = GetRailStationTrack(tile);
3687 }
3688 break;
3689
3691 /* buoy is coded as a station, it is always on open water */
3692 if (IsBuoy(tile)) {
3693 trackbits = TRACK_BIT_ALL;
3694 /* remove tracks that connect NE map edge */
3695 if (TileX(tile) == 0) trackbits.Reset(TRACK_BIT_3WAY_NE);
3696 /* remove tracks that connect NW map edge */
3697 if (TileY(tile) == 0) trackbits.Reset({Track::Y, Track::Left, Track::Upper});
3698 }
3699 break;
3700
3702 if (IsAnyRoadStop(tile)) {
3703 RoadTramType rtt = (RoadTramType)sub_mode;
3704 if (!HasTileRoadType(tile, rtt)) break;
3705
3706 if (IsBayRoadStopTile(tile)) {
3707 DiagDirection dir = GetBayRoadStopDir(tile);
3708 if (side != DiagDirection::Invalid && dir != side) break;
3709 trackbits = DiagDirToDiagTrack(dir);
3710 } else {
3711 Axis axis = GetDriveThroughStopAxis(tile);
3712 if (side != DiagDirection::Invalid && axis != DiagDirToAxis(side)) break;
3713 trackbits = AxisToTrack(axis);
3714 }
3715 }
3716 break;
3717
3718 default:
3719 break;
3720 }
3721
3722 return {TrackBitsToTrackdirBits(trackbits), {}};
3723}
3724
3725
3728{
3729 auto *st = BaseStation::GetByTile(tile);
3730 switch (GetStationType(tile)) {
3732 TriggerAirportTileAnimation(Station::From(st), tile, AirportAnimationTrigger::TileLoop);
3733 break;
3734
3735 case StationType::Rail:
3737 TriggerStationAnimation(st, tile, StationAnimationTrigger::TileLoop);
3738 break;
3739
3740 case StationType::Dock:
3741 if (!IsTileFlat(tile)) break; // only handle water part
3742 [[fallthrough]];
3743
3744 case StationType::Oilrig: //(station part)
3745 case StationType::Buoy:
3746 TileLoop_Water(tile);
3747 break;
3748
3749 case StationType::Truck:
3750 case StationType::Bus:
3751 TriggerRoadStopAnimation(st, tile, StationAnimationTrigger::TileLoop);
3752 break;
3753
3755 switch (_settings_game.game_creation.landscape) {
3757 if (IsRoadWaypointOnSnowOrDesert(tile) != (GetTileZ(tile) > GetSnowLine())) {
3759 MarkTileDirtyByTile(tile);
3760 }
3761 break;
3762
3766 MarkTileDirtyByTile(tile);
3767 }
3768 break;
3769
3770 default: break;
3771 }
3772
3773 HouseZone new_zone = HouseZone::TownEdge;
3774 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
3775 if (t != nullptr) {
3776 new_zone = GetTownRadiusGroup(t, tile);
3777 }
3778
3779 /* Adjust road ground type depending on 'new_zone' */
3781 Roadside cur_rs = GetRoadWaypointRoadside(tile);
3782
3783 if (new_rs != cur_rs) {
3784 SetRoadWaypointRoadside(tile, cur_rs == Roadside::Barren ? new_rs : Roadside::Barren);
3785 MarkTileDirtyByTile(tile);
3786 }
3787
3788 TriggerRoadStopAnimation(st, tile, StationAnimationTrigger::TileLoop);
3789 break;
3790 }
3791
3792 default: break;
3793 }
3794}
3795
3796
3799{
3800 if (HasStationRail(tile)) {
3801 AnimateStationTile(tile);
3802 return;
3803 }
3804
3805 if (IsAirport(tile)) {
3806 AnimateAirportTile(tile);
3807 return;
3808 }
3809
3810 if (IsAnyRoadStopTile(tile)) {
3811 AnimateRoadStopTile(tile);
3812 return;
3813 }
3814}
3815
3816
3819{
3820 const BaseStation *bst = BaseStation::GetByTile(tile);
3821
3824 } else if (IsHangar(tile)) {
3825 const Station *st = Station::From(bst);
3827 } else {
3828 ShowStationViewWindow(bst->index);
3829 }
3830 return true;
3831}
3832
3835{
3836 if (v->type == VehicleType::Train) {
3837 StationID station_id = GetStationIndex(tile);
3838 if (!IsRailStation(tile) || !v->IsMovingFront()) return {};
3839 Vehicle *consist = v->First();
3840 if (!consist->current_order.ShouldStopAtStation(consist, station_id)) return {};
3841
3842 int station_ahead;
3843 int station_length;
3844 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3845
3846 /* Stop whenever that amount of station ahead + the distance from the
3847 * begin of the platform to the stop location is longer than the length
3848 * of the platform. Station ahead 'includes' the current tile where the
3849 * vehicle is on, so we need to subtract that. */
3850 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return {};
3851
3853
3854 x &= 0xF;
3855 y &= 0xF;
3856
3857 if (DiagDirToAxis(dir) != Axis::X) std::swap(x, y);
3858 if (y == TILE_SIZE / 2) {
3859 if (dir != DiagDirection::SE && dir != DiagDirection::SW) x = TILE_SIZE - 1 - x;
3860 stop &= TILE_SIZE - 1;
3861
3862 if (x == stop) {
3863 return VehicleEnterTileState::EnteredStation; // enter station
3864 } else if (x < stop) {
3866 uint16_t spd = std::max(0, (stop - x) * 20 - 15);
3867 if (spd < v->cur_speed) v->cur_speed = spd;
3868 }
3869 }
3870 } else if (v->type == VehicleType::Road) {
3872 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir(static_cast<Trackdir>(rv->state)) && rv->frame == 0) {
3873 if (IsStationRoadStop(tile) && rv->IsFrontEngine()) {
3874 /* Attempt to allocate a parking bay in a road stop */
3875 if (RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv)) return {};
3877 }
3878 }
3879 }
3880
3881 return {};
3882}
3883
3889{
3890 /* Collect cargoes accepted since the last big tick. */
3891 CargoTypes cargoes{};
3892 for (CargoType cargo_type : EnumRange(NUM_CARGO)) {
3893 if (st->goods[cargo_type].status.Test(GoodsEntry::State::AcceptedBigtick)) cargoes.Set(cargo_type);
3894 }
3895
3896 /* Anything to do? */
3897 if (cargoes.None()) return;
3898
3899 /* Loop over all houses in the catchment. */
3900 for (TileIndex tile : st->catchment_tiles) {
3901 if (IsTileType(tile, TileType::House)) {
3903 }
3904 }
3905}
3906
3914{
3915 if (!st->IsInUse()) {
3916 if (++st->delete_ctr >= 8) delete st;
3917 return false;
3918 }
3919
3920 if (Station::IsExpected(st)) {
3922
3923 for (GoodsEntry &ge : Station::From(st)->goods) {
3925 }
3926 }
3927
3928
3930
3931 return true;
3932}
3933
3934static inline void byte_inc_sat(uint8_t *p)
3935{
3936 uint8_t b = *p + 1;
3937 if (b != 0) *p = b;
3938}
3939
3946static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3947{
3948 /* If truncating also punish the source stations' ratings to
3949 * decrease the flow of incoming cargo. */
3950
3951 if (!ge->HasData()) return;
3952
3953 StationCargoAmountMap waiting_per_source;
3954 ge->GetData().cargo.Truncate(amount, &waiting_per_source);
3955 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3956 Station *source_station = Station::GetIfValid(i->first);
3957 if (source_station == nullptr) continue;
3958
3959 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3960 source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3961 }
3962}
3963
3969{
3970 bool waiting_changed = false;
3971
3972 byte_inc_sat(&st->time_since_load);
3973 byte_inc_sat(&st->time_since_unload);
3974
3975 for (const CargoSpec *cs : CargoSpec::Iterate()) {
3976 GoodsEntry *ge = &st->goods[cs->Index()];
3977
3978 /* The station might not currently be moving this cargo. */
3979 if (!ge->HasRating()) {
3980 /* Slowly increase the rating back to its original level in the case we
3981 * didn't deliver cargo yet to this station. This happens when a bribe
3982 * failed while you didn't moved that cargo yet to a station. */
3983 if (ge->rating < INITIAL_STATION_RATING) ge->rating++;
3984
3985 /* Nothing else to do with this cargo. */
3986 continue;
3987 }
3988
3989 byte_inc_sat(&ge->time_since_pickup);
3990
3991 /* If this cargo hasn't been picked up in a long time, get rid of it. */
3992 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3994 ge->last_speed = 0;
3995 ge->GetOrCreateHistory().lost += ge->TotalCount();
3996 TruncateCargo(cs, ge);
3997 waiting_changed = true;
3998 continue;
3999 }
4000
4001 bool skip = false;
4002 int rating = 0;
4003 uint waiting = ge->AvailableCount();
4004
4005 /* num_dests is at least 1 if there is any cargo as
4006 * StationID::Invalid() is also a destination.
4007 */
4008 uint num_dests = ge->HasData() ? static_cast<uint>(ge->GetData().cargo.Packets()->MapSize()) : 0;
4009
4010 /* Average amount of cargo per next hop, but prefer solitary stations
4011 * with only one or two next hops. They are allowed to have more
4012 * cargo waiting per next hop.
4013 * With manual cargo distribution waiting_avg = waiting / 2 as then
4014 * StationID::Invalid() is the only destination.
4015 */
4016 uint waiting_avg = waiting / (num_dests + 1);
4017
4018 if (_cheats.station_rating.value) {
4019 ge->rating = rating = MAX_STATION_RATING;
4020 skip = true;
4021 } else if (cs->callback_mask.Test(CargoCallbackMask::StationRatingCalc)) {
4022 /* Perform custom station rating. If it succeeds the speed, days in transit and
4023 * waiting cargo ratings must not be executed. */
4024
4025 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
4026 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
4027
4028 uint32_t var18 = ClampTo<uint8_t>(ge->time_since_pickup)
4030 | (ClampTo<uint8_t>(last_speed) << 24);
4031 /* Convert to the 'old' vehicle types */
4032 uint32_t var10 = (st->last_vehicle_type == VehicleType::Invalid) ? 0x0 : (to_underlying(st->last_vehicle_type) + 0x10);
4033 uint16_t callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
4034 if (callback != CALLBACK_FAILED) {
4035 skip = true;
4036 rating = GB(callback, 0, 14);
4037
4038 /* Simulate a 15 bit signed value */
4039 if (HasBit(callback, 14)) rating -= 0x4000;
4040 }
4041 }
4042
4043 if (!skip) {
4044 int b = ge->last_speed - 85;
4045 if (b >= 0) rating += b >> 2;
4046
4047 uint8_t waittime = ge->time_since_pickup;
4048 if (st->last_vehicle_type == VehicleType::Ship) waittime >>= 2;
4049 if (waittime <= 21) rating += 25;
4050 if (waittime <= 12) rating += 25;
4051 if (waittime <= 6) rating += 45;
4052 if (waittime <= 3) rating += 35;
4053
4054 rating -= 90;
4055 if (ge->max_waiting_cargo <= 1500) rating += 55;
4056 if (ge->max_waiting_cargo <= 1000) rating += 35;
4057 if (ge->max_waiting_cargo <= 600) rating += 10;
4058 if (ge->max_waiting_cargo <= 300) rating += 20;
4059 if (ge->max_waiting_cargo <= 100) rating += 10;
4060 }
4061
4062 if (Company::IsValidID(st->owner) && st->town->statues.Test(st->owner)) rating += 26;
4063
4064 uint8_t age = ge->last_age;
4065 if (age < 3) rating += 10;
4066 if (age < 2) rating += 10;
4067 if (age < 1) rating += 13;
4068
4069 {
4070 int or_ = ge->rating; // old rating
4071 uint old_waiting = waiting;
4072
4073 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
4074 ge->rating = rating = ClampTo<uint8_t>(or_ + Clamp(rating - or_, -2, 2));
4075
4076 /* if rating is <= 64 and more than 100 items waiting on average per destination,
4077 * remove some random amount of goods from the station */
4078 if (rating <= 64 && waiting_avg >= 100) {
4079 int dec = Random() & 0x1F;
4080 if (waiting_avg < 200) dec &= 7;
4081 waiting -= (dec + 1) * num_dests;
4082 waiting_changed = true;
4083 }
4084
4085 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
4086 if (rating <= 127 && waiting != 0) {
4087 uint32_t r = Random();
4088 if (rating <= (int)GB(r, 0, 7)) {
4089 /* Need to have int, otherwise it will just overflow etc. */
4090 waiting = std::max((int)waiting - (int)((GB(r, 8, 2) + 1) * num_dests), 0);
4091 waiting_changed = true;
4092 }
4093 }
4094
4095 /* At some point we really must cap the cargo. Previously this
4096 * was a strict 4095, but now we'll have a less strict, but
4097 * increasingly aggressive truncation of the amount of cargo. */
4098 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
4099 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
4100 static const uint MAX_WAITING_CARGO = 1 << 15;
4101
4102 if (waiting > WAITING_CARGO_THRESHOLD) {
4103 uint difference = waiting - WAITING_CARGO_THRESHOLD;
4104 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
4105
4106 waiting = std::min(waiting, MAX_WAITING_CARGO);
4107 waiting_changed = true;
4108 }
4109
4110 /* We can't truncate cargo that's already reserved for loading.
4111 * Thus StoredCount() here. */
4112 if (waiting_changed && waiting < old_waiting) {
4113 /* Feed back the exact own waiting cargo at this station for the
4114 * next rating calculation. */
4115 ge->max_waiting_cargo = 0;
4116
4117 ge->GetOrCreateHistory().lost += old_waiting - waiting;
4118 TruncateCargo(cs, ge, old_waiting - waiting);
4119 } else {
4120 /* If the average number per next hop is low, be more forgiving. */
4121 ge->max_waiting_cargo = waiting_avg;
4122 }
4123 }
4124 }
4125
4126 StationID index = st->index;
4127 if (waiting_changed) {
4128 SetWindowDirty(WindowClass::StationView, index); // update whole window
4129 } else {
4130 SetWindowWidgetDirty(WindowClass::StationView, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
4131 }
4132}
4133
4142void RerouteCargo(Station *st, CargoType cargo, StationID avoid, StationID avoid2)
4143{
4144 GoodsEntry &ge = st->goods[cargo];
4145
4146 /* Reroute cargo in station. */
4147 if (ge.HasData()) ge.GetData().cargo.Reroute(UINT_MAX, &ge.GetData().cargo, avoid, avoid2, &ge);
4148
4149 /* Reroute cargo staged to be transferred. */
4150 for (Vehicle *v : st->loading_vehicles) {
4151 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
4152 if (u->cargo_type != cargo) continue;
4153 u->cargo.Reroute(UINT_MAX, &u->cargo, avoid, avoid2, &ge);
4154 }
4155 }
4156}
4157
4167{
4168 for (CargoType cargo : EnumRange(NUM_CARGO)) {
4169 const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(cargo) != DistributionType::Manual);
4170 GoodsEntry &ge = from->goods[cargo];
4172 if (lg == nullptr) continue;
4173 std::vector<NodeID> to_remove{};
4174 for (Edge &edge : (*lg)[ge.node].edges) {
4175 Station *to = Station::Get((*lg)[edge.dest_node].station);
4176 assert(to->goods[cargo].node == edge.dest_node);
4177 assert(TimerGameEconomy::date >= edge.LastUpdate());
4179 if (TimerGameEconomy::date - edge.LastUpdate() > timeout) {
4180 bool updated = false;
4181
4182 if (auto_distributed) {
4183 /* Have all vehicles refresh their next hops before deciding to
4184 * remove the node. */
4185 std::vector<Vehicle *> vehicles;
4186 for (const OrderList *l : OrderList::Iterate()) {
4187 bool found_from = false;
4188 bool found_to = false;
4189 for (const Order &order : l->GetOrders()) {
4190 if (!order.IsType(OT_GOTO_STATION) && !order.IsType(OT_IMPLICIT)) continue;
4191 if (order.GetDestination() == from->index) {
4192 found_from = true;
4193 if (found_to) break;
4194 } else if (order.GetDestination() == to->index) {
4195 found_to = true;
4196 if (found_from) break;
4197 }
4198 }
4199 if (!found_to || !found_from) continue;
4200 vehicles.push_back(l->GetFirstSharedVehicle());
4201 }
4202
4203 auto iter = vehicles.begin();
4204 while (iter != vehicles.end()) {
4205 Vehicle *v = *iter;
4206 /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
4208 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
4209 }
4210 if (edge.LastUpdate() == TimerGameEconomy::date) {
4211 updated = true;
4212 break;
4213 }
4214
4215 Vehicle *next_shared = v->NextShared();
4216 if (next_shared) {
4217 *iter = next_shared;
4218 ++iter;
4219 } else {
4220 iter = vehicles.erase(iter);
4221 }
4222
4223 if (iter == vehicles.end()) iter = vehicles.begin();
4224 }
4225 }
4226
4227 if (!updated) {
4228 /* If it's still considered dead remove it. */
4229 to_remove.emplace_back(to->goods[cargo].node);
4230 if (ge.HasData()) ge.GetData().flows.DeleteFlows(to->index);
4231 RerouteCargo(from, cargo, to->index, from->index);
4232 }
4233 } else if (edge.last_unrestricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_unrestricted_update > timeout) {
4234 edge.Restrict();
4235 if (ge.HasData()) ge.GetData().flows.RestrictFlows(to->index);
4236 RerouteCargo(from, cargo, to->index, from->index);
4237 } else if (edge.last_restricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_restricted_update > timeout) {
4238 edge.Release();
4239 }
4240 }
4241 /* Remove dead edges. */
4242 for (NodeID r : to_remove) (*lg)[ge.node].RemoveEdge(r);
4243
4244 assert(TimerGameEconomy::date >= lg->LastCompression());
4246 lg->Compress();
4247 }
4248 }
4249}
4250
4261void IncreaseStats(Station *st, CargoType cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateModes modes)
4262{
4263 GoodsEntry &ge1 = st->goods[cargo];
4264 Station *st2 = Station::Get(next_station_id);
4265 GoodsEntry &ge2 = st2->goods[cargo];
4266 LinkGraph *lg = nullptr;
4267 if (ge1.link_graph == LinkGraphID::Invalid()) {
4268 if (ge2.link_graph == LinkGraphID::Invalid()) {
4270 lg = LinkGraph::Create(cargo);
4272 ge2.link_graph = lg->index;
4273 ge2.node = lg->AddNode(st2);
4274 } else {
4275 Debug(Facility::Misc, Severity::Critical, "Can't allocate link graph");
4276 }
4277 } else {
4278 lg = LinkGraph::Get(ge2.link_graph);
4279 }
4280 if (lg) {
4281 ge1.link_graph = lg->index;
4282 ge1.node = lg->AddNode(st);
4283 }
4284 } else if (ge2.link_graph == LinkGraphID::Invalid()) {
4285 lg = LinkGraph::Get(ge1.link_graph);
4286 ge2.link_graph = lg->index;
4287 ge2.node = lg->AddNode(st2);
4288 } else {
4289 lg = LinkGraph::Get(ge1.link_graph);
4290 if (ge1.link_graph != ge2.link_graph) {
4292 if (lg->Size() < lg2->Size()) {
4293 LinkGraphSchedule::instance.Dequeue(lg);
4294 lg2->Merge(lg); // Updates GoodsEntries of lg
4295 lg = lg2;
4296 } else {
4297 LinkGraphSchedule::instance.Dequeue(lg2);
4298 lg->Merge(lg2); // Updates GoodsEntries of lg2
4299 }
4300 }
4301 }
4302 if (lg != nullptr) {
4303 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, modes);
4304 }
4305}
4306
4314void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32_t time)
4315{
4316 for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
4317 if (v->refit_cap > 0) {
4318 /* The cargo count can indeed be higher than the refit_cap if
4319 * wagons have been auto-replaced and subsequently auto-
4320 * refitted to a higher capacity. The cargo gets redistributed
4321 * among the wagons in that case.
4322 * As usage is not such an important figure anyway we just
4323 * ignore the additional cargo then.*/
4324 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
4325 std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EdgeUpdateMode::Increase);
4326 }
4327 }
4328}
4329
4330/* called for every station each tick */
4331static void StationHandleSmallTick(BaseStation *st)
4332{
4333 if (st->facilities.Test(StationFacility::Waypoint) || !st->IsInUse()) return;
4334
4335 uint8_t b = st->delete_ctr + 1;
4336 if (b >= Ticks::STATION_RATING_TICKS) b = 0;
4337 st->delete_ctr = b;
4338
4339 if (b == 0) UpdateStationRating(Station::From(st));
4340}
4341
4342void OnTick_Station()
4343{
4344 if (_game_mode == GameMode::Editor) return;
4345
4346 for (BaseStation *st : BaseStation::Iterate()) {
4347 StationHandleSmallTick(st);
4348
4349 /* Clean up the link graph about once a week. */
4352 };
4353
4354 if (Station::IsExpected(st) && (TimerGameTick::counter + st->index) % Ticks::DAY_TICKS == 0) {
4355 for (GoodsEntry &ge : Station::From(st)->goods) {
4356 ge.accumulated_rating += ge.rating;
4357
4358 if (ge.HasData()) {
4360 }
4361 }
4362 }
4363
4364 /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */
4366 /* Stop processing this station if it was deleted */
4367 if (!StationHandleBigTick(st)) continue;
4368 }
4369
4370 /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */
4372 TriggerStationAnimation(st, st->xy, StationAnimationTrigger::AcceptanceTick);
4373 TriggerRoadStopAnimation(st, st->xy, StationAnimationTrigger::AcceptanceTick);
4374 if (Station::IsExpected(st)) TriggerAirportAnimation(Station::From(st), AirportAnimationTrigger::AcceptanceTick);
4375 }
4376 }
4377}
4378
4384template <>
4385GoodsEntry::CargoHistory SumHistory(std::span<const GoodsEntry::CargoHistory> history)
4386{
4387 uint32_t accepted = std::accumulate(std::begin(history), std::end(history), 0, [](uint32_t r, const auto &h) { return r + RxDecompress(h.rx_accepted); });
4388 uint32_t waiting = std::accumulate(std::begin(history), std::end(history), 0, [](uint32_t r, const auto &h) { return r + RxDecompress(h.rx_waiting); });
4389 uint32_t supply = std::accumulate(std::begin(history), std::end(history), 0, [](uint32_t r, const auto &h) { return r + RxDecompress(h.rx_supply); });
4390 uint32_t lost = std::accumulate(std::begin(history), std::end(history), 0, [](uint32_t r, const auto &h) { return r + RxDecompress(h.rx_lost); });
4391 uint16_t rating = std::accumulate(std::begin(history), std::end(history), 0, [](uint16_t r, const auto &h) { return r + h.rating; });
4392 auto count = std::size(history);
4393 return {
4394 .rx_accepted = RxCompress(ClampTo<uint32_t>(accepted / count)),
4395 .rx_waiting = RxCompress(ClampTo<uint32_t>(waiting / count)),
4396 .rx_supply = RxCompress(ClampTo<uint32_t>(supply / count)),
4397 .rx_lost = RxCompress(ClampTo<uint32_t>(lost / count)),
4398 .rating = ClampTo<uint8_t>(rating / count),
4399 };
4400}
4401
4403static const IntervalTimer<TimerGameEconomy> _economy_stations_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::Station}, [](auto)
4404{
4405 for (Station *st : Station::Iterate()) {
4406 UpdateValidHistory(st->valid_cargo_history, HISTORY_YEAR, TimerGameEconomy::month);
4407
4408 for (GoodsEntry &ge : st->goods) {
4411
4412 if (ge.HasRating() || ge.HasHistory()) {
4413 auto &stats = ge.GetOrCreateHistory();
4414 stats.history[THIS_MONTH].rx_waiting = RxCompress(GetAndResetAccumulatedAverage<uint32_t>(stats.accumulated_waiting));
4415 stats.history[THIS_MONTH].rx_supply = RxCompress(stats.supply);
4416 stats.history[THIS_MONTH].rx_lost = RxCompress(stats.lost);
4417 stats.history[THIS_MONTH].rx_accepted = RxCompress(stats.accepted);
4418 stats.history[THIS_MONTH].rating = ToPercent8(GetAndResetAccumulatedAverage<uint8_t>(ge.accumulated_rating));
4419
4420 RotateHistory(stats.history, st->valid_cargo_history, HISTORY_YEAR, TimerGameEconomy::month);
4421
4422 stats.supply = 0;
4423 stats.lost = 0;
4424 stats.accepted = 0;
4425 }
4426 }
4427 }
4428});
4429
4438void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
4439{
4440 ForAllStationsRadius(tile, radius, [&](Station *st) {
4441 if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
4442 for (GoodsEntry &ge : st->goods) {
4443 if (ge.status.Any()) {
4444 ge.rating = ClampTo<uint8_t>(ge.rating + amount);
4445 }
4446 }
4447 }
4448 });
4449}
4450
4451static uint UpdateStationWaiting(Station *st, CargoType cargo, uint amount, Source source)
4452{
4453 /* We can't allocate a CargoPacket? Then don't do anything
4454 * at all; i.e. just discard the incoming cargo. */
4455 if (!CargoPacket::CanAllocateItem()) return 0;
4456
4457 GoodsEntry &ge = st->goods[cargo];
4458 amount += ge.amount_fract;
4459 ge.amount_fract = GB(amount, 0, 8);
4460
4461 amount >>= 8;
4462 /* No new "real" cargo item yet. */
4463 if (amount == 0) return 0;
4464
4465 /* Track amount supplied to the station. */
4466 ge.GetOrCreateHistory().supply += amount;
4467
4468 StationID next = ge.GetVia(st->index);
4469 ge.GetOrCreateData().cargo.Append(CargoPacket::Create(st->index, amount, source), next);
4470 LinkGraph *lg = nullptr;
4471 if (ge.link_graph == LinkGraphID::Invalid()) {
4472 if (LinkGraph::CanAllocateItem()) {
4473 lg = LinkGraph::Create(cargo);
4475 ge.link_graph = lg->index;
4476 ge.node = lg->AddNode(st);
4477 } else {
4478 Debug(Facility::Misc, Severity::Critical, "Can't allocate link graph");
4479 }
4480 } else {
4481 lg = LinkGraph::Get(ge.link_graph);
4482 }
4483 if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
4484
4485 if (!ge.HasRating()) {
4486 InvalidateWindowData(WindowClass::StationList, st->owner);
4488 }
4489
4491 TriggerStationAnimation(st, st->xy, StationAnimationTrigger::NewCargo, cargo);
4492 TriggerAirportAnimation(st, AirportAnimationTrigger::NewCargo, cargo);
4494 TriggerRoadStopAnimation(st, st->xy, StationAnimationTrigger::NewCargo, cargo);
4495
4496
4497 SetWindowDirty(WindowClass::StationView, st->index);
4498 st->MarkTilesDirty(true);
4499 return amount;
4500}
4501
4502static bool IsUniqueStationName(const std::string &name)
4503{
4504 for (const Station *st : Station::Iterate()) {
4505 if (!st->name.empty() && st->name == name) return false;
4506 }
4507
4508 return true;
4509}
4510
4518CommandCost CmdRenameStation(DoCommandFlags flags, StationID station_id, const std::string &text)
4519{
4520 Station *st = Station::GetIfValid(station_id);
4521 if (st == nullptr) return CMD_ERROR;
4522
4523 CommandCost ret = CheckOwnership(st->owner);
4524 if (ret.Failed()) return ret;
4525
4526 bool reset = text.empty();
4527
4528 if (!reset) {
4530 if (!IsUniqueStationName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
4531 }
4532
4533 if (flags.Test(DoCommandFlag::Execute)) {
4534 st->cached_name.clear();
4535 if (reset) {
4536 st->name.clear();
4537 } else {
4538 st->name = text;
4539 }
4540
4541 st->UpdateVirtCoord();
4542 InvalidateWindowData(WindowClass::StationList, st->owner, 1);
4543 }
4544
4545 return CommandCost();
4546}
4547
4555std::tuple<CommandCost, StationID> CmdMoveStationName(DoCommandFlags flags, StationID station_id, TileIndex tile)
4556{
4557 Station *st = Station::GetIfValid(station_id);
4558 if (st == nullptr) return { CMD_ERROR, StationID::Invalid() };
4559
4560 if (st->owner != OWNER_NONE) {
4561 CommandCost ret = CheckOwnership(st->owner);
4562 if (ret.Failed()) return { ret, StationID::Invalid() };
4563 }
4564
4565 if (!st->spread.Contains(tile)) {
4566 return { CommandCost(STR_ERROR_SITE_UNSUITABLE), StationID::Invalid() };
4567 }
4568
4569 bool other_station = false;
4570 /* Check if the tile is the base tile of another station */
4571 ForAllStationsRadius(tile, 0, [&](BaseStation *s) {
4572 if (s != nullptr) {
4573 if (s != st && s->xy == tile) other_station = true;
4574 }
4575 });
4576 if (other_station) return { CommandCost(STR_ERROR_SITE_UNSUITABLE), StationID::Invalid() };
4577
4578 if (flags.Test(DoCommandFlag::Execute)) {
4579 st->MoveSign(tile);
4580
4581 st->UpdateVirtCoord();
4582 st->RecomputeCatchment();
4583 }
4584 return { CommandCost(), station_id };
4585}
4586
4592void CcMoveStationName(Commands, const CommandCost &result, StationID station_id)
4593 {
4594 if (result.Failed()) return;
4595
4597 Station *st = Station::Get(station_id);
4598 SetViewportStationRect(st, false);
4599 }
4600
4601static void AddNearbyStationsByCatchment(TileIndex tile, StationList &stations, StationList &nearby)
4602{
4603 for (Station *st : nearby) {
4604 if (st->TileIsInCatchment(tile)) stations.insert(st);
4605 }
4606}
4607
4613{
4614 if (this->tile != INVALID_TILE) {
4615 if (IsTileType(this->tile, TileType::House)) {
4616 /* Town nearby stations need to be filtered per tile. */
4617 assert(this->w == 1 && this->h == 1);
4618 AddNearbyStationsByCatchment(this->tile, this->stations, Town::GetByTile(this->tile)->stations_near);
4619 } else {
4620 ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex) {
4621 this->stations.insert(st);
4622 return true;
4623 });
4624 }
4625 this->tile = INVALID_TILE;
4626 }
4627 return this->stations;
4628}
4629
4630
4631static bool CanMoveGoodsToStation(const Station *st, CargoType cargo)
4632{
4633 /* Is the station reserved exclusively for somebody else? */
4634 if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
4635
4636 /* Lowest possible rating, better not to give cargo anymore. */
4637 if (st->goods[cargo].rating == 0) return false;
4638
4639 /* Selectively servicing stations, and not this one. */
4640 if (_settings_game.order.selectgoods && !st->goods[cargo].HasVehicleEverTriedLoading()) return false;
4641
4643 /* Passengers are never served by just a truck stop. */
4644 if (st->facilities == StationFacility::TruckStop) return false;
4645 } else {
4646 /* Non-passengers are never served by just a bus stop. */
4647 if (st->facilities == StationFacility::BusStop) return false;
4648 }
4649 return true;
4650}
4651
4652uint MoveGoodsToStation(CargoType cargo, uint amount, Source source, const StationList &all_stations, Owner exclusivity)
4653{
4654 /* Return if nothing to do. Also the rounding below fails for 0. */
4655 if (all_stations.empty()) return 0;
4656 if (amount == 0) return 0;
4657
4658 Station *first_station = nullptr;
4659 typedef std::pair<Station *, uint> StationInfo;
4660 std::vector<StationInfo> used_stations;
4661
4662 for (Station *st : all_stations) {
4663 if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4664 if (!CanMoveGoodsToStation(st, cargo)) continue;
4665
4666 /* Avoid allocating a vector if there is only one station to significantly
4667 * improve performance in this common case. */
4668 if (first_station == nullptr) {
4669 first_station = st;
4670 continue;
4671 }
4672 if (used_stations.empty()) {
4673 used_stations.reserve(2);
4674 used_stations.emplace_back(first_station, 0);
4675 }
4676 used_stations.emplace_back(st, 0);
4677 }
4678
4679 /* no stations around at all? */
4680 if (first_station == nullptr) return 0;
4681
4682 if (used_stations.empty()) {
4683 /* only one station around */
4684 amount *= first_station->goods[cargo].rating + 1;
4685 return UpdateStationWaiting(first_station, cargo, amount, source);
4686 }
4687
4688 TypedIndexContainer<std::array<uint32_t, OWNER_END.base()>, Owner> company_best = {}; // best rating for each company, including OWNER_NONE
4689 TypedIndexContainer<std::array<uint32_t, OWNER_END.base()>, Owner> company_sum = {}; // sum of ratings for each company
4690 uint best_rating = 0;
4691 uint best_sum = 0; // sum of best ratings for each company
4692
4693 for (auto &p : used_stations) {
4694 auto owner = p.first->owner;
4695 auto rating = p.first->goods[cargo].rating;
4696 if (rating > company_best[owner]) {
4697 best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
4698 company_best[owner] = rating;
4699 if (rating > best_rating) best_rating = rating;
4700 }
4701 company_sum[owner] += rating;
4702 }
4703
4704 /* From now we'll calculate with fractional cargo amounts.
4705 * First determine how much cargo we really have. */
4706 amount *= best_rating + 1;
4707
4708 uint moving = 0;
4709 for (auto &p : used_stations) {
4710 Owner owner = p.first->owner;
4711 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4712 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4713 p.second = amount * company_best[owner] * p.first->goods[cargo].rating / best_sum / company_sum[owner];
4714 moving += p.second;
4715 }
4716
4717 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4718 if (amount > moving) {
4719 std::stable_sort(used_stations.begin(), used_stations.end(), [cargo](const StationInfo &a, const StationInfo &b) {
4720 return b.first->goods[cargo].rating < a.first->goods[cargo].rating;
4721 });
4722
4723 assert(amount - moving <= used_stations.size());
4724 for (uint i = 0; i < amount - moving; i++) {
4725 used_stations[i].second++;
4726 }
4727 }
4728
4729 uint moved = 0;
4730 for (auto &p : used_stations) {
4731 moved += UpdateStationWaiting(p.first, cargo, p.second, source);
4732 }
4733
4734 return moved;
4735}
4736
4737void UpdateStationDockingTiles(Station *st)
4738{
4739 st->docking_station.Clear();
4740
4741 /* For neutral stations, start with the industry area instead of dock area */
4742 const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4743
4744 if (area->tile == INVALID_TILE) return;
4745
4746 int x = TileX(area->tile);
4747 int y = TileY(area->tile);
4748
4749 /* Expand the area by a tile on each side while
4750 * making sure that we remain inside the map. */
4751 int x2 = std::min<int>(x + area->w + 1, Map::SizeX());
4752 int x1 = std::max<int>(x - 1, 0);
4753
4754 int y2 = std::min<int>(y + area->h + 1, Map::SizeY());
4755 int y1 = std::max<int>(y - 1, 0);
4756
4757 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4758 for (TileIndex tile : ta) {
4759 if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4760 }
4761}
4762
4763void BuildOilRig(TileIndex tile)
4764{
4765 if (!Station::CanAllocateItem()) {
4766 Debug(Facility::Misc, Severity::Critical, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4767 return;
4768 }
4769
4770 Station *st = Station::Create(tile);
4771 _station_kdtree.Insert(st->index);
4772 st->town = ClosestTownFromTile(tile, UINT_MAX);
4773
4775
4776 assert(IsTileType(tile, TileType::Industry));
4777 /* Mark industry as associated both ways */
4778 st->industry = Industry::GetByTile(tile);
4779 st->industry->neutral_station = st;
4780 DeleteAnimatedTile(tile);
4781 MakeOilrig(tile, st->index, GetWaterClass(tile));
4782
4783 st->owner = OWNER_NONE;
4784 st->airport.type = AT_OILRIG;
4786 st->airport.Add(tile);
4787 st->ship_station.Add(tile);
4790 UpdateStationDockingTiles(st);
4791
4792 st->spread.Add(tile);
4793
4794 st->UpdateVirtCoord();
4795
4796 /* An industry tile has now been replaced with a station tile, this may change the overlap between station catchments and industry tiles.
4797 * Recalculate the station catchment for all stations currently in the industry's nearby list.
4798 * Clear the industry's station nearby list first because Station::RecomputeCatchment cannot remove nearby industries in this case. */
4800 StationList nearby = std::move(st->industry->stations_near);
4801 st->industry->stations_near.clear();
4802 for (Station *near : nearby) {
4803 near->RecomputeCatchment(true);
4804 UpdateStationAcceptance(near, true);
4805 }
4806 }
4807
4808 st->RecomputeCatchment();
4809 UpdateStationAcceptance(st, false);
4810}
4811
4812void DeleteOilRig(TileIndex tile)
4813{
4814 Station *st = Station::GetByTile(tile);
4815
4816 MakeWaterKeepingClass(tile, OWNER_NONE);
4817
4818 /* The oil rig station is not supposed to be shared with anything else */
4819 [[maybe_unused]] static constexpr StationFacilities expected_facility{StationFacility::Airport, StationFacility::Dock};
4820 assert(st->facilities == expected_facility && st->airport.type == AT_OILRIG);
4821 if (st->industry != nullptr && st->industry->neutral_station == st) {
4822 /* Don't leave dangling neutral station pointer */
4823 st->industry->neutral_station = nullptr;
4824 }
4825 delete st;
4826}
4827
4829static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4830{
4831 if (IsAnyRoadStopTile(tile)) {
4832 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
4833 /* Update all roadtypes, no matter if they are present */
4834 if (GetRoadOwner(tile, rtt) == old_owner) {
4835 RoadType rt = GetRoadType(tile, rtt);
4836 if (rt != INVALID_ROADTYPE) {
4837 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4838 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4839 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4840 }
4841 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4842 }
4843 }
4844 }
4845
4846 if (!IsTileOwner(tile, old_owner)) return;
4847
4848 if (new_owner != INVALID_OWNER) {
4849 /* Update company infrastructure counts. Only do it here
4850 * if the new owner is valid as otherwise the clear
4851 * command will do it for us. No need to dirty windows
4852 * here, we'll redraw the whole screen anyway.*/
4853 Company *old_company = Company::Get(old_owner);
4854 Company *new_company = Company::Get(new_owner);
4855
4856 /* Update counts for underlying infrastructure. */
4857 switch (GetStationType(tile)) {
4858 case StationType::Rail:
4860 if (!IsStationTileBlocked(tile)) {
4861 old_company->infrastructure.rail[GetRailType(tile)]--;
4862 new_company->infrastructure.rail[GetRailType(tile)]++;
4863 }
4864 break;
4865
4866 case StationType::Bus:
4867 case StationType::Truck:
4869 /* Road stops were already handled above. */
4870 break;
4871
4872 case StationType::Buoy:
4873 case StationType::Dock:
4874 if (GetWaterClass(tile) == WaterClass::Canal) {
4875 old_company->infrastructure.water--;
4876 new_company->infrastructure.water++;
4877 }
4878 break;
4879
4880 default:
4881 break;
4882 }
4883
4884 /* Update station tile count. */
4885 if (!IsBuoy(tile) && !IsAirport(tile)) {
4886 old_company->infrastructure.station--;
4887 new_company->infrastructure.station++;
4888 }
4889
4890 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4891 SetTileOwner(tile, new_owner);
4892 InvalidateWindowClassesData(WindowClass::StationList, 0);
4893 } else {
4894 if (IsDriveThroughStopTile(tile)) {
4895 /* Remove the drive-through road stop */
4896 if (IsRoadWaypoint(tile)) {
4897 Command<Commands::RemoveFromRoadWaypoint>::Do({DoCommandFlag::Execute, DoCommandFlag::Bankrupt}, tile, tile);
4898 } else {
4899 Command<Commands::RemoveRoadStop>::Do({DoCommandFlag::Execute, DoCommandFlag::Bankrupt}, tile, 1, 1, (GetStationType(tile) == StationType::Truck) ? RoadStopType::Truck : RoadStopType::Bus, false);
4900 }
4901 assert(IsTileType(tile, TileType::Road));
4902 /* Change owner of tile and all roadtypes */
4903 ChangeTileOwner(tile, old_owner, new_owner);
4904 } else {
4905 Command<Commands::LandscapeClear>::Do({DoCommandFlag::Execute, DoCommandFlag::Bankrupt}, tile);
4906 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4907 * Update owner of buoy if it was not removed (was in orders).
4908 * Do not update when owned by OWNER_WATER (sea and rivers). */
4909 if ((IsTileType(tile, TileType::Water) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4910 }
4911 }
4912}
4913
4923{
4924 /* Water flooding can always clear road stops. */
4925 if (_current_company == OWNER_WATER) return CommandCost();
4926
4927 CommandCost ret;
4928
4929 if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4930 Owner tram_owner = GetRoadOwner(tile, RoadTramType::Tram);
4931 if (tram_owner != OWNER_NONE) {
4932 ret = CheckOwnership(tram_owner);
4933 if (ret.Failed()) return ret;
4934 }
4935 }
4936
4937 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4938 Owner road_owner = GetRoadOwner(tile, RoadTramType::Road);
4939 if (road_owner == OWNER_TOWN) {
4941 if (ret.Failed()) return ret;
4942 } else if (road_owner != OWNER_NONE) {
4943 ret = CheckOwnership(road_owner);
4944 if (ret.Failed()) return ret;
4945 }
4946 }
4947
4948 return CommandCost();
4949}
4950
4953{
4954 if (flags.Test(DoCommandFlag::Auto)) {
4955 switch (GetStationType(tile)) {
4956 default: break;
4957 case StationType::Rail: return CommandCost(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4958 case StationType::RailWaypoint: return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4959 case StationType::Airport: return CommandCost(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4960 case StationType::Truck: return CommandCost(HasTileRoadType(tile, RoadTramType::Tram) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4961 case StationType::Bus: return CommandCost(HasTileRoadType(tile, RoadTramType::Tram) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4962 case StationType::RoadWaypoint: return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4963 case StationType::Buoy: return CommandCost(STR_ERROR_BUOY_IN_THE_WAY);
4964 case StationType::Dock: return CommandCost(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4966 return CommandCostWithParam(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY, STR_INDUSTRY_NAME_OIL_RIG);
4967 }
4968 }
4969
4970 switch (GetStationType(tile)) {
4971 case StationType::Rail: return RemoveRailStation(tile, flags);
4972 case StationType::RailWaypoint: return RemoveRailWaypoint(tile, flags);
4973 case StationType::Airport: return RemoveAirport(tile, flags);
4974 case StationType::Truck: [[fallthrough]];
4975 case StationType::Bus:
4976 if (IsDriveThroughStopTile(tile)) {
4977 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4978 if (remove_road.Failed()) return remove_road;
4979 }
4980 return RemoveRoadStop(tile, flags);
4982 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4983 if (remove_road.Failed()) return remove_road;
4984 return RemoveRoadWaypointStop(tile, flags);
4985 }
4986 case StationType::Buoy: return RemoveBuoy(tile, flags);
4987 case StationType::Dock: return RemoveDock(tile, flags);
4988 default: break;
4989 }
4990
4991 return CMD_ERROR;
4992}
4993
4995static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlags flags, int z_new, Slope tileh_new)
4996{
4997 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4998 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4999 * TTDP does not call it.
5000 */
5001 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
5002 switch (GetStationType(tile)) {
5004 case StationType::Rail: {
5005 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetRailStationAxis(tile))) break;
5007 }
5008
5011
5012 case StationType::Truck:
5013 case StationType::Bus:
5015 if (IsDriveThroughStopTile(tile)) {
5016 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetDriveThroughStopAxis(tile))) break;
5017 } else {
5018 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetBayRoadStopDir(tile))) break;
5019 }
5021 }
5022
5023 default: break;
5024 }
5025 }
5026 }
5027 return Command<Commands::LandscapeClear>::Do(flags, tile);
5028}
5029
5035uint FlowStat::GetShare(StationID st) const
5036{
5037 uint32_t prev = 0;
5038 for (const auto &it : this->shares) {
5039 if (it.second == st) {
5040 return it.first - prev;
5041 } else {
5042 prev = it.first;
5043 }
5044 }
5045 return 0;
5046}
5047
5054StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
5055{
5056 if (this->unrestricted == 0) return StationID::Invalid();
5057 assert(!this->shares.empty());
5058 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
5059 assert(it != this->shares.end() && it->first <= this->unrestricted);
5060 if (it->second != excluded && it->second != excluded2) return it->second;
5061
5062 /* We've hit one of the excluded stations.
5063 * Draw another share, from outside its range. */
5064
5065 uint end = it->first;
5066 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
5067 uint interval = end - begin;
5068 if (interval >= this->unrestricted) return StationID::Invalid(); // Only one station in the map.
5069 uint new_max = this->unrestricted - interval;
5070 uint rand = RandomRange(new_max);
5071 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
5072 this->shares.upper_bound(rand + interval);
5073 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
5074 if (it2->second != excluded && it2->second != excluded2) return it2->second;
5075
5076 /* We've hit the second excluded station.
5077 * Same as before, only a bit more complicated. */
5078
5079 uint end2 = it2->first;
5080 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
5081 uint interval2 = end2 - begin2;
5082 if (interval2 >= new_max) return StationID::Invalid(); // Only the two excluded stations in the map.
5083 new_max -= interval2;
5084 if (begin > begin2) {
5085 std::swap(begin, begin2);
5086 std::swap(end, end2);
5087 std::swap(interval, interval2);
5088 }
5089 rand = RandomRange(new_max);
5090 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
5091 if (rand < begin) {
5092 it3 = this->shares.upper_bound(rand);
5093 } else if (rand < begin2 - interval) {
5094 it3 = this->shares.upper_bound(rand + interval);
5095 } else {
5096 it3 = this->shares.upper_bound(rand + interval + interval2);
5097 }
5098 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
5099 return it3->second;
5100}
5101
5108{
5109 assert(!this->shares.empty());
5110 SharesMap new_shares;
5111 uint i = 0;
5112 for (const auto &it : this->shares) {
5113 new_shares[++i] = it.second;
5114 if (it.first == this->unrestricted) this->unrestricted = i;
5115 }
5116 this->shares.swap(new_shares);
5117 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
5118}
5119
5126void FlowStat::ChangeShare(StationID st, int flow)
5127{
5128 /* We assert only before changing as afterwards the shares can actually
5129 * be empty. In that case the whole flow stat must be deleted then. */
5130 assert(!this->shares.empty());
5131
5132 uint removed_shares = 0;
5133 uint added_shares = 0;
5134 uint last_share = 0;
5135 SharesMap new_shares;
5136 for (const auto &it : this->shares) {
5137 if (it.second == st) {
5138 if (flow < 0) {
5139 uint share = it.first - last_share;
5140 if (flow == INT_MIN || (uint)(-flow) >= share) {
5141 removed_shares += share;
5142 if (it.first <= this->unrestricted) this->unrestricted -= share;
5143 if (flow != INT_MIN) flow += share;
5144 last_share = it.first;
5145 continue; // remove the whole share
5146 }
5147 removed_shares += (uint)(-flow);
5148 } else {
5149 added_shares += (uint)(flow);
5150 }
5151 if (it.first <= this->unrestricted) this->unrestricted += flow;
5152
5153 /* If we don't continue above the whole flow has been added or
5154 * removed. */
5155 flow = 0;
5156 }
5157 new_shares[it.first + added_shares - removed_shares] = it.second;
5158 last_share = it.first;
5159 }
5160 if (flow > 0) {
5161 new_shares[last_share + (uint)flow] = st;
5162 if (this->unrestricted < last_share) {
5163 this->ReleaseShare(st);
5164 } else {
5165 this->unrestricted += flow;
5166 }
5167 }
5168 this->shares.swap(new_shares);
5169}
5170
5176void FlowStat::RestrictShare(StationID st)
5177{
5178 assert(!this->shares.empty());
5179 uint flow = 0;
5180 uint last_share = 0;
5181 SharesMap new_shares;
5182 for (auto &it : this->shares) {
5183 if (flow == 0) {
5184 if (it.first > this->unrestricted) return; // Not present or already restricted.
5185 if (it.second == st) {
5186 flow = it.first - last_share;
5187 this->unrestricted -= flow;
5188 } else {
5189 new_shares[it.first] = it.second;
5190 }
5191 } else {
5192 new_shares[it.first - flow] = it.second;
5193 }
5194 last_share = it.first;
5195 }
5196 if (flow == 0) return;
5197 new_shares[last_share + flow] = st;
5198 this->shares.swap(new_shares);
5199 assert(!this->shares.empty());
5200}
5201
5207void FlowStat::ReleaseShare(StationID st)
5208{
5209 assert(!this->shares.empty());
5210 uint flow = 0;
5211 uint next_share = 0;
5212 bool found = false;
5213 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
5214 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
5215 if (found) {
5216 flow = next_share - it->first;
5217 this->unrestricted += flow;
5218 break;
5219 } else {
5220 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
5221 if (it->second == st) found = true;
5222 }
5223 next_share = it->first;
5224 }
5225 if (flow == 0) return;
5226 SharesMap new_shares;
5227 new_shares[flow] = st;
5228 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
5229 if (it->second != st) {
5230 new_shares[flow + it->first] = it->second;
5231 } else {
5232 flow = 0;
5233 }
5234 }
5235 this->shares.swap(new_shares);
5236 assert(!this->shares.empty());
5237}
5238
5245{
5246 assert(runtime > 0);
5247 SharesMap new_shares;
5248 uint share = 0;
5249 for (auto i : this->shares) {
5250 share = std::max(share + 1, i.first * 30 / runtime);
5251 new_shares[share] = i.second;
5252 if (this->unrestricted == i.first) this->unrestricted = share;
5253 }
5254 this->shares.swap(new_shares);
5255}
5256
5263void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
5264{
5265 FlowStatMap::iterator origin_it = this->find(origin);
5266 if (origin_it == this->end()) {
5267 this->emplace(origin, FlowStat(via, flow));
5268 } else {
5269 origin_it->second.ChangeShare(via, flow);
5270 assert(!origin_it->second.GetShares()->empty());
5271 }
5272}
5273
5282void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
5283{
5284 FlowStatMap::iterator prev_it = this->find(origin);
5285 if (prev_it == this->end()) {
5286 FlowStat fs(via, flow);
5287 fs.AppendShare(StationID::Invalid(), flow);
5288 this->emplace(origin, fs);
5289 } else {
5290 prev_it->second.ChangeShare(via, flow);
5291 prev_it->second.ChangeShare(StationID::Invalid(), flow);
5292 assert(!prev_it->second.GetShares()->empty());
5293 }
5294}
5295
5301{
5302 for (auto &i : *this) {
5303 FlowStat &fs = i.second;
5304 uint local = fs.GetShare(StationID::Invalid());
5305 if (local > INT_MAX) { // make sure it fits in an int
5306 fs.ChangeShare(self, -INT_MAX);
5307 fs.ChangeShare(StationID::Invalid(), -INT_MAX);
5308 local -= INT_MAX;
5309 }
5310 fs.ChangeShare(self, -(int)local);
5311 fs.ChangeShare(StationID::Invalid(), -(int)local);
5312
5313 /* If the local share is used up there must be a share for some
5314 * remote station. */
5315 assert(!fs.GetShares()->empty());
5316 }
5317}
5318
5325std::vector<StationID> FlowStatMap::DeleteFlows(StationID via)
5326{
5327 std::vector<StationID> ret;
5328 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
5329 FlowStat &s_flows = f_it->second;
5330 s_flows.ChangeShare(via, INT_MIN);
5331 if (s_flows.GetShares()->empty()) {
5332 ret.push_back(f_it->first);
5333 this->erase(f_it++);
5334 } else {
5335 ++f_it;
5336 }
5337 }
5338 return ret;
5339}
5340
5346{
5347 for (auto &it : *this) {
5348 it.second.RestrictShare(via);
5349 }
5350}
5351
5356void FlowStatMap::ReleaseFlows(StationID via)
5357{
5358 for (auto &it : *this) {
5359 it.second.ReleaseShare(via);
5360 }
5361}
5362
5368{
5369 uint ret = 0;
5370 for (const auto &it : *this) {
5371 ret += (--(it.second.GetShares()->end()))->first;
5372 }
5373 return ret;
5374}
5375
5381uint FlowStatMap::GetFlowVia(StationID via) const
5382{
5383 uint ret = 0;
5384 for (const auto &it : *this) {
5385 ret += it.second.GetShare(via);
5386 }
5387 return ret;
5388}
5389
5395uint FlowStatMap::GetFlowFrom(StationID from) const
5396{
5397 FlowStatMap::const_iterator i = this->find(from);
5398 if (i == this->end()) return 0;
5399 return (--(i->second.GetShares()->end()))->first;
5400}
5401
5408uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
5409{
5410 FlowStatMap::const_iterator i = this->find(from);
5411 if (i == this->end()) return 0;
5412 return i->second.GetShare(via);
5413}
5414
5416static CommandCost CheckBuildAbove_Station(TileIndex tile, [[maybe_unused]] DoCommandFlags flags, [[maybe_unused]] Axis axis, int height)
5417{
5418 StationType type = GetStationType(tile);
5419 auto bridgeable_info = GetStationBridgeableTileInfo(type);
5420
5421 switch (type) {
5422 case StationType::Rail:
5424 if (const StationSpec *spec = GetStationSpec(tile); spec != nullptr) bridgeable_info = spec->bridgeable_info;
5425 break;
5426
5427 case StationType::Bus:
5428 case StationType::Truck:
5430 if (const RoadStopSpec *spec = GetRoadStopSpec(tile); spec != nullptr) bridgeable_info = spec->bridgeable_info;
5431 break;
5432
5433 default: break;
5434 }
5435
5436 return IsStationBridgeAboveOk(tile, bridgeable_info, type, GetStationGfx(tile), height);
5437}
5438
5440extern const TileTypeProcs _tile_type_station_procs = {
5441 .draw_tile_proc = DrawTile_Station,
5442 .get_slope_pixel_z_proc = [](TileIndex tile, uint, uint, bool) { return GetTileMaxPixelZ(tile); },
5443 .clear_tile_proc = ClearTile_Station,
5444 .get_tile_desc_proc = GetTileDesc_Station,
5445 .get_tile_track_status_proc = GetTileTrackStatus_Station,
5446 .click_tile_proc = ClickTile_Station,
5447 .animate_tile_proc = AnimateTile_Station,
5448 .tile_loop_proc = TileLoop_Station,
5449 .change_tile_owner_proc = ChangeTileOwner_Station,
5450 .vehicle_enter_tile_proc = VehicleEnterTile_Station,
5451 .get_foundation_proc = [](TileIndex, Slope tileh) { return FlatteningFoundation(tileh); },
5452 .terraform_tile_proc = TerraformTile_Station,
5453 .check_build_above_proc = CheckBuildAbove_Station,
5454};
Base for aircraft.
void UpdateAirplanesOnNewStation(const Station *st)
Updates the status of the Aircraft heading or in the station.
const AirportFTAClass * GetAirport(const uint8_t airport_type)
Get the finite state machine of an airport type.
Definition airport.cpp:188
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition airport.h:25
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition airport.h:24
@ AirportClosed
Dummy block for indicating a closed airport.
Definition airport.h:131
@ FLYING
Vehicle is flying in the air.
Definition airport.h:78
@ NUM_AIRPORTS
Maximal number of airports in total.
Definition airport.h:41
@ AT_OILRIG
Oilrig airport.
Definition airport.h:38
Enum of the default airport tiles.
void AddAnimatedTile(TileIndex tile, bool mark_dirty)
Add the given tile to the animated tile table (if it does not exist yet).
void DeleteAnimatedTile(TileIndex tile, bool immediate)
Stops animation on the given tile.
Tile animation!
Functions related to autoslope.
bool AutoslopeCheckForAxis(TileIndex tile, int z_new, Slope tileh_new, Axis axis)
Autoslope check for tiles with something built along an axis.
Definition autoslope.h:51
bool AutoslopeCheckForEntranceEdge(TileIndex tile, int z_new, Slope tileh_new, DiagDirection entrance)
Autoslope check for tiles with an entrance on an edge.
Definition autoslope.h:31
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition autoslope.h:65
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Header file for bridges.
void DrawBridgeMiddle(const TileInfo *ti, BridgePillarFlags blocked_pillars)
Draw the middle bits of a bridge.
TileIndex GetSouthernBridgeEnd(TileIndex t)
Finds the southern end of a bridge starting at a middle tile.
int GetBridgeHeight(TileIndex t)
Get the height ('z') of a bridge.
Map accessor functions for bridges.
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition bridge_map.h:45
EnumBitSet< BridgePillarFlag, uint8_t > BridgePillarFlags
Bitset of BridgePillarFlag elements.
Definition bridge_type.h:53
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
static constexpr CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:77
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
@ Passengers
Passengers.
Definition cargotype.h:50
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does a given cargo have any cargo class from cc.
Definition cargotype.h:288
Cheats _cheats
All the cheats.
Definition cheat.cpp:16
Types related to cheating.
Iterator to iterate over all tiles belonging to an airport.
Iterator to iterate over all tiles belonging to an airport spec.
AirportGfx GetAirportGfx() const
Get the AirportGfx for the current tile.
uint Count() const
Count the number of set bits.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Tstorage base() const noexcept
Retrieve the raw value behind this bit set.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Flip()
Flip all bits.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
Iterate a range of enum values.
Flat set implementation that uses a sorted vector for storage.
std::pair< const_iterator, bool > insert(const Tkey &key)
Insert a key into the set, if it does not already exist.
uint GetFlow() const
Get the sum of all flows from this FlowStatMap.
void PassOnFlow(StationID origin, StationID via, uint amount)
Pass on some flow, remembering it as invalid, for later subtraction from locally consumed flow.
std::vector< StationID > DeleteFlows(StationID via)
Delete all flows at a station for specific cargo and destination.
void AddFlow(StationID origin, StationID via, uint amount)
Add some flow from "origin", going via "via".
uint GetFlowFrom(StationID from) const
Get the sum of flows from a specific station from this FlowStatMap.
void FinalizeLocalConsumption(StationID self)
Subtract invalid flows from locally consumed flow.
void ReleaseFlows(StationID via)
Release all flows at a station for specific cargo and destination.
uint GetFlowFromVia(StationID from, StationID via) const
Get the flow from a specific station via a specific other station.
uint GetFlowVia(StationID via) const
Get the sum of flows via a specific station from this FlowStatMap.
void RestrictFlows(StationID via)
Restrict all flows at a station for specific cargo and destination.
Flow statistics telling how much flow should be sent along a link.
static const SharesMap empty_sharesmap
Static instance of FlowStat::SharesMap.
void ScaleToMonthly(uint runtime)
Scale all shares from link graph's runtime to monthly values.
void RestrictShare(StationID st)
Restrict a flow by moving it to the end of the map and decreasing the amount of unrestricted flow.
uint GetShare(StationID st) const
Get flow for a station.
StationID GetVia() const
Get a station a package can be routed to.
const SharesMap * GetShares() const
Get the actual shares as a const pointer so that they can be iterated over.
SharesMap shares
Shares of flow to be sent via specified station (or consumed locally).
void ReleaseShare(StationID st)
Release ("unrestrict") a flow by moving it to the begin of the map and increasing the amount of unres...
void ChangeShare(StationID st, int flow)
Change share for specified station.
void AppendShare(StationID st, uint flow, bool restricted=false)
Add some flow to the end of the shares map.
void Invalidate()
Reduce all flows to minimum capacity so that they don't get in the way of link usage statistics too m...
uint unrestricted
Limit for unrestricted shares.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
void Insert(const T &element)
Insert a single element in the tree.
Definition kdtree.hpp:452
static LinkGraphSchedule instance
Static instance of LinkGraphSchedule.
void Queue(LinkGraph *lg)
Queue a link graph for execution.
A connected component of a link graph.
Definition linkgraph.h:35
void Merge(LinkGraph *other)
Merge a link graph with another one.
Definition linkgraph.cpp:91
TimerGameEconomy::Date LastCompression() const
Get date of last compression.
Definition linkgraph.h:249
NodeID AddNode(const Station *st)
Add a node to the component and create empty edges associated with it.
NodeID Size() const
Get the current size of the component.
Definition linkgraph.h:243
static const uint MIN_TIMEOUT_DISTANCE
Minimum effective distance for timeout calculation.
Definition linkgraph.h:183
static constexpr TimerGameEconomy::Date STALE_LINK_DEPOT_TIMEOUT
Number of days before deleting links served only by vehicles stopped in depot.
Definition linkgraph.h:186
static constexpr TimerGameEconomy::Date COMPRESSION_INTERVAL
Minimum number of days between subsequent compressions of a LG.
Definition linkgraph.h:189
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
Definition refresh.cpp:26
const Tspec * GetSpec(uint index) const
Get a spec from the class at a given index.
uint GetSpecCount() const
Get the number of allocated specs within the class.
static NewGRFClass * Get(StationClassID class_index)
StringID name
Name of this class.
bool Contains(TileIndex tile) const
Does this tile area contain a tile?
uint16_t w
The width of the area.
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
void Clear()
Clears the 'tile area', i.e.
TileIndex tile
The base tile of the area.
bool IsEmpty() const
Test if this tile area is empty.
uint16_t h
The height of the area.
OrthogonalTileArea & Expand(int rad)
Expand a tile area by rad tiles in each direction, keeping within map bounds.
const RailStationTileLayout & stl
Station tile layout being iterated.
uint position
Position within iterator.
StationGfx operator*() const
Dereference operator.
uint length
Length of platforms.
std::span< const StationGfx > layout
Predefined tile layout.
This struct contains all the info that is needed to draw and construct tracks.
Definition rail.h:134
SpriteID single_x
single piece of rail in X direction, without ground
Definition rail.h:144
uint16_t max_speed
Maximum speed for vehicles travelling on this rail type.
Definition rail.h:239
struct RailTypeInfo::@157247141350136173143103254227157213063052244122 strings
Strings associated with the rail type.
SpriteID single_y
single piece of rail in Y direction, without ground
Definition rail.h:145
StringID name
Name of this rail type.
Definition rail.h:184
uint8_t fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition rail.h:209
uint GetRailtypeSpriteOffset() const
Offset between the current railtype and normal rail.
Definition rail.h:306
struct RailTypeInfo::@332027037331076264023214171276243307073252216167 base_sprites
Struct containing the main sprites.
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition road.h:118
struct RoadTypeInfo::@070000167274302256150317022075324310363002361255 strings
Strings associated with the rail type.
StringID name
Name of this rail type.
Definition road.h:79
Generate TileIndices around a center tile or tile area, with increasing distance.
Add dynamic register values to a sprite layout.
DrawTileSpriteSpan GetLayout() const
Returns the result spritelayout after preprocessing.
uint TotalCount() const
Returns total count of cargo at the station, including cargo which is already reserved for loading.
uint Reroute(uint max_move, StationCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge)
Routes packets with station "avoid" as next hop to a different place.
void Append(CargoPacket *cp, StationID next)
Appends the given cargo packet to the range of packets with the same next station.
uint Truncate(uint max_move=UINT_MAX, StationCargoAmountMap *cargo_per_source=nullptr)
Truncates where each destination loses roughly the same percentage of its cargo.
const StationList & GetStations()
Run a tile loop to find stations around a tile, on demand.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static constexpr TimerGameTick::Ticks STATION_LINKGRAPH_TICKS
Cycle duration for cleaning dead links.
static constexpr TimerGameTick::Ticks STATION_ACCEPTANCE_TICKS
Cycle duration for updating station acceptance.
static constexpr TimerGameTick::Ticks STATION_RATING_TICKS
Cycle duration for updating station rating.
Tile iterator wrapper.
Wrapper class to abstract away the way the tiles are stored.
Definition map_func.h:25
static Date date
Current date in days (day counter).
static constexpr TimerGame< struct Economy >::Date INVALID_DATE
static Date date
Current date in days (day counter).
static Month month
Current month (0..11).
static TickCounter counter
Monotonic counter, in ticks, since start of game.
StrongType::Typedef< int32_t, DateTag< struct Economy >, StrongType::Compare, StrongType::Integer > Date
Iterate over all vehicles on a tile.
void DrawClearLandTile(const TileInfo *ti, uint8_t density)
Draw a ClearGround::Grass tile.
Definition clear_cmd.cpp:70
Functions related to clear (TileType::Clear) land.
CommandCost CommandCostWithParam(StringID str, uint64_t value)
Return an error status, with string and parameter.
Definition command.cpp:415
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Auto
don't allow building on structures
@ Execute
execute the given command
@ Bankrupt
company bankrupts, skip money check, skip vehicle on tile check in some cases
Commands
List of commands.
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
Definition of stuff that is very close to a company, like the company struct itself.
PaletteID GetCompanyPalette(CompanyID company)
Get the palette for recolouring with a company colour.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
void DirtyCompanyInfrastructureWindows(CompanyID company)
Redraw all windows with company infrastructure counts.
GUI Functions related to companies.
static constexpr Owner OWNER_END
Last + 1 owner.
static constexpr Owner OWNER_TOWN
A town owns the tile, or a town is expanding.
static constexpr Owner OWNER_NONE
The tile has no ownership.
static constexpr Owner INVALID_OWNER
An invalid owner.
static constexpr Owner OWNER_WATER
The tile/execution is done by "water".
Some simple functions to help with accessing containers.
bool include(Container &container, typename Container::const_reference &item)
Helper function to append an item to a container if it is not already contained.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
bool CanBuildDepotByTileh(DiagDirection direction, Slope tileh)
Find out if the slope of the tile is suitable to build a depot of given direction.
Definition depot_func.h:27
void ShowDepotWindow(TileIndex tile, VehicleType type)
Opens a depot window.
bool IsValidAxis(Axis d)
Checks if an integer value is a valid Axis.
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
DiagDirections AxisToDiagDirs(Axis a)
Converts an Axis to DiagDirections.
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
Axis OtherAxis(Axis a)
Select the other axis as provided.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
EnumIndexArray< T, DiagDirection, DiagDirection::End > DiagDirectionIndexArray
Array with DiagDirection as index.
Direction
Defines the 8 directions on the map.
Axis
Enumeration for the two axis X and Y.
@ X
The X axis.
DiagDirection
Enumeration for diagonal directions.
@ Invalid
Flag for an invalid DiagDirection.
@ SW
Southwest.
@ End
Used for iterations.
@ SE
Southeast.
EnumBitSet< DiagDirection, uint8_t > DiagDirections
Bitset of DiagDirection elements.
Prices _price
Prices and also the fractional part.
Definition economy.cpp:94
static const uint ROAD_STOP_TRACKBIT_FACTOR
Multiplier for how many regular track bits a bay stop counts.
@ Construction
Construction costs.
Price
Enumeration of all base prices for use with Prices.
@ BuildStationTruck
Price for building lorry stations.
@ ClearStationBus
Price for destroying bus stops.
@ BuildStationBus
Price for building bus stops.
@ ClearStationAirport
Price for destroying airports.
@ ClearStationTruck
Price for destroying lorry stations.
@ BuildStationAirport
Price for building airports.
@ ClearStationDock
Price for destroying docks.
@ ClearStationRail
Price for destroying rail stations.
@ BuildStationRailLength
Additional price for building rail stations dependent on their length.
@ BuildFoundation
Price for building foundation under other constructions e.g. roads, rails, depots,...
@ BuildStationRail
Price for building rail stations.
@ BuildStationDock
Price for building docks.
@ ClearWaypointRail
Price for destroying rail waypoints.
@ ClearRail
Price for destroying rails.
void DrawRailCatenary(const TileInfo *ti)
Draws overhead wires and pylons for electric railways.
Definition elrail.cpp:554
Header file for electrified rail specific functions.
bool HasRailCatenaryDrawn(RailType rt)
Test if we should draw rail catenary.
Definition elrail_func.h:32
#define T
Climate temperate.
Definition engines.h:91
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Flat set container implementation.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Definition station.cpp:250
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
static const SpriteID SPR_RAIL_TRACK_Y
Definition sprites.h:449
static const SpriteID SPR_MONO_TRACK_X_SNOW
Definition sprites.h:496
static const SpriteID SPR_MGLV_TRACK_Y_SNOW
Definition sprites.h:508
static const SpriteID SPR_MONO_TRACK_Y
Definition sprites.h:491
static const SpriteID SPR_MONO_TRACK_Y_SNOW
Definition sprites.h:495
static const SpriteID SPR_MONO_TRACK_X
Definition sprites.h:492
static const SpriteID SPR_RAIL_TRACK_X_SNOW
Definition sprites.h:454
static const SpriteID SPR_MGLV_TRACK_X
Definition sprites.h:506
static const SpriteID SPR_RAIL_TRACK_Y_SNOW
Definition sprites.h:453
static const SpriteID SPR_MGLV_TRACK_X_SNOW
Definition sprites.h:509
static const SpriteID SPR_MGLV_TRACK_Y
Definition sprites.h:505
static const SpriteID SPR_RAIL_TRACK_X
Definition sprites.h:450
void UpdateValidHistory(ValidHistoryMask &valid_history, const HistoryRange &hr, uint cur_month)
Update mask of valid records for a historical data.
Definition history.cpp:25
Functions for storing historical data.
T GetAndResetAccumulatedAverage(Taccrued &total)
Get an average value for the previous month, as reset for the next month.
void RotateHistory(HistoryData< T > &history, ValidHistoryMask valid_history, const HistoryRange &hr, uint cur_month)
Rotate historical data.
uint16_t RxCompress(uint32_t num)
Compress unsigned integer into 16 bits, in a way that increases dynamic range at the expense of preci...
uint32_t RxDecompress(uint16_t num)
Decompress a range-compressed integer.
HouseZone
Concentric rings of zoning around the centre of a town.
Definition house.h:59
@ TownEdge
Edge of the town; roads without pavement.
Definition house.h:60
Base of all industries.
bool IsTileForestIndustry(TileIndex tile)
Check whether the tile is a forest.
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
IndustryType GetIndustryType(Tile tile)
Retrieve the type for this industry.
IndustryID GetIndustryIndex(Tile t)
Get the industry ID of the given tile.
static const IndustryType NUM_INDUSTRYTYPES
total number of industry types, new and old; limited to 240 because we need some special ids like IT_...
@ Extractive
Like mines.
const TileTypeProcs _tile_type_station_procs
TileTypeProcs definitions for TileType::Station tiles.
Definition landscape.cpp:59
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
uint GetFoundationSpriteBlock(TileIndex tile)
Get the sprite block to use for a foundation.
uint ApplyPixelFoundationToSlope(Foundation f, Slope &s)
Applies a foundation to a slope.
Definition landscape.h:128
Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition landscape.h:97
Command definitions related to landscape (slopes etc.).
@ Arctic
Landscape with snow levels.
@ Tropic
Landscape with distinct rainforests and deserts,.
Some typedefs for the main game.
EnumBitSet< EdgeUpdateMode, uint8_t > EdgeUpdateModes
Bitset of EdgeUpdateMode elements.
@ Increase
Increase capacity.
@ Manual
Manual distribution. No link graph calculations are run.
#define Point
Macro that prevents name conflicts between included headers.
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition map.cpp:228
uint DistanceMax(TileIndex t0, TileIndex t1)
Gets the biggest distance component (x or y) between the two given tiles.
Definition map.cpp:200
TileIndex TileAddWrap(TileIndex tile, int addx, int addy)
This function checks if we add addx/addy to tile, if we do wrap around the edges.
Definition map.cpp:119
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:168
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition map_func.h:444
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition map_func.h:392
TileIndexDiff TileOffsByAxis(Axis axis)
Convert an Axis to a TileIndexDiff.
Definition map_func.h:559
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:376
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:574
int32_t TileIndexDiff
An offset value between two tiles.
Definition map_type.h:23
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr uint ToPercent8(uint i)
Converts a "fract" value 0..255 to "percent" value 0..100.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
@ Buoy
Buoy without underlying water.
Definition newgrf.h:39
@ RoadStops
Road stops feature.
Definition newgrf.h:102
@ Stations
Stations feature.
Definition newgrf.h:86
@ Airports
Airports feature.
Definition newgrf.h:95
@ AirportTiles
Airport tiles feature.
Definition newgrf.h:99
static constexpr AirportGfx AIRPORTGFX_CLEARTILE_SPECIALCHECK
Sentinel marker in airport layout to perform a clear tile check.
StationGfx GetTranslatedAirportTileID(StationGfx gfx)
Do airporttile gfx ID translation for NewGRFs.
NewGRF handling of airport tiles.
@ NoAnimation
There is no animation.
@ DrawTileLayout
Use callback to select a tile layout to use when drawing.
@ Avail
Availability of station in construction window.
@ SlopeCheck
Check slope of new station tiles.
@ StationRatingCalc
custom station rating for this cargo type
@ CBID_STATION_BUILD_TILE_LAYOUT
Called when building a station to customize the tile layout.
@ CBID_STATION_DRAW_TILE_LAYOUT
Choose a tile layout to draw, instead of the standard range.
@ CBID_CARGO_STATION_RATING_CALC
Called to calculate part of a station rating.
@ CBID_STATION_AVAILABILITY
Determine whether a newstation should be made available to build.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
@ Avail
Availability of road stop in construction window.
SpriteID GetCanalSprite(CanalFeature feature, TileIndex tile)
Lookup the base sprite to use for a canal.
Handling of NewGRF canals.
Cargo support for NewGRFs.
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
void ErrorUnknownCallbackResult(GrfID grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
GRFConfig * GetGRFConfig(GrfID grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
@ Any
Use first found.
Functions/types related to NewGRF debugging.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
void TriggerHouseAnimation_WatchedCargoAccepted(TileIndex tile, CargoTypes trigger_cargoes)
Run watched cargo accepted callback for a house.
Functions related to NewGRF houses.
SpriteID GetCustomRailSprite(const RailTypeInfo *rti, TileIndex tile, RailSpriteType rtsg, TileContext context, uint *num_results)
Get the sprite to draw for the given tile.
NewGRF handling of rail types.
void TriggerRoadStopRandomisation(BaseStation *st, TileIndex tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger road stop randomisation.
void DeallocateSpecFromRoadStop(BaseStation *st, uint8_t specindex)
Deallocate a RoadStopSpec from a Station.
std::optional< uint8_t > AllocateSpecToRoadStop(const RoadStopSpec *spec, BaseStation *st)
Allocate a RoadStopSpec to a Station.
void AssignSpecToRoadStop(const RoadStopSpec *spec, BaseStation *st, uint8_t specindex)
Assign a previously allocated RoadStopSpec specindex to a Station.
NewGRF definitions and structures for road stops.
@ Overlay
Drive-through stops: Draw the road overlay, e.g. pavement.
@ WaypGround
Waypoints: Draw the sprite layout ground tile (on top of the road).
@ Road
Bay stops: Draw the road itself.
bool IsWaypointClass(const RoadStopClass &cls)
Test if a RoadStopClass is the waypoint class.
PoolID< uint16_t, struct RoadStopClassIDTag, UINT16_MAX, UINT16_MAX > RoadStopClassID
Class IDs for stations.
EnumBitSet< RoadStopDrawMode, uint8_t > RoadStopDrawModes
Bitset of RoadStopDrawMode elements.
@ ROADSTOPTYPE_FREIGHT
This RoadStop is for freight (truck) stops.
@ ROADSTOPTYPE_ALL
This RoadStop is for both types of station road stops.
@ ROADSTOPTYPE_PASSENGER
This RoadStop is for passenger (bus) stops.
@ NoCatenary
Do not show catenary.
@ DriveThroughOnly
Stop is drive-through only.
@ DrawModeRegister
Read draw mode from register 0x100.
SpriteID GetCustomRoadSprite(const RoadTypeInfo *rti, TileIndex tile, RoadSpriteType rtsg, TileContext context, uint *num_results)
Get the sprite to draw for the given tile.
NewGRF handling of road types.
SpriteID GetCustomStationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint32_t var10)
Resolve sprites for drawing a station tile.
SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint layout, uint edge_info)
Resolve the sprites for custom station foundations.
void AssignSpecToStation(const StationSpec *spec, BaseStation *st, uint8_t specindex)
Assign a previously allocated StationSpec specindex to a Station.
void DeallocateSpecFromStation(BaseStation *st, uint8_t specindex)
Deallocate a StationSpec from a Station.
void TriggerStationRandomisation(BaseStation *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger station randomisation.
CommandCost PerformStationTileSlopeCheck(TileIndex north_tile, TileIndex cur_tile, const StationSpec *statspec, Axis axis, uint8_t plat_len, uint8_t numtracks)
Check the slope of a tile of a new station.
uint32_t GetPlatformInfo(StationGfx gfx, int platforms, int length, int platform, int position, bool centred)
Evaluate a tile's position within a station, and return the result in a bit-stuffed format.
std::optional< uint8_t > AllocateSpecToStation(const StationSpec *spec, BaseStation *st)
Allocate a StationSpec to a Station.
Header file for NewGRF stations.
@ CustomFoundations
Draw custom foundations.
@ SeparateGround
Use different sprite set for ground sprites.
@ ExtendedFoundations
Extended foundation block instead of simple.
NewGRFClass< StationSpec, StationClassID > StationClass
Class containing information relating to station classes.
PoolID< uint16_t, struct StationClassIDTag, UINT16_MAX, UINT16_MAX > StationClassID
Class IDs for stations.
Functions related to news.
void AddNewsItem(EncodedString &&headline, NewsType type, NewsStyle style, NewsFlags flags, NewsReference ref1={}, NewsReference ref2={}, std::unique_ptr< NewsAllocatedData > &&data=nullptr, AdviceType advice_type=AdviceType::Invalid)
Add a new newsitem to be shown.
Definition news_gui.cpp:919
@ Acceptance
A type of cargo is (no longer) accepted.
Definition news_type.h:46
@ Small
Small news item. (Information window with text and viewport).
Definition news_type.h:82
@ InColour
News item is shown in colour (otherwise it is shown in black & white).
Definition news_type.h:93
@ LinkGraph
A game paused due to the link graph schedule lagging.
Definition openttd.h:78
@ Editor
In the scenario editor.
Definition openttd.h:21
@ Menu
In the main menu.
Definition openttd.h:19
Functions related to order backups.
Train * GetTrainForReservation(TileIndex tile, Track track)
Find the train which has reserved a specific path.
Definition pbs.cpp:345
void SetRailStationPlatformReservation(TileIndex start, DiagDirection dir, bool b)
Set the reservation for a complete station platform.
Definition pbs.cpp:57
PBS support routines.
bool ValParamRailType(const RailType rail)
Validate functions for rail building.
Definition rail.cpp:92
@ Ground
Main group of ground images.
Definition rail.h:45
@ Overlay
Images for overlaying track.
Definition rail.h:44
Money RailBuildCost(RailType railtype)
Returns the cost of building the specified railtype.
Definition rail.h:448
bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Definition rail.h:396
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition rail.h:320
RailTrackOffset
Offsets for sprites within an overlay/underlay set.
Definition rail.h:63
@ X
Piece of rail in X direction.
Definition rail.h:64
@ Y
Piece of rail in Y direction.
Definition rail.h:65
Command definitions for rail.
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition rail_map.h:115
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Definition rail_map.h:136
static bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition rail_map.h:60
void MakeRailNormal(Tile t, Owner o, TrackBits b, RailType r)
Make the given tile a normal rail.
Definition rail_map.h:624
TrackBits GetRailReservationTrackBits(Tile t)
Returns the reserved track bits of the tile.
Definition rail_map.h:194
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition rail_map.h:72
RailType
Enumeration for all possible railtypes.
Definition rail_type.h:26
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition rail_type.h:33
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
Declaration of link refreshing utility.
bool ValParamRoadType(RoadType roadtype)
Validate functions for rail building.
Definition road.cpp:164
bool HasPowerOnRoad(RoadType enginetype, RoadType tiletype)
Checks if an engine of the given RoadType got power on a tile with a given RoadType.
Definition road.h:232
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition road.h:217
@ Roadstop
Required: Bay stop surface.
Definition road.h:49
@ Ground
Required: Main group of ground images.
Definition road.h:41
@ Overlay
Optional: Images for overlaying track.
Definition road.h:40
Money RoadBuildCost(RoadType roadtype)
Returns the cost of building the specified roadtype.
Definition road.h:242
void DrawRoadGroundSprites(const TileInfo *ti, RoadBits road, RoadBits tram, const RoadTypeInfo *road_rti, const RoadTypeInfo *tram_rti, Roadside roadside, bool snow_or_desert)
Draw road ground sprites.
void DrawRoadCatenary(const TileInfo *ti)
Draws the catenary for the given tile.
void UpdateCompanyRoadInfrastructure(RoadType rt, Owner o, int count)
Update road infrastructure counts for a company.
Definition road_cmd.cpp:184
CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadTramType rtt, DoCommandFlags flags, bool town_check)
Is it allowed to remove the given road bits from the given tile?
Definition road_cmd.cpp:256
void DrawRoadOverlays(const TileInfo *ti, PaletteID pal, const RoadTypeInfo *road_rti, const RoadTypeInfo *tram_rti, uint road_offset, uint tram_offset, bool draw_underlay)
Draw road underlay and overlay sprites.
Functions related to roads.
RoadBits AxisToRoadBits(Axis a)
Create the road-part which belongs to the given Axis.
Definition road_func.h:93
Functions used internally by the roads.
bool MayHaveRoad(Tile t)
Test whether a tile can have road/tram types.
Definition road_map.cpp:21
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition road_map.cpp:54
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition road_map.h:261
RoadType GetRoadTypeRoad(Tile t)
Get the road type for RoadTramType being RoadTramType::Road.
Definition road_map.h:152
RoadBits GetRoadBits(Tile t, RoadTramType rtt)
Get the present road bits for a specific road type.
Definition road_map.h:112
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
Definition road_map.h:311
bool HasTileRoadType(Tile t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition road_map.h:221
RoadType GetRoadTypeTram(Tile t)
Get the road type for RoadTramType being RoadTramType::Tram.
Definition road_map.h:163
void MakeRoadNormal(Tile t, RoadBits bits, RoadType road_rt, RoadType tram_rt, TownID town, Owner road, Owner tram)
Make a normal road tile.
Definition road_map.h:646
RoadBits GetAllRoadBits(Tile tile)
Get all set RoadBits on the given tile.
Definition road_map.h:125
RoadType GetRoadType(Tile t, RoadTramType rtt)
Get the road type for the given RoadTramType.
Definition road_map.h:175
static bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
Definition road_map.h:58
Owner GetRoadOwner(Tile t, RoadTramType rtt)
Get the owner of a specific road type.
Definition road_map.h:244
Roadside
The possible road side decorations.
Definition road_map.h:483
@ Paved
Road with paved sidewalks.
Definition road_map.h:486
@ Barren
Road on barren land.
Definition road_map.h:484
@ Grass
Road on grass.
Definition road_map.h:485
static constexpr RoadBits ROAD_X
Full road along the x-axis (south-west + north-east).
Definition road_type.h:67
EnumBitSet< RoadBit, uint8_t > RoadBits
Bitset of RoadBit elements.
Definition road_type.h:65
static constexpr RoadBits ROAD_Y
Full road along the y-axis (north-west + south-east).
Definition road_type.h:68
static constexpr RoadTramTypes ROADTRAMTYPES_ALL
All possible RoadTramTypes.
Definition road_type.h:49
RoadType
The different roadtypes we support.
Definition road_type.h:24
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition road_type.h:29
RoadTramType
The different types of road type.
Definition road_type.h:38
@ Tram
Tram type.
Definition road_type.h:40
@ Road
Road type.
Definition road_type.h:39
Base class for roadstops.
Road vehicle states.
@ RVSB_IN_ROAD_STOP
The vehicle is in a road stop.
Definition roadveh.h:49
@ RVSB_ROAD_STOP_TRACKDIR_MASK
Only bits 0 and 3 are used to encode the trackdir for road stops.
Definition roadveh.h:57
@ RVS_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition roadveh.h:46
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Base for ships.
bool IsShipDestinationTile(TileIndex tile, StationID station)
Test if a tile is a docking tile for the given station.
Definition ship_cmd.cpp:575
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
Definition signal.cpp:597
@ Enter
signal entering the block found
Definition signal.cpp:261
static constexpr int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height).
Definition slope_func.h:170
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition slope_func.h:36
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition slope_func.h:377
DiagDirection GetInclinedSlopeDirection(Slope s)
Returns the direction of an inclined slope.
Definition slope_func.h:249
Slope
Enumeration for the slope-type.
Definition slope_type.h:53
@ SLOPE_FLAT
a flat tile
Definition slope_type.h:54
@ Leveled
The tile is leveled up to a flat slope.
Definition slope_type.h:121
void DrawRailTileSeqInGUI(int x, int y, const DrawTileSprites *dts, int32_t total_offset, uint32_t newgrf_offset, PaletteID default_palette)
Draw tile sprite sequence in GUI with railroad specifics.
Definition sprite.h:122
void DrawRailTileSeq(const struct TileInfo *ti, const DrawTileSprites *dts, TransparencyOption to, int32_t total_offset, uint32_t newgrf_offset, PaletteID default_palette)
Draw tile sprite sequence on tile with railroad specifics.
Definition sprite.h:108
PaletteID GroundSpritePaletteTransform(SpriteID image, PaletteID pal, PaletteID default_pal)
Applies PALETTE_MODIFIER_COLOUR to a palette entry of a ground sprite.
Definition sprite.h:207
static const SpriteID SPR_TRAMWAY_TRAM
Definition sprites.h:304
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1794
static const SpriteID SPR_FLAT_SNOW_DESERT_TILE
Definition sprites.h:689
static const PaletteID PALETTE_TO_GREY
Definition sprites.h:1778
static const SpriteID SPR_IMG_BUOY
Definition sprites.h:1464
static const SpriteID SPR_FLAT_GRASS_TILE
Definition sprites.h:677
static constexpr uint8_t SPRITE_MODIFIER_CUSTOM_SPRITE
these masks change the colours of the palette for a sprite.
Definition sprites.h:1732
static constexpr uint8_t SPRITE_WIDTH
number of bits for the sprite number
Definition sprites.h:1722
static constexpr uint8_t PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition sprites.h:1735
CommandCost CheckStationSpread(TileArea area, const TileArea &new_area)
Check if adding a new area to a station will exceed the maximum station spread.
Definition station.cpp:526
Base classes/functions for stations.
void ForAllStationsAroundTiles(const TileArea &ta, Func func)
Call a function on all stations that have any part of the requested area within their catchment.
static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index=-1)
Remove a bus station/truck stop.
std::tuple< CommandCost, StationID > CmdMoveStationName(DoCommandFlags flags, StationID station_id, TileIndex tile)
Move a station name.
static StringID GetBridgeTooLowMessageForStationType(StationType type)
Get station-type-specific string for a bridge that is too low.
static const IntervalTimer< TimerGameEconomy > _economy_stations_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::Station}, [](auto) { for(Station *st :Station::Iterate()) { UpdateValidHistory(st->valid_cargo_history, HISTORY_YEAR, TimerGameEconomy::month);for(GoodsEntry &ge :st->goods) { ge.status.Set(GoodsEntry::State::LastMonth, ge.status.Test(GoodsEntry::State::CurrentMonth));ge.status.Reset(GoodsEntry::State::CurrentMonth);if(ge.HasRating()||ge.HasHistory()) { auto &stats=ge.GetOrCreateHistory();stats.history[THIS_MONTH].rx_waiting=RxCompress(GetAndResetAccumulatedAverage< uint32_t >(stats.accumulated_waiting));stats.history[THIS_MONTH].rx_supply=RxCompress(stats.supply);stats.history[THIS_MONTH].rx_lost=RxCompress(stats.lost);stats.history[THIS_MONTH].rx_accepted=RxCompress(stats.accepted);stats.history[THIS_MONTH].rating=ToPercent8(GetAndResetAccumulatedAverage< uint8_t >(ge.accumulated_rating));RotateHistory(stats.history, st->valid_cargo_history, HISTORY_YEAR, TimerGameEconomy::month);stats.supply=0;stats.lost=0;stats.accepted=0;} } } })
Economy monthly loop for stations.
static void GetTileDesc_Station(TileIndex tile, TileDesc &td)
Tile callback function signature for obtaining a tile description.
static CommandCost BuildStationPart(Station **st, DoCommandFlags flags, bool reuse, TileArea area, StationNaming name_class)
Common part of building various station parts and possibly attaching them to an existing one.
static void MakeStationSpreadAreaSmaller(BaseStation *st)
Make the spread area of a station as small as possible.
static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlags flags)
Remove a rail waypoint.
void CcMoveStationName(Commands, const CommandCost &result, StationID station_id)
Callback function that is called after a name is moved.
CommandCost IsRailStationBridgeAboveOk(TileIndex tile, const StationSpec *spec, StationType type, StationGfx layout)
Test if a rail station can be built below a bridge.
uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
Get a possible noise reduction factor based on distance from town center.
static constexpr DiagDirectionIndexArray< uint8_t > _dock_w_chk
X dimension of dock for each direction.
static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlags flags, int z_new, Slope tileh_new)
Tile callback function signature of the terraforming callback.
CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector< T * > &affected_stations, DoCommandFlags flags, Money removal_cost, bool keep_rail)
Remove a number of tiles from any rail station within the area.
static CommandCost CalculateRailStationCost(TileArea tile_area, DoCommandFlags 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)
Calculates cost of new rail stations within the area.
static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
Generate a station name for the given station at the given location.
void ClearDockingTilesCheckingNeighbours(TileIndex tile)
Clear docking tile status from tiles around a removed dock, if the tile has no neighbours which would...
bool(* CMSAMatcher)(TileIndex tile)
Function to check whether the given tile matches some criterion.
CommandCost IsRoadStationBridgeAboveOk(TileIndex tile, const RoadStopSpec *spec, StationType type, StationGfx layout)
Test if a road station can be built below a bridge.
bool IsHangar(Tile t)
Check whether the given tile is a hangar.
Town * AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIteratorWrapper< AirportTileIterator, AirportTileTableIterator > &&iter, uint &mindist)
Finds the town nearest to given airport.
static Station * GetClosestDeletedStation(TileIndex tile)
Find the closest deleted station of the current company.
CommandCost CmdRenameStation(DoCommandFlags flags, StationID station_id, const std::string &text)
Rename a station.
std::pair< CargoArray, CargoTypes > GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad)
Get the acceptance of cargoes around the tile in 1/8.
static CommandCost RemoveAirport(TileIndex tile, DoCommandFlags flags)
Remove an airport.
static void TileLoop_Station(TileIndex tile)
Tile callback function signature for running periodic tile updates.
static bool CMSAMine(TileIndex tile)
Check whether the tile is a mine.
void IncreaseStats(Station *st, CargoType cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateModes modes)
Increase capacity for a link stat given by station cargo and next hop.
static CommandCost CheckFlatLandRoadStop(TileIndex cur_tile, int &allowed_z, const RoadStopSpec *spec, DoCommandFlags flags, DiagDirections invalid_dirs, bool is_drive_through, StationType station_type, Axis axis, StationID *station, RoadType rt)
Checks if a road stop can be built at the given tile.
static CommandCost RemoveGenericRoadStop(DoCommandFlags flags, const TileArea &roadstop_area, bool road_waypoint, bool remove_road)
Remove a tile area of road stop or road waypoints.
static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount=UINT_MAX)
Truncate the cargo by a specific amount.
CommandCost CmdRemoveFromRailWaypoint(DoCommandFlags flags, TileIndex start, TileIndex end, bool keep_rail)
Remove a single tile from a waypoint.
StationNaming
Station types a station could be named after.
@ Dock
Ship dock.
@ Rail
Railway station.
@ Road
Truck or bus stop.
@ Oilrig
Heliport of an oilrig.
@ Heliport
Standalone heliport.
@ Airport
Airport for fixed wing aircraft.
CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
Find a nearby waypoint that joins this waypoint.
CommandCost CmdBuildDock(DoCommandFlags flags, TileIndex tile, StationID station_to_join, bool adjacent)
Build a dock/haven.
CommandCost IsBuoyBridgeAboveOk(TileIndex tile)
Test if a buoy can be built below a bridge.
static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlags flags)
Checks if an airport can be built at the given location and clear the area.
CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index=-1)
Remove a road waypoint.
CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st, F filter)
Look for a station owned by the given company around the given tile area.
CommandCost CmdRemoveRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
Remove bus or truck stops.
static VehicleEnterTileStates VehicleEnterTile_Station(Vehicle *v, TileIndex tile, int x, int y)
Tile callback function for a vehicle entering a tile.
static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
Tile callback function signature for changing the owner of a tile.
bool HasStationInUse(StationID station, bool include_company, CompanyID company)
Tests whether the company's vehicles have this station in orders.
static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
Counts the numbers of tiles matching a specific type in the area around.
CommandCost CmdBuildRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through, DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
Build a bus or truck stop.
static StationSpec::TileFlags GetStationTileFlags(StationGfx gfx, const StationSpec *statspec)
Get station tile flags for the given StationGfx.
static CommandCost IsDockBridgeAboveOk(TileIndex tile, StationGfx layout)
Test if a dock can be built below a bridge.
static bool DrawCustomStationFoundations(const StationSpec *statspec, BaseStation *st, TileInfo *ti, StationGfx gfx)
Draw custom station foundations for a NewGRF station if provided.
const DrawTileSprites * GetStationTileLayout(StationType st, uint8_t gfx)
Get station tile layout for a station type and its station gfx.
CommandCost CmdRemoveFromRoadWaypoint(DoCommandFlags flags, TileIndex start, TileIndex end)
Remove road waypoints.
void RerouteCargo(Station *st, CargoType cargo, StationID avoid, StationID avoid2)
Reroute cargo of type c at station st or in any vehicles unloading there.
static constexpr DiagDirectionIndexArray< TileIndexDiffC > _dock_tileoffs_chkaround
Offset of northern-most dock tile for each direction.
CommandCost ClearTile_Station(TileIndex tile, DoCommandFlags flags)
Tile callback function signature for clearing a tile.
static std::pair< CargoArray, CargoTypes > GetAcceptanceAroundStation(const Station *st)
Get the acceptance of cargoes around the station in.
static void UpdateStationRating(Station *st)
Periodic update of a station's rating.
static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, RoadTramType sub_mode, DiagDirection side)
Tile callback function signature for getting the possible tracks that can be taken on a given tile by...
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
static void DrawTile_Station(TileInfo *ti)
Tile callback function signature for drawing a tile and its contents to the screen.
static bool CMSAWater(TileIndex tile)
Check whether the tile is water.
CommandCost CmdBuildAirport(DoCommandFlags flags, TileIndex tile, uint8_t airport_type, uint8_t layout, StationID station_to_join, bool allow_adjacent)
Place an Airport.
void TriggerWatchedCargoCallbacks(Station *st)
Run the watched cargo callback for all houses in the catchment area.
static CommandCost CanRemoveRoadWithStop(TileIndex tile, DoCommandFlags flags)
Check if a drive-through road stop tile can be cleared.
static RoadStop ** FindRoadStopSpot(bool truck_station, Station *st)
CargoTypes GetAcceptanceMask(const Station *st)
Get a mask of the cargo types that the station accepts.
static void RestoreTrainReservation(Train *v)
Restore platform reservation during station building/removing.
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
static std::span< const BridgeableTileInfo > GetStationBridgeableTileInfo(StationType type)
Get bridgeable tile information for a station type.
static bool CMSATree(TileIndex tile)
Check whether the tile is a tree.
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
Forcibly modify station ratings near a given tile.
CommandCost RemoveRailStation(T *st, DoCommandFlags flags, Money removal_cost)
Remove a rail station/waypoint.
void UpdateStationAcceptance(Station *st, bool show_msg)
Update the acceptance for a station.
static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
Find a nearby station that joins this road stop.
CommandCost CmdOpenCloseAirport(DoCommandFlags flags, StationID station_id)
Open/close an airport to incoming aircraft.
static CommandCost CheckFlatLandRailStation(TileIndex tile_cur, TileIndex north_tile, int &allowed_z, DoCommandFlags 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)
Checks if a rail station can be built at the given tile.
static TileIndex FindDockLandPart(TileIndex t)
Find the part of a dock that is land-based.
static CommandCost CheckBuildAbove_Station(TileIndex tile, DoCommandFlags flags, Axis axis, int height)
Tile callback function signature to test if a bridge can be built above a tile.
static void FreeTrainReservation(Train *v)
Clear platform reservation during station building/removing.
static bool ClickTile_Station(TileIndex tile)
Tile callback function signature for clicking a tile.
void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
Set rail station tile flags for the given tile.
CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlags flags, bool is_drive_through, StationType station_type, const RoadStopSpec *roadstopspec, Axis axis, DiagDirection ddir, StationID *station, RoadType rt, Money unit_cost)
Calculates cost of new road stops within the area.
CargoTypes GetCargoWaitingMask(const Station *st)
Get a mask of the cargo types that have cargo waiting at the station.
static CommandCost RemoveDock(TileIndex tile, DoCommandFlags flags)
Remove a dock.
static void AnimateTile_Station(TileIndex tile)
Tile callback function signature for animating a tile.
bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a ra...
CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
Get the cargo types being produced around the tile (in a rectangle).
CommandCost CmdRemoveFromRailStation(DoCommandFlags flags, TileIndex start, TileIndex end, bool keep_rail)
Remove a single tile from a rail station.
static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
Find a nearby station that joins this station.
void DeleteStaleLinks(Station *from)
Check all next hops of cargo packets in this station for existence of a a valid link they may use to ...
static BridgePillarFlags GetStationBlockedPillars(std::span< const BridgeableTileInfo > bridgeable_info, uint8_t layout)
Get blocked pillar information for a station tile.
CommandCost CheckBuildableTile(TileIndex tile, DiagDirections invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge=true)
Checks if the given tile is buildable, flat and has a certain height.
CommandCost FindJoiningBaseStation(StringID error_message, StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
Find a nearby station that joins this station.
static constexpr DiagDirectionIndexArray< uint8_t > _dock_h_chk
Y dimension of dock for each direction.
static bool StationHandleBigTick(BaseStation *st)
This function is called for each station once every 250 ticks.
static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
Add news item for when a station changes which cargoes it accepts.
CommandCost CmdBuildRailStation(DoCommandFlags flags, TileIndex tile_org, RailType rt, Axis axis, uint8_t numtracks, uint8_t plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
Build rail station.
static void DeleteStationIfEmpty(BaseStation *st)
This is called right after a station was deleted.
static CommandCost IsStationBridgeAboveOk(TileIndex tile, std::span< const BridgeableTileInfo > bridgeable_info, StationType type, StationGfx layout, int bridge_height, StringID disallowed_msg=INVALID_STRING_ID)
Test if a bridge can be built above a station.
Command definitions related to stations.
Functions related to stations.
void ShowStationViewWindow(StationID station)
Opens StationViewWindow for given station.
@ Count
by amount of cargo
Declarations for accessing the k-d tree of stations.
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
Sprites to use and how to display them for station tiles.
Functions related to station layouts.
void MakeAirport(Tile t, Owner o, StationID sid, uint8_t section, WaterClass wc)
Make the given tile an airport tile.
StationType GetStationType(Tile t)
Get the station type of this tile.
Definition station_map.h:42
StationGfx GetStationGfx(Tile t)
Get the station graphics of this tile.
Definition station_map.h:66
void SetStationGfx(Tile t, StationGfx gfx)
Set the station graphics of this tile.
Definition station_map.h:78
void MakeRoadStop(Tile t, Owner o, StationID sid, RoadStopType rst, RoadType road_rt, RoadType tram_rt, DiagDirection d)
Make the given tile a roadstop tile.
void SetCustomStationSpecIndex(Tile t, uint8_t specindex)
Set the custom station spec for this tile.
void SetStationTileHaveWires(Tile t, bool b)
Set the catenary wires state of the rail station.
bool IsAirport(Tile t)
Is this station tile an airport?
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
uint GetCustomRoadStopSpecIndex(Tile t)
Get the custom road stop spec for this tile.
static const int GFX_DOCK_BASE_WATER_PART
The offset for the water parts.
Definition station_map.h:33
bool IsBuoy(Tile t)
Is tile t a buoy tile?
bool IsCompatibleTrainStationTile(Tile test_tile, Tile station_tile)
Check if a tile is a valid continuation to a railstation tile.
bool IsRoadWaypoint(Tile t)
Is the station at t a road waypoint?
void MakeDriveThroughRoadStop(Tile t, Owner station, Owner road, Owner tram, StationID sid, StationType rst, RoadType road_rt, RoadType tram_rt, Axis a)
Make the given tile a drivethrough roadstop tile.
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
static Roadside GetRoadWaypointRoadside(Tile tile)
Get the decorations of a road waypoint.
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
Track GetRailStationTrack(Tile t)
Get the rail track of a rail station tile.
static void ToggleRoadWaypointOnSnowOrDesert(Tile t)
Toggle the snow/desert state of a road waypoint tile.
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:26
bool HasStationTileRail(Tile t)
Has this station tile a rail?
StationGfx GetAirportGfx(Tile t)
Get the station graphics of this airport tile.
uint GetCustomStationSpecIndex(Tile t)
Get the custom station spec for this tile.
bool IsRailWaypoint(Tile t)
Is this station tile a rail waypoint?
bool IsRailStation(Tile t)
Is this station tile a rail station?
Definition station_map.h:90
bool IsDockTile(Tile t)
Is tile t a dock tile?
static void SetRoadWaypointRoadside(Tile tile, Roadside s)
Set the decorations of a road waypoint.
void SetStationTileRandomBits(Tile t, uint8_t random_bits)
Set the random bits for a station tile.
bool IsAnyRoadStop(Tile t)
Is the station at t a road station?
void MakeOilrig(Tile t, StationID sid, WaterClass wc)
Make the given tile an oilrig tile.
DiagDirection GetDockDirection(Tile t)
Get the direction of a dock.
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
static bool IsRoadWaypointOnSnowOrDesert(Tile t)
Check if a road waypoint tile has snow/desert.
bool IsRoadWaypointTile(Tile t)
Is this tile a station tile and a road waypoint?
bool IsStationTileBlocked(Tile t)
Is tile t a blocked tile?
bool IsTruckStop(Tile t)
Is the station at t a truck stop?
uint8_t StationGfx
Index of station graphics.
Definition station_map.h:18
bool IsStationRoadStop(Tile t)
Is the station at t a road station?
bool IsCustomStationSpecIndex(Tile t)
Is there a custom rail station spec on this tile?
bool HasStationRail(Tile t)
Has this station tile a rail?
static const int GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET
The offset for the drive through parts.
Definition station_map.h:34
Axis GetDriveThroughStopAxis(Tile t)
Gets the axis of the drive through stop.
void SetStationTileHavePylons(Tile t, bool b)
Set the catenary pylon state of the rail station.
bool IsOilRig(Tile t)
Is tile t part of an oilrig?
bool IsBuoyTile(Tile t)
Is tile t a buoy tile?
void MakeRailStation(Tile t, Owner o, StationID sid, Axis a, uint8_t section, RailType rt)
Make the given tile a rail station tile.
bool HasStationReservation(Tile t)
Get the reservation state of the rail station.
void MakeDock(Tile t, Owner o, StationID sid, DiagDirection d, WaterClass wc)
Make the given tile a dock tile.
DiagDirection GetBayRoadStopDir(Tile t)
Gets the direction the bay road stop entrance points towards.
bool IsDock(Tile t)
Is tile t a dock tile?
bool IsAnyRoadStopTile(Tile t)
Is tile t a road stop station?
void SetStationTileBlocked(Tile t, bool b)
Set the blocked state of the rail station.
RoadStopType GetRoadStopType(Tile t)
Get the road stop type of this tile.
Definition station_map.h:54
void SetCustomRoadStopSpecIndex(Tile t, uint8_t specindex)
Set the custom road stop spec for this tile.
RoadStopType
Types of RoadStops.
@ Bus
A standard stop for buses.
@ Truck
A standard stop for trucks.
@ End
End of valid types.
@ Dock
Station with a dock.
@ Waypoint
Station is a waypoint.
@ TruckStop
Station with truck stops.
@ Train
Station with train station.
@ Airport
Station with an airport.
@ BusStop
Station with bus stops.
StationType
Station types.
@ Dock
Ship port.
@ Rail
Railways/train station.
@ Bus
Road stop for busses.
@ Truck
Road stop for trucks.
@ RailWaypoint
Waypoint for trains.
@ Buoy
Waypoint for ships.
@ RoadWaypoint
Waypoint for trucks and busses.
@ Oilrig
Heliport on an oil rig.
@ Airport
Airports and heliports, excluding the ones on oil rigs.
@ NewCargo
Trigger station on new cargo arrival.
std::set< Station *, StationCompare > StationList
List of stations.
@ Built
Trigger tile when built.
@ TileLoop
Trigger in the periodic tile loop.
@ NewCargo
Trigger station on new cargo arrival.
@ AcceptanceTick
Trigger station every 250 ticks.
EnumBitSet< StationFacility, uint8_t > StationFacilities
Bitset of StationFacility elements.
static const uint MAX_LENGTH_STATION_NAME_CHARS
The maximum length of a station name in characters including '\0'.
@ Built
Triggered when the airport is built (for all tiles at the same time).
@ TileLoop
Triggered in the periodic tile loop.
@ NewCargo
Triggered when new cargo arrives at the station (for all tiles at the same time).
@ AcceptanceTick
Triggered every 250 ticks (for all tiles at the same time).
Types related to the station widgets.
@ WID_SV_CLOSE_AIRPORT
'Close airport' button.
@ WID_SV_ROADVEHS
List of scheduled road vehs button.
@ WID_SV_ACCEPT_RATING_LIST
List of accepted cargoes / rating of cargoes.
@ WID_SV_SHIPS
List of scheduled ships button.
@ WID_SV_TRAINS
List of scheduled trains button.
Definition of base types and functions in a cross-platform compatible way.
size_t Utf8StringLength(std::string_view str)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition string.cpp:350
Functions related to low-level strings.
void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition strings.cpp:335
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
Functions related to OTTD's strings.
auto MakeParameters(Args &&... args)
Helper to create the StringParameters with its own buffer with the given parameter values.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
static constexpr StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames).
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition aircraft.h:75
@ Airplanes
Can planes land on this airport type?
Definition airport.h:165
Defines the data structure for an airport.
StringID name
name of this airport
SubstituteGRFFileProps grf_prop
Properties related to the grf file.
std::vector< AirportTileLayout > layouts
List of layouts composing the airport.
bool IsWithinMapBounds(uint8_t table, TileIndex index) const
Check if the airport would be within the map bounds at the given tile.
uint8_t size_y
size of airport in y direction
uint8_t size_x
size of airport in x direction
static const AirportSpec * Get(uint8_t type)
Retrieve airport spec for the given airport.
std::span< const HangarTileTable > depots
Position of the depots on the airports.
bool IsAvailable() const
Check whether this airport is available to build.
uint8_t noise_level
noise that this airport generates
Defines the data structure of each individual tile of an airport.
static const AirportTileSpec * Get(StationGfx gfx)
Retrieve airport tile spec for the given airport tile.
SubstituteGRFFileProps grf_prop
properties related the the grf file
StringID name
Tile Subname string, land information on this tile will give you "AirportName (TileSubname)".
static const AirportTileSpec * GetByTile(TileIndex tile)
Retrieve airport tile spec for the given airport tile.
All airport-related information.
AirportBlocks blocks
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
TileIndex GetRotatedTileFromOffset(TileIndexDiffC tidc) const
Add the tileoffset to the base tile of this airport but rotate it first.
uint GetHangarNum(TileIndex tile) const
Get the hangar number of the hangar at a specific tile.
Direction rotation
How this airport is rotated.
uint8_t type
Type of this airport,.
PersistentStorage * psa
Persistent storage for NewGRF airports.
uint GetNumHangars() const
Get the number of hangars on this airport.
TileIndex GetHangarTile(uint hangar_num) const
Get the first tile of the given hangar.
const AirportSpec * GetSpec() const
Get the AirportSpec that from the airport type of this airport.
uint8_t layout
Airport layout number.
Base class for all station-ish types.
StringID string_id
Default name (town area) of station.
TileIndex xy
Base tile of the station.
virtual void MoveSign(TileIndex new_xy)
Move this station's main coordinate somewhere else.
std::vector< SpecMapping< StationSpec > > speclist
List of rail station specs of this station.
StationFacilities facilities
The facilities that this station has.
std::string cached_name
NOSAVE: Cache of the resolved name of the station, if not using a custom name.
TileArea train_station
Tile area the train 'station' part covers.
StationAnimationTriggers cached_anim_triggers
NOSAVE: Combined animation trigger bitmask, used to determine if trigger processing should happen.
Owner owner
The owner of this station.
virtual void UpdateVirtCoord()=0
Update the coordinated of the sign (as shown in the viewport).
uint8_t delete_ctr
Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is ...
StationAnimationTriggers cached_roadstop_anim_triggers
NOSAVE: Combined animation trigger bitmask for road stops, used to determine if trigger processing sh...
bool IsInUse() const
Check whether the base station currently is in use; in use means that it is not scheduled for deletio...
Town * town
The town this station is associated with.
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
virtual bool TileBelongsToRailStation(TileIndex tile) const =0
Check whether a specific tile belongs to this station.
TrackedViewportSign sign
NOSAVE: Dimensions of sign.
TimerGameCalendar::Date build_date
Date of construction.
std::string name
Custom name.
TileArea spread
NOSAVE: Station spread tile area.
VehicleType type
Type of vehicle.
Class for storing amounts of cargo.
Definition cargo_type.h:120
Specification of a cargo type.
Definition cargotype.h:76
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
CargoType Index() const
Determines index of this cargospec.
Definition cargotype.h:110
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition cargotype.h:239
uint32_t station
Count of company owned station tiles.
std::array< uint32_t, RAILTYPE_END > rail
Count of company owned track bits for each rail type.
uint32_t water
Count of company owned track bits for canals.
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
T y
Y coordinate.
T x
X coordinate.
T z
Z coordinate.
Ground palette sprite of a tile, together with its sprite layout.
Definition sprite.h:76
Ground palette sprite of a tile, together with its sprite layout.
Definition sprite.h:55
PalSpriteID ground
Palette and sprite for the ground.
Definition sprite.h:56
std::string GetName() const
Get the name of this grf.
GrfID grfid
grfid that introduced this entity.
const struct GRFFile * grffile
grf file that introduced this entity
bool HasGrfFile() const
Test if this entity was introduced by NewGRF.
StationSettings station
settings related to station management
uint32_t supply
Cargo supplied over the last period.
HistoryData< CargoHistory > history
Historical cargo data.
uint32_t lost
Cargo lost over the last period.
uint32_t accumulated_waiting
Accumulated waiting over the last period.
Individual data point for station cargo history.
FlowStatMap flows
Planned flows through this station.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Stores station stats for a single cargo.
uint max_waiting_cargo
Max cargo from this station waiting at any station.
bool HasRating() const
Does this cargo have a rating at this station?
uint16_t accumulated_rating
Accumulated rating over the last month.
uint8_t last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
uint TotalCount() const
Returns total count of cargo at the station, including cargo which is already reserved for loading.
uint8_t last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
uint8_t time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
States status
Status of this cargo, see State.
NodeID node
ID of node in link graph referring to this goods entry.
@ LastMonth
Set when cargo was delivered for final delivery last month.
@ Acceptance
Set when the station accepts the cargo currently for final deliveries.
@ Rating
This indicates whether a cargo has a rating at the station.
@ AcceptedBigtick
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval.
@ CurrentMonth
Set when cargo was delivered for final delivery this month.
const GoodsEntryData & GetData() const
Get optional cargo packet/flow data.
uint8_t amount_fract
Fractional part of the amount in the cargo list.
LinkGraphID link_graph
Link graph this station belongs to.
bool HasVehicleEverTriedLoading() const
Reports whether a vehicle has ever tried to load the cargo at this station.
CargoHistoryData & GetOrCreateHistory()
Get or create the cargo history data.
uint8_t rating
Station rating for this cargo.
bool HasData() const
Test if this goods entry has optional cargo packet/flow data.
bool HasHistory() const
Test if cargo history is present.
GoodsEntryData & GetOrCreateData()
Get optional cargo packet/flow data.
uint AvailableCount() const
Returns sum of cargo still available for loading at the station.
StationID GetVia(StationID source) const
Get the best next hop for a cargo packet from station source.
Defines the data structure for constructing industry.
SubstituteGRFFileProps grf_prop
properties related to the grf file
StringID name
Displayed name of the industry.
StringID station_name
Default name for nearby station.
bool enabled
entity still available (by default true).newgrf can disable it, though
IndustryLifeTypes life_type
This is also known as Industry production flag, in newgrf specs.
Defines the internal data of a functional industry.
Definition industry.h:64
IndustryType type
type of industry.
Definition industry.h:117
ProducedCargoes produced
produced cargo slots
Definition industry.h:112
Owner owner
owner of the industry. Which SHOULD always be (imho) OWNER_NONE
Definition industry.h:118
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition industry.h:253
TileArea location
Location of the industry.
Definition industry.h:108
Station * neutral_station
Associated neutral station.
Definition industry.h:110
StationList stations_near
NOSAVE: List of nearby stations.
Definition industry.h:125
static uint SizeX()
Get the size of the map along the X.
Definition map_func.h:262
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:271
static uint Size()
Get the size of the map.
Definition map_func.h:280
Tindex class_index
Class index of this spec, invalid until class is allocated.
NewGRF supplied spritelayout.
static void Reset(TileIndex tile=INVALID_TILE, bool from_gui=true)
Reset the OrderBackups from GUI/game logic.
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition order_base.h:373
If you change this, keep in mind that it is also saved in 2 other places:
Definition order_base.h:33
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
SpriteID sprite
The 'real' sprite.
Definition gfx_type.h:23
PaletteID pal
The palette (use PAL_NONE) if not needed).
Definition gfx_type.h:24
static Pool::IterateWrapper< BaseStation > Iterate(size_t from=0)
static T * Create(Targs &&... args)
static Industry * Get(auto index)
static LinkGraph * GetIfValid(auto index)
Road stop specification.
Money GetBuildCost(Price category) const
Get the cost for building a road stop of this type.
std::array< BridgeableTileInfo, 6 > bridgeable_info
Per tile layout bridge information.
CargoGRFFileProps grf_prop
Link to NewGRF.
Money GetClearCost(Price category) const
Get the cost for clearing a road stop of this type.
A Stop for a Road Vehicle.
RoadStop * next
Next stop of the given type at this station.
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
Definition roadstop.cpp:253
void MakeDriveThrough()
Join this road stop to another 'base' road stop if possible; fill all necessary data to become an act...
Definition roadstop.cpp:60
void ClearDriveThrough()
Prepare for removal of this stop; update other neighbouring stops if needed.
Definition roadstop.cpp:122
Buses, trucks and trams belong to this class.
Definition roadveh.h:105
uint8_t state
Definition roadveh.h:107
All ships have this type.
Definition ship.h:39
static Station * Create(Targs &&... args)
static bool IsExpected(const BaseStation *st)
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static Station * Get(auto index)
static Station * GetIfValid(auto index)
static Station * From(BaseStation *st)
static RoadVehicle * From(Vehicle *v)
T * Last()
Get the last vehicle in the chain.
bool HasSpriteGroups() const
Check whether the entity has sprite groups.
Information to handle station action 0 property 24 correctly.
void SetUsed(StringID str)
Mark the given station name as used.
std::bitset< NUM_INDUSTRYTYPES > indtypes
Bit set indicating when an industry type has been found.
std::bitset<(STR_SV_STNAME_FALLBACK - STR_SV_STNAME).base()> used_names
Used default station suffixes.
bool IsAvailable(StringID str) const
Is the given station name available, and not already used?
bool serve_neutral_industries
company stations can serve industries with attached neutral stations
Station specification.
std::vector< BridgeableTileInfo > bridgeable_info
Per tile layout bridge information.
uint8_t disallowed_lengths
Bitmask of platform lengths available for the station.
StringID name
Name of this station.
uint8_t disallowed_platforms
Bitmask of number of platforms available for the station.
CargoGRFFileProps grf_prop
Link to NewGRF.
std::vector< TileFlags > tileflags
List of tile flags.
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
EnumBitSet< TileFlag, uint8_t > TileFlags
Bitset of TileFlag elements.
StationCallbackMasks callback_mask
Bitmask of station callbacks that have to be called.
@ NoWires
Tile should NOT contain catenary wires.
@ Pylons
Tile should contain catenary pylons.
@ Blocked
Tile is blocked to vehicles.
StationSpecFlags flags
Bitmask of flags, bit 0: use different sprite set; bit 1: divide cargo about by station size.
Station data structure.
TileArea GetTileArea(StationType type) const override
Get the tile area for a given station type.
RoadStop * bus_stops
All the road stops.
TileArea ship_station
Tile area the ship 'station' part covers.
IndustryType indtype
Industry type to get the name from.
TileArea docking_station
Tile area the docking tiles cover.
CargoTypes always_accepted
Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn't accept c...
Industry * industry
NOSAVE: Associated industry for neutral stations. (Rebuilt on load from Industry->st).
void MoveSign(TileIndex new_xy) override
Move the station main coordinate somewhere else.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
TileArea bus_station
Tile area the bus 'station' part covers.
BitmapTileArea catchment_tiles
NOSAVE: Set of individual tiles covered by catchment area.
void RecomputeCatchment(bool no_clear_nearby_lists=false)
Recompute tiles covered in our catchment area.
Definition station.cpp:447
void AfterStationTileSetChange(bool adding, StationType type)
After adding/removing tiles to station, update some station-related stuff.
Airport airport
Tile area the airport covers.
void UpdateVirtCoord() override
Update the virtual coords needed to draw the station sign.
TileArea truck_station
Tile area the truck 'station' part covers.
RoadStop * truck_stops
All the truck stops.
void AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
Called when new facility is built on the station.
Definition station.cpp:233
uint16_t subst_id
The id of the entity to replace.
Tile description for the 'land area information' tool.
Definition tile_cmd.h:40
uint16_t rail_speed
Speed limit of rail (bridges and track).
Definition tile_cmd.h:53
std::optional< std::string > grf
newGRF used for the tile contents
Definition tile_cmd.h:51
StringID station_name
Type of station within the class.
Definition tile_cmd.h:47
StringID str
Description of the tile.
Definition tile_cmd.h:41
TimerGameCalendar::Date build_date
Date of construction of tile contents.
Definition tile_cmd.h:45
std::array< Owner, 4 > owner
Name of the owner(s).
Definition tile_cmd.h:43
StringID airport_class
Name of the airport class.
Definition tile_cmd.h:48
StringID airport_name
Name of the airport.
Definition tile_cmd.h:49
uint16_t tram_speed
Speed limit of tram (bridges and track).
Definition tile_cmd.h:57
StringID roadtype
Type of road on the tile.
Definition tile_cmd.h:54
StringID tramtype
Type of tram on the tile.
Definition tile_cmd.h:56
StringID railtype
Type of rail on the tile.
Definition tile_cmd.h:52
uint16_t road_speed
Speed limit of road (bridges and track).
Definition tile_cmd.h:55
std::array< StringID, 4 > owner_type
Type of each owner.
Definition tile_cmd.h:44
StringID airport_tile_name
Name of the airport tile.
Definition tile_cmd.h:50
StringID station_class
Class of station.
Definition tile_cmd.h:46
Tile information, used while rendering the tile.
Definition tile_cmd.h:34
Slope tileh
Slope of the tile.
Definition tile_cmd.h:35
TileIndex tile
Tile index.
Definition tile_cmd.h:36
Town data structure.
Definition town.h:64
CompanyMask statues
which companies have a statue?
Definition town.h:82
TileIndex xy
town center tile
Definition town.h:65
uint16_t noise_reached
level of noise that all the airports are generating
Definition town.h:80
uint16_t MaxTownNoise() const
Calculate the max town noise.
Definition town.h:224
CompanyID exclusivity
which company has exclusivity
Definition town.h:87
uint8_t exclusive_counter
months till the exclusivity expires
Definition town.h:88
Track status of a tile.
Definition track_type.h:105
'Train' is either a loco or a wagon.
Definition train.h:97
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
Vehicle data structure.
Direction GetMovingDirection() const
Get the moving direction of this vehicle chain.
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
bool IsMovingFront() const
Is this vehicle the moving front of the vehicle chain?
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
virtual void SetDestTile(TileIndex tile)
Set the destination of this vehicle.
VehStates vehstatus
Status.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
virtual TileIndex GetOrderStationLocation(StationID station)
Determine the location for the station where the vehicle goes to next.
Order current_order
The current order (+ status, like: loading).
Vehicle * Next() const
Get the next vehicle of this vehicle.
Vehicle * NextShared() const
Get the next vehicle of the shared vehicle chain.
uint16_t cur_speed
current speed
bool IsFrontEngine() const
Check if the vehicle is a front engine.
TileIndex tile
Current tile index.
TileIndex dest_tile
Heading for this tile.
Owner owner
Which company owns the vehicle?
Representation of a waypoint.
TileArea road_waypoint_area
Tile area the road waypoint part covers.
uint16_t waypoint_flags
Waypoint flags, see WaypointFlags.
void UpdateVirtCoord() override
Update the virtual coords needed to draw the waypoint sign.
@ Source
town/industry is source of subsidised path
@ EnteredStation
The vehicle entered a station.
Definition tile_cmd.h:25
@ CannotEnter
The vehicle cannot enter the tile.
Definition tile_cmd.h:27
void AddProducedCargo(TileIndex tile, CargoArray &produced)
Obtain the produced cargo of a tile.
Definition tile_cmd.h:257
EnumBitSet< VehicleEnterTileState, uint8_t > VehicleEnterTileStates
Bitset of VehicleEnterTileState elements.
Definition tile_cmd.h:31
void AddAcceptedCargo(TileIndex tile, CargoArray &acceptance, CargoTypes &always_accepted)
Obtain cargo acceptance of a tile.
Definition tile_cmd.h:245
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition tile_map.cpp:94
std::tuple< Slope, int > GetTileSlopeZ(TileIndex tile)
Return the slope of a given tile inside the map.
Definition tile_map.cpp:55
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition tile_map.cpp:135
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition tile_map.cpp:115
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition tile_map.h:214
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
void SetTileOwner(Tile tile, Owner owner)
Sets the owner of a tile.
Definition tile_map.h:198
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition tile_map.h:312
uint8_t GetAnimationFrame(Tile t)
Get the current animation frame.
Definition tile_map.h:250
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition tile_map.h:161
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Definition tile_map.h:238
void SetAnimationFrame(Tile t, uint8_t frame)
Set a new animation frame.
Definition tile_map.h:262
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
Definition tile_map.h:279
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
@ Desert
Tile is desert.
Definition tile_type.h:83
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
static constexpr uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in ZOOM_BASE.
Definition tile_type.h:18
@ Water
Water tile.
Definition tile_type.h:55
@ Station
A tile of a station or airport.
Definition tile_type.h:54
@ Industry
Part of an industry.
Definition tile_type.h:57
@ Trees
Tile with one or more trees.
Definition tile_type.h:53
@ House
A house by a town.
Definition tile_type.h:52
@ Road
A tile with road and/or tram tracks.
Definition tile_type.h:51
@ Clear
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition tile_type.h:49
Class for iterating an airport on the map.
Class for iterating an airport layout on the map.
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Type for iterating a sprial tile area.
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Base of the town class.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
HouseZone GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlags flags)
Checks whether the local authority allows construction of a new station (rail, road,...
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition track_func.h:292
bool IsReversingRoadTrackdir(Trackdir dir)
Checks whether the trackdir means that we are reversing.
Definition track_func.h:568
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition track_func.h:220
Track AxisToTrack(Axis a)
Convert an Axis to the corresponding Track Axis::X -> Track::X Axis::Y -> Track::Y Uses the fact that...
Definition track_func.h:62
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Definition track_func.h:343
Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a DiagDirection to the associated diagonal Track.
Definition track_func.h:419
static constexpr TrackBits TRACK_BIT_3WAY_NE
"Arrow" to the north-east
Definition track_type.h:48
EnumBitSet< Track, uint8_t > TrackBits
Bitset of Track elements.
Definition track_type.h:43
static constexpr TrackBits TRACK_BIT_ALL
All possible tracks.
Definition track_type.h:52
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:63
Track
These are used to specify a single track.
Definition track_type.h:19
@ Upper
Track in the upper corner of the tile (north).
Definition track_type.h:23
@ Y
Track along the y-axis (north-west to south-east).
Definition track_type.h:22
@ Left
Track in the left corner of the tile (west).
Definition track_type.h:25
Base for the train class.
bool TryPathReserve(Train *v, bool mark_as_stuck=false, bool first_tile_okay=false)
Try to reserve a path to a safe position.
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *moving_front, int *station_ahead, int *station_length)
Get the stop location of (the center) of the front vehicle of a train at a platform of a station.
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
@ Buildings
company buildings - depots, stations, HQ, ...
TransportType
Available types of transport.
@ Water
Transport over water.
@ Rail
Transport by train.
@ Road
Transport by road vehicle.
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
Definition vehicle.cpp:561
@ TrainSlowing
Train is slowing down.
Functions related to vehicles.
@ Ship
Ship vehicle type.
@ Invalid
Non-existing type of vehicle.
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
Functions and type for generating vehicle lists.
void FindVehiclesWithOrder(VehiclePredicate veh_pred, OrderPredicate ord_pred, VehicleFunc veh_func)
Find vehicles matching an order.
void OffsetGroundSprite(int x, int y)
Called when a foundation has been drawn for the current tile.
Definition viewport.cpp:606
void SetViewportStationRect(const Station *st, bool sel)
Select or deselect station for rectangle area highlight.
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
Definition viewport.cpp:766
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int z, const SpriteBounds &bounds, bool transparent, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition viewport.cpp:665
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
Definition viewport.cpp:776
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition viewport.cpp:580
Functions related to (drawing on) viewports.
static const int TILE_HEIGHT_STEP
One Z unit tile height difference is displayed as 50m.
Declarations for accessing the k-d tree of viewports.
Functions related to water management.
void TileLoop_Water(TileIndex tile)
Tile callback function signature for running periodic tile updates.
void CheckForDockingTile(TileIndex t)
Mark the supplied tile as a docking tile if it is suitable for docking.
bool IsPossibleDockingTile(Tile t)
Check whether it is feasible that the given tile could be a docking tile.
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
Definition water_map.h:356
bool IsTileOnWater(Tile t)
Tests if the tile was built on water.
Definition water_map.h:140
WaterClass
classes of water (for WaterTileType::Clear water tile type).
Definition water_map.h:41
@ Invalid
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition water_map.h:45
@ Canal
Canal.
Definition water_map.h:43
@ Sea
Sea.
Definition water_map.h:42
bool HasTileWaterClass(Tile t)
Checks whether the tile has an waterclass associated.
Definition water_map.h:105
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition water_map.h:116
bool IsDockingTile(Tile t)
Checks whether the tile is marked as a dockling tile.
Definition water_map.h:378
void SetDockingTile(Tile t, bool b)
Set the docking tile state of a tile.
Definition water_map.h:367
bool IsWater(Tile t)
Is it a plain water tile?
Definition water_map.h:151
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
Definition water_map.h:194
Base of waypoints.
@ WPF_ROAD
This is a road waypoint.
CommandCost RemoveBuoy(TileIndex tile, DoCommandFlags flags)
Remove a buoy.
Command definitions related to waypoints.
Functions related to waypoints.
void ShowWaypointWindow(const Waypoint *wp)
Show the window for the given waypoint.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
Definition window.cpp:3285
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3377
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting).
Definition window.cpp:3271
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3395
Entry point for OpenTTD to YAPF's cache.
void YapfNotifyTrackLayoutChange(TileIndex tile, Track track)
Use this function to notify YAPF that track layout (or signal configuration) has change.
@ Station
station encountered (could be a target next time)
Definition yapf_type.hpp:26