OpenTTD Source  14.1
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 <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 #include "aircraft.h"
12 #include "bridge_map.h"
13 #include "viewport_func.h"
14 #include "viewport_kdtree.h"
15 #include "command_func.h"
16 #include "town.h"
17 #include "news_func.h"
18 #include "train.h"
19 #include "ship.h"
20 #include "roadveh.h"
21 #include "industry.h"
22 #include "newgrf_cargo.h"
23 #include "newgrf_debug.h"
24 #include "newgrf_station.h"
25 #include "newgrf_canal.h" /* For the buoy */
27 #include "road_internal.h" /* For drawing catenary/checking road removal */
28 #include "autoslope.h"
29 #include "water.h"
30 #include "strings_internal.h"
31 #include "clear_func.h"
33 #include "vehicle_func.h"
34 #include "string_func.h"
35 #include "animated_tile_func.h"
36 #include "elrail_func.h"
37 #include "station_base.h"
38 #include "station_func.h"
39 #include "station_kdtree.h"
40 #include "roadstop_base.h"
41 #include "newgrf_railtype.h"
42 #include "newgrf_roadtype.h"
43 #include "waypoint_base.h"
44 #include "waypoint_func.h"
45 #include "pbs.h"
46 #include "debug.h"
47 #include "core/random_func.hpp"
48 #include "core/container_func.hpp"
49 #include "company_base.h"
50 #include "table/airporttile_ids.h"
51 #include "newgrf_airporttiles.h"
52 #include "order_backup.h"
53 #include "newgrf_house.h"
54 #include "company_gui.h"
56 #include "linkgraph/refresh.h"
57 #include "widgets/station_widget.h"
58 #include "tunnelbridge_map.h"
59 #include "station_cmd.h"
60 #include "waypoint_cmd.h"
61 #include "landscape_cmd.h"
62 #include "rail_cmd.h"
63 #include "newgrf_roadstop.h"
64 #include "timer/timer.h"
67 #include "timer/timer_game_tick.h"
68 #include "cheat_type.h"
69 
70 #include "table/strings.h"
71 
72 #include <bitset>
73 
74 #include "safeguards.h"
75 
81 /* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
82 
89 bool IsHangar(Tile t)
90 {
91  assert(IsTileType(t, MP_STATION));
92 
93  /* If the tile isn't an airport there's no chance it's a hangar. */
94  if (!IsAirport(t)) return false;
95 
96  const Station *st = Station::GetByTile(t);
97  const AirportSpec *as = st->airport.GetSpec();
98 
99  for (uint i = 0; i < as->nof_depots; i++) {
100  if (st->airport.GetHangarTile(i) == TileIndex(t)) return true;
101  }
102 
103  return false;
104 }
105 
114 template <class T>
115 CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st)
116 {
117  ta.Expand(1);
118 
119  /* check around to see if there are any stations there owned by the company */
120  for (TileIndex tile_cur : ta) {
121  if (IsTileType(tile_cur, MP_STATION)) {
122  StationID t = GetStationIndex(tile_cur);
123  if (!T::IsValidID(t) || Station::Get(t)->owner != company) continue;
124  if (closest_station == INVALID_STATION) {
125  closest_station = t;
126  } else if (closest_station != t) {
127  return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
128  }
129  }
130  }
131  *st = (closest_station == INVALID_STATION) ? nullptr : T::Get(closest_station);
132  return CommandCost();
133 }
134 
140 typedef bool (*CMSAMatcher)(TileIndex tile);
141 
149 {
150  int num = 0;
151 
152  for (int dx = -3; dx <= 3; dx++) {
153  for (int dy = -3; dy <= 3; dy++) {
154  TileIndex t = TileAddWrap(tile, dx, dy);
155  if (t != INVALID_TILE && cmp(t)) num++;
156  }
157  }
158 
159  return num;
160 }
161 
167 static bool CMSAMine(TileIndex tile)
168 {
169  /* No industry */
170  if (!IsTileType(tile, MP_INDUSTRY)) return false;
171 
172  const Industry *ind = Industry::GetByTile(tile);
173 
174  /* No extractive industry */
175  if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
176 
177  for (const auto &p : ind->produced) {
178  /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
179  * Also the production of passengers and mail is ignored. */
180  if (IsValidCargoID(p.cargo) &&
181  (CargoSpec::Get(p.cargo)->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
182  return true;
183  }
184  }
185 
186  return false;
187 }
188 
194 static bool CMSAWater(TileIndex tile)
195 {
196  return IsTileType(tile, MP_WATER) && IsWater(tile);
197 }
198 
204 static bool CMSATree(TileIndex tile)
205 {
206  return IsTileType(tile, MP_TREES);
207 }
208 
209 #define M(x) ((x) - STR_SV_STNAME)
210 
211 enum StationNaming {
212  STATIONNAMING_RAIL,
213  STATIONNAMING_ROAD,
214  STATIONNAMING_AIRPORT,
215  STATIONNAMING_OILRIG,
216  STATIONNAMING_DOCK,
217  STATIONNAMING_HELIPORT,
218 };
219 
222  uint32_t free_names;
223  std::bitset<NUM_INDUSTRYTYPES> indtypes;
224 };
225 
234 static bool FindNearIndustryName(TileIndex tile, void *user_data)
235 {
236  /* All already found industry types */
238  if (!IsTileType(tile, MP_INDUSTRY)) return false;
239 
240  /* If the station name is undefined it means that it doesn't name a station */
241  IndustryType indtype = GetIndustryType(tile);
242  if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
243 
244  /* In all cases if an industry that provides a name is found two of
245  * the standard names will be disabled. */
246  sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
247  return !sni->indtypes[indtype];
248 }
249 
250 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
251 {
252  static const uint32_t _gen_station_name_bits[] = {
253  0, // STATIONNAMING_RAIL
254  0, // STATIONNAMING_ROAD
255  1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
256  1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
257  1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
258  1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
259  };
260 
261  const Town *t = st->town;
262 
264  sni.free_names = UINT32_MAX;
265 
266  for (const Station *s : Station::Iterate()) {
267  if (s != st && s->town == t) {
268  if (s->indtype != IT_INVALID) {
269  sni.indtypes[s->indtype] = true;
270  StringID name = GetIndustrySpec(s->indtype)->station_name;
271  if (name != STR_UNDEFINED) {
272  /* Filter for other industrytypes with the same name */
273  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
274  const IndustrySpec *indsp = GetIndustrySpec(it);
275  if (indsp->enabled && indsp->station_name == name) sni.indtypes[it] = true;
276  }
277  }
278  continue;
279  }
280  uint str = M(s->string_id);
281  if (str <= 0x20) {
282  if (str == M(STR_SV_STNAME_FOREST)) {
283  str = M(STR_SV_STNAME_WOODS);
284  }
285  ClrBit(sni.free_names, str);
286  }
287  }
288  }
289 
290  TileIndex indtile = tile;
291  if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
292  /* An industry has been found nearby */
293  IndustryType indtype = GetIndustryType(indtile);
294  const IndustrySpec *indsp = GetIndustrySpec(indtype);
295  /* STR_NULL means it only disables oil rig/mines */
296  if (indsp->station_name != STR_NULL) {
297  st->indtype = indtype;
298  return STR_SV_STNAME_FALLBACK;
299  }
300  }
301 
302  /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
303 
304  /* check default names */
305  uint32_t tmp = sni.free_names & _gen_station_name_bits[name_class];
306  if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
307 
308  /* check mine? */
309  if (HasBit(sni.free_names, M(STR_SV_STNAME_MINES))) {
310  if (CountMapSquareAround(tile, CMSAMine) >= 2) {
311  return STR_SV_STNAME_MINES;
312  }
313  }
314 
315  /* check close enough to town to get central as name? */
316  if (DistanceMax(tile, t->xy) < 8) {
317  if (HasBit(sni.free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
318 
319  if (HasBit(sni.free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
320  }
321 
322  /* Check lakeside */
323  if (HasBit(sni.free_names, M(STR_SV_STNAME_LAKESIDE)) &&
324  DistanceFromEdge(tile) < 20 &&
325  CountMapSquareAround(tile, CMSAWater) >= 5) {
326  return STR_SV_STNAME_LAKESIDE;
327  }
328 
329  /* Check woods */
330  if (HasBit(sni.free_names, M(STR_SV_STNAME_WOODS)) && (
331  CountMapSquareAround(tile, CMSATree) >= 8 ||
333  ) {
334  return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
335  }
336 
337  /* check elevation compared to town */
338  int z = GetTileZ(tile);
339  int z2 = GetTileZ(t->xy);
340  if (z < z2) {
341  if (HasBit(sni.free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
342  } else if (z > z2) {
343  if (HasBit(sni.free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
344  }
345 
346  /* check direction compared to town */
347  static const int8_t _direction_and_table[] = {
348  ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
349  ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
350  ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
351  ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
352  };
353 
354  sni.free_names &= _direction_and_table[
355  (TileX(tile) < TileX(t->xy)) +
356  (TileY(tile) < TileY(t->xy)) * 2];
357 
359  static const uint32_t fallback_names = (
360  (1U << M(STR_SV_STNAME_NORTH)) |
361  (1U << M(STR_SV_STNAME_SOUTH)) |
362  (1U << M(STR_SV_STNAME_EAST)) |
363  (1U << M(STR_SV_STNAME_WEST)) |
364  (1U << M(STR_SV_STNAME_TRANSFER)) |
365  (1U << M(STR_SV_STNAME_HALT)) |
366  (1U << M(STR_SV_STNAME_EXCHANGE)) |
367  (1U << M(STR_SV_STNAME_ANNEXE)) |
368  (1U << M(STR_SV_STNAME_SIDINGS)) |
369  (1U << M(STR_SV_STNAME_BRANCH)) |
370  (1U << M(STR_SV_STNAME_UPPER)) |
371  (1U << M(STR_SV_STNAME_LOWER))
372  );
373 
374  sni.free_names &= fallback_names;
375  return (sni.free_names == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(sni.free_names));
376 }
377 #undef M
378 
385 {
386  uint threshold = 8;
387 
388  Station *best_station = nullptr;
389  ForAllStationsRadius(tile, threshold, [&](Station *st) {
390  if (!st->IsInUse() && st->owner == _current_company) {
391  uint cur_dist = DistanceManhattan(tile, st->xy);
392 
393  if (cur_dist < threshold) {
394  threshold = cur_dist;
395  best_station = st;
396  } else if (cur_dist == threshold && best_station != nullptr) {
397  /* In case of a tie, lowest station ID wins */
398  if (st->index < best_station->index) best_station = st;
399  }
400  }
401  });
402 
403  return best_station;
404 }
405 
406 
408 {
409  switch (type) {
410  case STATION_RAIL:
411  *ta = this->train_station;
412  return;
413 
414  case STATION_AIRPORT:
415  *ta = this->airport;
416  return;
417 
418  case STATION_TRUCK:
419  *ta = this->truck_station;
420  return;
421 
422  case STATION_BUS:
423  *ta = this->bus_station;
424  return;
425 
426  case STATION_DOCK:
427  case STATION_OILRIG:
428  *ta = this->docking_station;
429  return;
430 
431  default: NOT_REACHED();
432  }
433 }
434 
439 {
440  Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
441 
442  pt.y -= 32 * ZOOM_LVL_BASE;
443  if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
444 
445  if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
446 
447  SetDParam(0, this->index);
448  SetDParam(1, this->facilities);
449  this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION, STR_VIEWPORT_STATION_TINY);
450 
451  _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
452 
454 }
455 
461 {
462  if (this->xy == new_xy) return;
463 
464  _station_kdtree.Remove(this->index);
465 
466  this->BaseStation::MoveSign(new_xy);
467 
468  _station_kdtree.Insert(this->index);
469 }
470 
473 {
474  for (BaseStation *st : BaseStation::Iterate()) {
475  st->UpdateVirtCoord();
476  }
477 }
478 
479 void BaseStation::FillCachedName() const
480 {
481  auto tmp_params = MakeParameters(this->index);
482  this->cached_name = GetStringWithArgs(Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, tmp_params);
483 }
484 
485 void ClearAllStationCachedNames()
486 {
487  for (BaseStation *st : BaseStation::Iterate()) {
488  st->cached_name.clear();
489  }
490 }
491 
497 CargoTypes GetAcceptanceMask(const Station *st)
498 {
499  CargoTypes mask = 0;
500 
501  for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
502  if (HasBit(it->status, GoodsEntry::GES_ACCEPTANCE)) SetBit(mask, std::distance(std::begin(st->goods), it));
503  }
504  return mask;
505 }
506 
512 CargoTypes GetEmptyMask(const Station *st)
513 {
514  CargoTypes mask = 0;
515 
516  for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
517  if (it->cargo.TotalCount() == 0) SetBit(mask, std::distance(std::begin(st->goods), it));
518  }
519  return mask;
520 }
521 
528 static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
529 {
530  SetDParam(0, st->index);
531  SetDParam(1, cargoes);
532  StringID msg = reject ? STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_LIST : STR_NEWS_STATION_NOW_ACCEPTS_CARGO_LIST;
534 }
535 
543 CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
544 {
545  CargoArray produced{};
546  std::set<IndustryID> industries;
547  TileArea ta = TileArea(north_tile, w, h).Expand(rad);
548 
549  /* Loop over all tiles to get the produced cargo of
550  * everything except industries */
551  for (TileIndex tile : ta) {
552  if (IsTileType(tile, MP_INDUSTRY)) industries.insert(GetIndustryIndex(tile));
553  AddProducedCargo(tile, produced);
554  }
555 
556  /* Loop over the seen industries. They produce cargo for
557  * anything that is within 'rad' of any one of their tiles.
558  */
559  for (IndustryID industry : industries) {
560  const Industry *i = Industry::Get(industry);
561  /* Skip industry with neutral station */
562  if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
563 
564  for (const auto &p : i->produced) {
565  if (IsValidCargoID(p.cargo)) produced[p.cargo]++;
566  }
567  }
568 
569  return produced;
570 }
571 
581 CargoArray GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad, CargoTypes *always_accepted)
582 {
583  CargoArray acceptance{};
584  if (always_accepted != nullptr) *always_accepted = 0;
585 
586  TileArea ta = TileArea(center_tile, w, h).Expand(rad);
587 
588  for (TileIndex tile : ta) {
589  /* Ignore industry if it has a neutral station. */
590  if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
591 
592  AddAcceptedCargo(tile, acceptance, always_accepted);
593  }
594 
595  return acceptance;
596 }
597 
603 static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
604 {
605  CargoArray acceptance{};
606  if (always_accepted != nullptr) *always_accepted = 0;
607 
609  for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
610  AddAcceptedCargo(tile, acceptance, always_accepted);
611  }
612 
613  return acceptance;
614 }
615 
621 void UpdateStationAcceptance(Station *st, bool show_msg)
622 {
623  /* old accepted goods types */
624  CargoTypes old_acc = GetAcceptanceMask(st);
625 
626  /* And retrieve the acceptance. */
627  CargoArray acceptance{};
628  if (!st->rect.IsEmpty()) {
629  acceptance = GetAcceptanceAroundStation(st, &st->always_accepted);
630  }
631 
632  /* Adjust in case our station only accepts fewer kinds of goods */
633  for (CargoID i = 0; i < NUM_CARGO; i++) {
634  uint amt = acceptance[i];
635 
636  /* Make sure the station can accept the goods type. */
637  bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
638  if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
639  (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
640  amt = 0;
641  }
642 
643  GoodsEntry &ge = st->goods[i];
644  SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
646  (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
647  }
648  }
649 
650  /* Only show a message in case the acceptance was actually changed. */
651  CargoTypes new_acc = GetAcceptanceMask(st);
652  if (old_acc == new_acc) return;
653 
654  /* show a message to report that the acceptance was changed? */
655  if (show_msg && st->owner == _local_company && st->IsInUse()) {
656  /* Combine old and new masks to get changes */
657  CargoTypes accepts = new_acc & ~old_acc;
658  CargoTypes rejects = ~new_acc & old_acc;
659 
660  /* Show news message if there are any changes */
661  if (accepts != 0) ShowRejectOrAcceptNews(st, accepts, false);
662  if (rejects != 0) ShowRejectOrAcceptNews(st, rejects, true);
663  }
664 
665  /* redraw the station view since acceptance changed */
667 }
668 
669 static void UpdateStationSignCoord(BaseStation *st)
670 {
671  const StationRect *r = &st->rect;
672 
673  if (r->IsEmpty()) return; // no tiles belong to this station
674 
675  /* clamp sign coord to be inside the station rect */
676  TileIndex new_xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
677  st->MoveSign(new_xy);
678 
679  if (!Station::IsExpected(st)) return;
680  Station *full_station = Station::From(st);
681  for (const GoodsEntry &ge : full_station->goods) {
682  LinkGraphID lg = ge.link_graph;
683  if (!LinkGraph::IsValidID(lg)) continue;
684  (*LinkGraph::Get(lg))[ge.node].UpdateLocation(st->xy);
685  }
686 }
687 
697 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
698 {
699  /* Find a deleted station close to us */
700  if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
701 
702  if (*st != nullptr) {
703  if ((*st)->owner != _current_company) {
705  }
706 
707  CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
708  if (ret.Failed()) return ret;
709  } else {
710  /* allocate and initialize new station */
711  if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
712 
713  if (flags & DC_EXEC) {
714  *st = new Station(area.tile);
715  _station_kdtree.Insert((*st)->index);
716 
717  (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
718  (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
719 
721  SetBit((*st)->town->have_ratings, _current_company);
722  }
723  }
724  }
725  return CommandCost();
726 }
727 
735 {
736  if (!st->IsInUse()) {
737  st->delete_ctr = 0;
739  }
740  /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
741  UpdateStationSignCoord(st);
742 }
743 
750 {
751  this->UpdateVirtCoord();
753 
754  if (adding) {
755  this->RecomputeCatchment();
756  MarkCatchmentTilesDirty();
758  } else {
759  MarkCatchmentTilesDirty();
760  }
761 
762  switch (type) {
763  case STATION_RAIL:
765  break;
766  case STATION_AIRPORT:
767  break;
768  case STATION_TRUCK:
769  case STATION_BUS:
771  break;
772  case STATION_DOCK:
774  break;
775  default: NOT_REACHED();
776  }
777 
778  if (adding) {
779  UpdateStationAcceptance(this, false);
781  } else {
782  DeleteStationIfEmpty(this);
783  this->RecomputeCatchment();
784  }
785 
786 }
787 
789 
799 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
800 {
801  if (check_bridge && IsBridgeAbove(tile)) {
802  return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
803  }
804 
806  if (ret.Failed()) return ret;
807 
808  int z;
809  Slope tileh = GetTileSlope(tile, &z);
810 
811  /* Prohibit building if
812  * 1) The tile is "steep" (i.e. stretches two height levels).
813  * 2) The tile is non-flat and the build_on_slopes switch is disabled.
814  */
815  if ((!allow_steep && IsSteepSlope(tileh)) ||
817  return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
818  }
819 
821  int flat_z = z + GetSlopeMaxZ(tileh);
822  if (tileh != SLOPE_FLAT) {
823  /* Forbid building if the tile faces a slope in a invalid direction. */
824  for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
825  if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
826  return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
827  }
828  }
829  cost.AddCost(_price[PR_BUILD_FOUNDATION]);
830  }
831 
832  /* The level of this tile must be equal to allowed_z. */
833  if (allowed_z < 0) {
834  /* First tile. */
835  allowed_z = flat_z;
836  } else if (allowed_z != flat_z) {
837  return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
838  }
839 
840  return cost;
841 }
842 
850 {
852  int allowed_z = -1;
853 
854  for (; tile_iter != INVALID_TILE; ++tile_iter) {
855  CommandCost ret = CheckBuildableTile(tile_iter, 0, allowed_z, true);
856  if (ret.Failed()) return ret;
857  cost.AddCost(ret);
858 
859  ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_iter);
860  if (ret.Failed()) return ret;
861  cost.AddCost(ret);
862  }
863 
864  return cost;
865 }
866 
883 static CommandCost CheckFlatLandRailStation(TileIndex tile_cur, TileIndex north_tile, int &allowed_z, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, byte plat_len, byte numtracks)
884 {
886  uint invalid_dirs = 5 << axis;
887 
888  const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
889  bool slope_cb = statspec != nullptr && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
890 
891  CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
892  if (ret.Failed()) return ret;
893  cost.AddCost(ret);
894 
895  if (slope_cb) {
896  /* Do slope check if requested. */
897  ret = PerformStationTileSlopeCheck(north_tile, tile_cur, statspec, axis, plat_len, numtracks);
898  if (ret.Failed()) return ret;
899  }
900 
901  /* if station is set, then we have special handling to allow building on top of already existing stations.
902  * so station points to INVALID_STATION if we can build on any station.
903  * Or it points to a station if we're only allowed to build on exactly that station. */
904  if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
905  if (!IsRailStation(tile_cur)) {
906  return ClearTile_Station(tile_cur, DC_AUTO); // get error message
907  } else {
908  StationID st = GetStationIndex(tile_cur);
909  if (*station == INVALID_STATION) {
910  *station = st;
911  } else if (*station != st) {
912  return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
913  }
914  }
915  } else {
916  /* Rail type is only valid when building a railway station; if station to
917  * build isn't a rail station it's INVALID_RAILTYPE. */
918  if (rt != INVALID_RAILTYPE &&
919  IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
920  HasPowerOnRail(GetRailType(tile_cur), rt)) {
921  /* Allow overbuilding if the tile:
922  * - has rail, but no signals
923  * - it has exactly one track
924  * - the track is in line with the station
925  * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
926  */
927  TrackBits tracks = GetTrackBits(tile_cur);
928  Track track = RemoveFirstTrack(&tracks);
929  Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
930 
931  if (tracks == TRACK_BIT_NONE && track == expected_track) {
932  /* Check for trains having a reservation for this tile. */
933  if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
934  Train *v = GetTrainForReservation(tile_cur, track);
935  if (v != nullptr) {
936  affected_vehicles.push_back(v);
937  }
938  }
939  ret = Command<CMD_REMOVE_SINGLE_RAIL>::Do(flags, tile_cur, track);
940  if (ret.Failed()) return ret;
941  cost.AddCost(ret);
942  /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
943  return cost;
944  }
945  }
946  ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
947  if (ret.Failed()) return ret;
948  cost.AddCost(ret);
949  }
950 
951  return cost;
952 }
953 
967 static CommandCost CheckFlatLandRoadStop(TileIndex cur_tile, int &allowed_z, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadType rt)
968 {
970 
971  CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
972  if (ret.Failed()) return ret;
973  cost.AddCost(ret);
974 
975  /* If station is set, then we have special handling to allow building on top of already existing stations.
976  * Station points to INVALID_STATION if we can build on any station.
977  * Or it points to a station if we're only allowed to build on exactly that station. */
978  if (station != nullptr && IsTileType(cur_tile, MP_STATION)) {
979  if (!IsRoadStop(cur_tile)) {
980  return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
981  } else {
982  if (is_truck_stop != IsTruckStop(cur_tile) ||
983  is_drive_through != IsDriveThroughStopTile(cur_tile)) {
984  return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
985  }
986  /* Drive-through station in the wrong direction. */
987  if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
988  return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
989  }
990  StationID st = GetStationIndex(cur_tile);
991  if (*station == INVALID_STATION) {
992  *station = st;
993  } else if (*station != st) {
994  return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
995  }
996  }
997  } else {
998  bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
999  /* Road bits in the wrong direction. */
1000  RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
1001  if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
1002  /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1003  switch (CountBits(rb)) {
1004  case 1:
1005  return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1006 
1007  case 2:
1008  if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1009  return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
1010 
1011  default: // 3 or 4
1012  return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1013  }
1014  }
1015 
1016  if (build_over_road) {
1017  /* There is a road, check if we can build road+tram stop over it. */
1018  RoadType road_rt = GetRoadType(cur_tile, RTT_ROAD);
1019  if (road_rt != INVALID_ROADTYPE) {
1020  Owner road_owner = GetRoadOwner(cur_tile, RTT_ROAD);
1021  if (road_owner == OWNER_TOWN) {
1022  if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1023  } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1024  ret = CheckOwnership(road_owner);
1025  if (ret.Failed()) return ret;
1026  }
1027  uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_ROAD));
1028 
1029  if (RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1030 
1031  if (GetDisallowedRoadDirections(cur_tile) != DRD_NONE && road_owner != OWNER_TOWN) {
1032  ret = CheckOwnership(road_owner);
1033  if (ret.Failed()) return ret;
1034  }
1035 
1036  cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1037  } else if (RoadTypeIsRoad(rt)) {
1038  cost.AddCost(RoadBuildCost(rt) * 2);
1039  }
1040 
1041  /* There is a tram, check if we can build road+tram stop over it. */
1042  RoadType tram_rt = GetRoadType(cur_tile, RTT_TRAM);
1043  if (tram_rt != INVALID_ROADTYPE) {
1044  Owner tram_owner = GetRoadOwner(cur_tile, RTT_TRAM);
1045  if (Company::IsValidID(tram_owner) &&
1047  /* Disallow breaking end-of-line of someone else
1048  * so trams can still reverse on this tile. */
1049  HasExactlyOneBit(GetRoadBits(cur_tile, RTT_TRAM)))) {
1050  ret = CheckOwnership(tram_owner);
1051  if (ret.Failed()) return ret;
1052  }
1053  uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_TRAM));
1054 
1055  if (RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1056 
1057  cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1058  } else if (RoadTypeIsTram(rt)) {
1059  cost.AddCost(RoadBuildCost(rt) * 2);
1060  }
1061  } else {
1062  ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, cur_tile);
1063  if (ret.Failed()) return ret;
1064  cost.AddCost(ret);
1065  cost.AddCost(RoadBuildCost(rt) * 2);
1066  }
1067  }
1068 
1069  return cost;
1070 }
1071 
1079 {
1080  TileArea cur_ta = st->train_station;
1081 
1082  /* determine new size of train station region.. */
1083  int x = std::min(TileX(cur_ta.tile), TileX(new_ta.tile));
1084  int y = std::min(TileY(cur_ta.tile), TileY(new_ta.tile));
1085  new_ta.w = std::max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1086  new_ta.h = std::max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1087  new_ta.tile = TileXY(x, y);
1088 
1089  /* make sure the final size is not too big. */
1091  return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1092  }
1093 
1094  return CommandCost();
1095 }
1096 
1097 static inline byte *CreateSingle(byte *layout, int n)
1098 {
1099  int i = n;
1100  do *layout++ = 0; while (--i);
1101  layout[((n - 1) >> 1) - n] = 2;
1102  return layout;
1103 }
1104 
1105 static inline byte *CreateMulti(byte *layout, int n, byte b)
1106 {
1107  int i = n;
1108  do *layout++ = b; while (--i);
1109  if (n > 4) {
1110  layout[0 - n] = 0;
1111  layout[n - 1 - n] = 0;
1112  }
1113  return layout;
1114 }
1115 
1123 void GetStationLayout(byte *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
1124 {
1125  if (statspec != nullptr && statspec->layouts.size() >= plat_len &&
1126  statspec->layouts[plat_len - 1].size() >= numtracks &&
1127  !statspec->layouts[plat_len - 1][numtracks - 1].empty()) {
1128  /* Custom layout defined, follow it. */
1129  memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1].data(),
1130  static_cast<size_t>(plat_len) * numtracks);
1131  return;
1132  }
1133 
1134  if (plat_len == 1) {
1135  CreateSingle(layout, numtracks);
1136  } else {
1137  if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1138  int n = numtracks >> 1;
1139 
1140  while (--n >= 0) {
1141  layout = CreateMulti(layout, plat_len, 4);
1142  layout = CreateMulti(layout, plat_len, 6);
1143  }
1144  }
1145 }
1146 
1158 template <class T, StringID error_message>
1159 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
1160 {
1161  assert(*st == nullptr);
1162  bool check_surrounding = true;
1163 
1165  if (existing_station != INVALID_STATION) {
1166  if (adjacent && existing_station != station_to_join) {
1167  /* You can't build an adjacent station over the top of one that
1168  * already exists. */
1169  return_cmd_error(error_message);
1170  } else {
1171  /* Extend the current station, and don't check whether it will
1172  * be near any other stations. */
1173  *st = T::GetIfValid(existing_station);
1174  check_surrounding = (*st == nullptr);
1175  }
1176  } else {
1177  /* There's no station here. Don't check the tiles surrounding this
1178  * one if the company wanted to build an adjacent station. */
1179  if (adjacent) check_surrounding = false;
1180  }
1181  }
1182 
1183  if (check_surrounding) {
1184  /* Make sure there is no more than one other station around us that is owned by us. */
1185  CommandCost ret = GetStationAround(ta, existing_station, _current_company, st);
1186  if (ret.Failed()) return ret;
1187  }
1188 
1189  /* Distant join */
1190  if (*st == nullptr && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1191 
1192  return CommandCost();
1193 }
1194 
1204 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1205 {
1206  return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
1207 }
1208 
1218 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
1219 {
1220  return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
1221 }
1222 
1228 {
1231  v = v->Last();
1233 }
1234 
1240 {
1242  TryPathReserve(v, true, true);
1243  v = v->Last();
1245 }
1246 
1261 static CommandCost CalculateRailStationCost(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, byte plat_len, byte numtracks)
1262 {
1264  bool length_price_ready = true;
1265  byte tracknum = 0;
1266  int allowed_z = -1;
1267  for (TileIndex cur_tile : tile_area) {
1268  /* Clear the land below the station. */
1269  CommandCost ret = CheckFlatLandRailStation(cur_tile, tile_area.tile, allowed_z, flags, axis, station, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1270  if (ret.Failed()) return ret;
1271 
1272  /* Only add _price[PR_BUILD_STATION_RAIL_LENGTH] once for each valid plat_len. */
1273  if (tracknum == numtracks) {
1274  length_price_ready = true;
1275  tracknum = 0;
1276  } else {
1277  tracknum++;
1278  }
1279 
1280  /* AddCost for new or rotated rail stations. */
1281  if (!IsRailStationTile(cur_tile) || (IsRailStationTile(cur_tile) && GetRailStationAxis(cur_tile) != axis)) {
1282  cost.AddCost(ret);
1283  cost.AddCost(_price[PR_BUILD_STATION_RAIL]);
1284  cost.AddCost(RailBuildCost(rt));
1285 
1286  if (length_price_ready) {
1287  cost.AddCost(_price[PR_BUILD_STATION_RAIL_LENGTH]);
1288  length_price_ready = false;
1289  }
1290  }
1291  }
1292 
1293  return cost;
1294 }
1295 
1310 CommandCost CmdBuildRailStation(DoCommandFlag flags, TileIndex tile_org, RailType rt, Axis axis, byte numtracks, byte plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1311 {
1312  /* Does the authority allow this? */
1313  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1314  if (ret.Failed()) return ret;
1315 
1316  if (!ValParamRailType(rt) || !IsValidAxis(axis)) return CMD_ERROR;
1317 
1318  /* Check if the given station class is valid */
1319  if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
1320  if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
1321  if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1322 
1323  int w_org, h_org;
1324  if (axis == AXIS_X) {
1325  w_org = plat_len;
1326  h_org = numtracks;
1327  } else {
1328  h_org = plat_len;
1329  w_org = numtracks;
1330  }
1331 
1332  bool reuse = (station_to_join != NEW_STATION);
1333  if (!reuse) station_to_join = INVALID_STATION;
1334  bool distant_join = (station_to_join != INVALID_STATION);
1335 
1336  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1337 
1339 
1340  /* these values are those that will be stored in train_tile and station_platforms */
1341  TileArea new_location(tile_org, w_org, h_org);
1342 
1343  /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1344  StationID est = INVALID_STATION;
1345  std::vector<Train *> affected_vehicles;
1346  /* Add construction and clearing expenses. */
1347  CommandCost cost = CalculateRailStationCost(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1348  if (cost.Failed()) return cost;
1349 
1350  Station *st = nullptr;
1351  ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1352  if (ret.Failed()) return ret;
1353 
1354  ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1355  if (ret.Failed()) return ret;
1356 
1357  if (st != nullptr && st->train_station.tile != INVALID_TILE) {
1358  ret = CanExpandRailStation(st, new_location);
1359  if (ret.Failed()) return ret;
1360  }
1361 
1362  /* Check if we can allocate a custom stationspec to this station */
1363  const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1364  int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1365  if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1366 
1367  if (statspec != nullptr) {
1368  /* Perform NewStation checks */
1369 
1370  /* Check if the station size is permitted */
1371  if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) {
1372  return CMD_ERROR;
1373  }
1374 
1375  /* Check if the station is buildable */
1376  if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1377  uint16_t cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1378  if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1379  }
1380  }
1381 
1382  if (flags & DC_EXEC) {
1383  TileIndexDiff tile_delta;
1384  byte numtracks_orig;
1385  Track track;
1386 
1387  st->train_station = new_location;
1388  st->AddFacility(FACIL_TRAIN, new_location.tile);
1389 
1390  st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1391 
1392  if (statspec != nullptr) {
1393  /* Include this station spec's animation trigger bitmask
1394  * in the station's cached copy. */
1395  st->cached_anim_triggers |= statspec->animation.triggers;
1396  }
1397 
1398  tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1399  track = AxisToTrack(axis);
1400 
1401  std::vector<byte> layouts(numtracks * plat_len);
1402  GetStationLayout(layouts.data(), numtracks, plat_len, statspec);
1403 
1404  numtracks_orig = numtracks;
1405 
1406  Company *c = Company::Get(st->owner);
1407  size_t layout_idx = 0;
1408  TileIndex tile_track = tile_org;
1409  do {
1410  TileIndex tile = tile_track;
1411  int w = plat_len;
1412  do {
1413  byte layout = layouts[layout_idx++];
1414  if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1415  /* Check for trains having a reservation for this tile. */
1417  if (v != nullptr) {
1418  affected_vehicles.push_back(v);
1420  }
1421  }
1422 
1423  /* Railtype can change when overbuilding. */
1424  if (IsRailStationTile(tile)) {
1425  if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1426  c->infrastructure.station--;
1427  }
1428 
1429  /* Remove animation if overbuilding */
1430  DeleteAnimatedTile(tile);
1431  byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1432  MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1433  /* Free the spec if we overbuild something */
1434  DeallocateSpecFromStation(st, old_specindex);
1435 
1436  SetCustomStationSpecIndex(tile, specindex);
1437  SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1438  SetAnimationFrame(tile, 0);
1439 
1440  if (statspec != nullptr) {
1441  /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1442  uint32_t platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1443 
1444  /* As the station is not yet completely finished, the station does not yet exist. */
1445  uint16_t callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1446  if (callback != CALLBACK_FAILED) {
1447  if (callback < 8) {
1448  SetStationGfx(tile, (callback & ~1) + axis);
1449  } else {
1451  }
1452  }
1453 
1454  /* Trigger station animation -- after building? */
1455  TriggerStationAnimation(st, tile, SAT_BUILT);
1456  }
1457 
1458  /* Should be the same as layout but axis component could be wrong... */
1459  StationGfx gfx = GetStationGfx(tile);
1460  bool blocked = statspec != nullptr && HasBit(statspec->blocked, gfx);
1461  /* Default stations do not draw pylons under roofs (gfx >= 4) */
1462  bool pylons = statspec != nullptr ? HasBit(statspec->pylons, gfx) : gfx < 4;
1463  bool wires = statspec == nullptr || !HasBit(statspec->wires, gfx);
1464 
1465  SetStationTileBlocked(tile, blocked);
1466  SetStationTileHavePylons(tile, pylons);
1467  SetStationTileHaveWires(tile, wires);
1468 
1469  if (!blocked) c->infrastructure.rail[rt]++;
1470  c->infrastructure.station++;
1471 
1472  tile += tile_delta;
1473  } while (--w);
1474  AddTrackToSignalBuffer(tile_track, track, _current_company);
1475  YapfNotifyTrackLayoutChange(tile_track, track);
1476  tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1477  } while (--numtracks);
1478 
1479  for (uint i = 0; i < affected_vehicles.size(); ++i) {
1480  /* Restore reservations of trains. */
1481  RestoreTrainReservation(affected_vehicles[i]);
1482  }
1483 
1484  /* Check whether we need to expand the reservation of trains already on the station. */
1485  TileArea update_reservation_area;
1486  if (axis == AXIS_X) {
1487  update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1488  } else {
1489  update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1490  }
1491 
1492  for (TileIndex tile : update_reservation_area) {
1493  /* Don't even try to make eye candy parts reserved. */
1494  if (IsStationTileBlocked(tile)) continue;
1495 
1496  DiagDirection dir = AxisToDiagDir(axis);
1497  TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1498  TileIndex platform_begin = tile;
1499  TileIndex platform_end = tile;
1500 
1501  /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1502  for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1503  platform_begin = next_tile;
1504  }
1505  for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1506  platform_end = next_tile;
1507  }
1508 
1509  /* If there is at least on reservation on the platform, we reserve the whole platform. */
1510  bool reservation = false;
1511  for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1512  reservation = HasStationReservation(t);
1513  }
1514 
1515  if (reservation) {
1516  SetRailStationPlatformReservation(platform_begin, dir, true);
1517  }
1518  }
1519 
1520  st->MarkTilesDirty(false);
1521  st->AfterStationTileSetChange(true, STATION_RAIL);
1522  }
1523 
1524  return cost;
1525 }
1526 
1527 static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1528 {
1529 restart:
1530 
1531  /* too small? */
1532  if (ta.w != 0 && ta.h != 0) {
1533  /* check the left side, x = constant, y changes */
1534  for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1535  /* the left side is unused? */
1536  if (++i == ta.h) {
1537  ta.tile += TileDiffXY(1, 0);
1538  ta.w--;
1539  goto restart;
1540  }
1541  }
1542 
1543  /* check the right side, x = constant, y changes */
1544  for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1545  /* the right side is unused? */
1546  if (++i == ta.h) {
1547  ta.w--;
1548  goto restart;
1549  }
1550  }
1551 
1552  /* check the upper side, y = constant, x changes */
1553  for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1554  /* the left side is unused? */
1555  if (++i == ta.w) {
1556  ta.tile += TileDiffXY(0, 1);
1557  ta.h--;
1558  goto restart;
1559  }
1560  }
1561 
1562  /* check the lower side, y = constant, x changes */
1563  for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1564  /* the left side is unused? */
1565  if (++i == ta.w) {
1566  ta.h--;
1567  goto restart;
1568  }
1569  }
1570  } else {
1571  ta.Clear();
1572  }
1573 
1574  return ta;
1575 }
1576 
1577 static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1578 {
1579  return st->TileBelongsToRailStation(tile);
1580 }
1581 
1582 static void MakeRailStationAreaSmaller(BaseStation *st)
1583 {
1584  st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1585 }
1586 
1587 static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1588 {
1589  return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1590 }
1591 
1592 static void MakeShipStationAreaSmaller(Station *st)
1593 {
1594  st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1595  UpdateStationDockingTiles(st);
1596 }
1597 
1608 template <class T>
1609 CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1610 {
1611  /* Count of the number of tiles removed */
1612  int quantity = 0;
1613  CommandCost total_cost(EXPENSES_CONSTRUCTION);
1614  /* Accumulator for the errors seen during clearing. If no errors happen,
1615  * and the quantity is 0 there is no station. Otherwise it will be one
1616  * of the other error that got accumulated. */
1617  CommandCost error;
1618 
1619  /* Do the action for every tile into the area */
1620  for (TileIndex tile : ta) {
1621  /* Make sure the specified tile is a rail station */
1622  if (!HasStationTileRail(tile)) continue;
1623 
1624  /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1626  error.AddCost(ret);
1627  if (ret.Failed()) continue;
1628 
1629  /* Check ownership of station */
1630  T *st = T::GetByTile(tile);
1631  if (st == nullptr) continue;
1632 
1633  if (_current_company != OWNER_WATER) {
1634  ret = CheckOwnership(st->owner);
1635  error.AddCost(ret);
1636  if (ret.Failed()) continue;
1637  }
1638 
1639  /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1640  quantity++;
1641 
1642  if (keep_rail || IsStationTileBlocked(tile)) {
1643  /* Don't refund the 'steel' of the track when we keep the
1644  * rail, or when the tile didn't have any rail at all. */
1645  total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1646  }
1647 
1648  if (flags & DC_EXEC) {
1649  /* read variables before the station tile is removed */
1650  uint specindex = GetCustomStationSpecIndex(tile);
1651  Track track = GetRailStationTrack(tile);
1652  Owner owner = GetTileOwner(tile);
1653  RailType rt = GetRailType(tile);
1654  Train *v = nullptr;
1655 
1656  if (HasStationReservation(tile)) {
1657  v = GetTrainForReservation(tile, track);
1658  if (v != nullptr) FreeTrainReservation(v);
1659  }
1660 
1661  bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1662  if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1663 
1664  DoClearSquare(tile);
1665  DeleteNewGRFInspectWindow(GSF_STATIONS, tile.base());
1666  if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1667  Company::Get(owner)->infrastructure.station--;
1669 
1670  st->rect.AfterRemoveTile(st, tile);
1671  AddTrackToSignalBuffer(tile, track, owner);
1672  YapfNotifyTrackLayoutChange(tile, track);
1673 
1674  DeallocateSpecFromStation(st, specindex);
1675 
1676  include(affected_stations, st);
1677 
1678  if (v != nullptr) RestoreTrainReservation(v);
1679  }
1680  }
1681 
1682  if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1683 
1684  for (T *st : affected_stations) {
1685 
1686  /* now we need to make the "spanned" area of the railway station smaller
1687  * if we deleted something at the edges.
1688  * we also need to adjust train_tile. */
1689  MakeRailStationAreaSmaller(st);
1690  UpdateStationSignCoord(st);
1691 
1692  /* if we deleted the whole station, delete the train facility. */
1693  if (st->train_station.tile == INVALID_TILE) {
1694  st->facilities &= ~FACIL_TRAIN;
1697  MarkCatchmentTilesDirty();
1698  st->UpdateVirtCoord();
1700  }
1701  }
1702 
1703  total_cost.AddCost(quantity * removal_cost);
1704  return total_cost;
1705 }
1706 
1717 {
1718  if (end == 0) end = start;
1719  if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1720 
1721  TileArea ta(start, end);
1722  std::vector<Station *> affected_stations;
1723 
1724  CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], keep_rail);
1725  if (ret.Failed()) return ret;
1726 
1727  /* Do all station specific functions here. */
1728  for (Station *st : affected_stations) {
1729 
1731  st->MarkTilesDirty(false);
1732  MarkCatchmentTilesDirty();
1733  st->RecomputeCatchment();
1734  }
1735 
1736  /* Now apply the rail cost to the number that we deleted */
1737  return ret;
1738 }
1739 
1750 {
1751  if (end == 0) end = start;
1752  if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1753 
1754  TileArea ta(start, end);
1755  std::vector<Waypoint *> affected_stations;
1756 
1757  return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], keep_rail);
1758 }
1759 
1760 
1769 template <class T>
1771 {
1772  /* Current company owns the station? */
1773  if (_current_company != OWNER_WATER) {
1774  CommandCost ret = CheckOwnership(st->owner);
1775  if (ret.Failed()) return ret;
1776  }
1777 
1778  /* determine width and height of platforms */
1779  TileArea ta = st->train_station;
1780 
1781  assert(ta.w != 0 && ta.h != 0);
1782 
1784  /* clear all areas of the station */
1785  for (TileIndex tile : ta) {
1786  /* only remove tiles that are actually train station tiles */
1787  if (st->TileBelongsToRailStation(tile)) {
1788  std::vector<T*> affected_stations; // dummy
1789  CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1790  if (ret.Failed()) return ret;
1791  cost.AddCost(ret);
1792  }
1793  }
1794 
1795  return cost;
1796 }
1797 
1805 {
1806  /* if there is flooding, remove platforms tile by tile */
1807  if (_current_company == OWNER_WATER) {
1808  return Command<CMD_REMOVE_FROM_RAIL_STATION>::Do(DC_EXEC, tile, 0, false);
1809  }
1810 
1811  Station *st = Station::GetByTile(tile);
1812  CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1813 
1814  if (flags & DC_EXEC) st->RecomputeCatchment();
1815 
1816  return cost;
1817 }
1818 
1826 {
1827  /* if there is flooding, remove waypoints tile by tile */
1828  if (_current_company == OWNER_WATER) {
1829  return Command<CMD_REMOVE_FROM_RAIL_WAYPOINT>::Do(DC_EXEC, tile, 0, false);
1830  }
1831 
1832  return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1833 }
1834 
1835 
1841 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1842 {
1843  RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1844 
1845  if (*primary_stop == nullptr) {
1846  /* we have no roadstop of the type yet, so write a "primary stop" */
1847  return primary_stop;
1848  } else {
1849  /* there are stops already, so append to the end of the list */
1850  RoadStop *stop = *primary_stop;
1851  while (stop->next != nullptr) stop = stop->next;
1852  return &stop->next;
1853  }
1854 }
1855 
1856 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
1857 
1867 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1868 {
1869  return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
1870 }
1871 
1885 static CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlag flags, bool is_drive_through, bool is_truck_stop, Axis axis, DiagDirection ddir, StationID *est, RoadType rt, Money unit_cost)
1886 {
1887  uint invalid_dirs = 0;
1888  if (is_drive_through) {
1889  SetBit(invalid_dirs, AxisToDiagDir(axis));
1890  SetBit(invalid_dirs, ReverseDiagDir(AxisToDiagDir(axis)));
1891  } else {
1892  SetBit(invalid_dirs, ddir);
1893  }
1894 
1895  /* Check every tile in the area. */
1896  int allowed_z = -1;
1898  for (TileIndex cur_tile : tile_area) {
1899  CommandCost ret = CheckFlatLandRoadStop(cur_tile, allowed_z, flags, invalid_dirs, is_drive_through, is_truck_stop, axis, est, rt);
1900  if (ret.Failed()) return ret;
1901 
1902  bool is_preexisting_roadstop = IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile);
1903 
1904  /* Only add costs if a stop doesn't already exist in the location */
1905  if (!is_preexisting_roadstop) {
1906  cost.AddCost(ret);
1907  cost.AddCost(unit_cost);
1908  }
1909  }
1910 
1911  return cost;
1912 }
1913 
1930 CommandCost CmdBuildRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through,
1931  DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1932 {
1933  if (!ValParamRoadType(rt) || !IsValidDiagDirection(ddir) || stop_type >= ROADSTOP_END) return CMD_ERROR;
1934  bool reuse = (station_to_join != NEW_STATION);
1935  if (!reuse) station_to_join = INVALID_STATION;
1936  bool distant_join = (station_to_join != INVALID_STATION);
1937 
1938  /* Check if the given station class is valid */
1939  if ((uint)spec_class >= RoadStopClass::GetClassCount() || spec_class == ROADSTOP_CLASS_WAYP) return CMD_ERROR;
1940  if (spec_index >= RoadStopClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
1941 
1942  const RoadStopSpec *roadstopspec = RoadStopClass::Get(spec_class)->GetSpec(spec_index);
1943  if (roadstopspec != nullptr) {
1944  if (stop_type == ROADSTOP_TRUCK && roadstopspec->stop_type != ROADSTOPTYPE_FREIGHT && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1945  if (stop_type == ROADSTOP_BUS && roadstopspec->stop_type != ROADSTOPTYPE_PASSENGER && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1946  if (!is_drive_through && HasBit(roadstopspec->flags, RSF_DRIVE_THROUGH_ONLY)) return CMD_ERROR;
1947  }
1948 
1949  /* Check if the requested road stop is too big */
1950  if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1951  /* Check for incorrect width / length. */
1952  if (width == 0 || length == 0) return CMD_ERROR;
1953  /* Check if the first tile and the last tile are valid */
1954  if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
1955 
1956  TileArea roadstop_area(tile, width, length);
1957 
1958  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1959 
1960  /* Trams only have drive through stops */
1961  if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
1962 
1963  Axis axis = DiagDirToAxis(ddir);
1964 
1965  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
1966  if (ret.Failed()) return ret;
1967 
1968  bool is_truck_stop = stop_type != ROADSTOP_BUS;
1969 
1970  /* Total road stop cost. */
1971  Money unit_cost;
1972  if (roadstopspec != nullptr) {
1973  unit_cost = roadstopspec->GetBuildCost(is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS);
1974  } else {
1975  unit_cost = _price[is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS];
1976  }
1977  StationID est = INVALID_STATION;
1978  CommandCost cost = CalculateRoadStopCost(roadstop_area, flags, is_drive_through, is_truck_stop, axis, ddir, &est, rt, unit_cost);
1979  if (cost.Failed()) return cost;
1980 
1981  Station *st = nullptr;
1982  ret = FindJoiningRoadStop(est, station_to_join, adjacent, roadstop_area, &st);
1983  if (ret.Failed()) return ret;
1984 
1985  /* Check if this number of road stops can be allocated. */
1986  if (!RoadStop::CanAllocateItem(static_cast<size_t>(roadstop_area.w) * roadstop_area.h)) return_cmd_error(is_truck_stop ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
1987 
1988  ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
1989  if (ret.Failed()) return ret;
1990 
1991  /* Check if we can allocate a custom stationspec to this station */
1992  int specindex = AllocateSpecToRoadStop(roadstopspec, st, (flags & DC_EXEC) != 0);
1993  if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1994 
1995  if (roadstopspec != nullptr) {
1996  /* Perform NewGRF checks */
1997 
1998  /* Check if the road stop is buildable */
1999  if (HasBit(roadstopspec->callback_mask, CBM_ROAD_STOP_AVAIL)) {
2000  uint16_t cb_res = GetRoadStopCallback(CBID_STATION_AVAILABILITY, 0, 0, roadstopspec, nullptr, INVALID_TILE, rt, is_truck_stop ? STATION_TRUCK : STATION_BUS, 0);
2001  if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(roadstopspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
2002  }
2003  }
2004 
2005  if (flags & DC_EXEC) {
2006  /* Check every tile in the area. */
2007  for (TileIndex cur_tile : roadstop_area) {
2008  /* Get existing road types and owners before any tile clearing */
2009  RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_ROAD) : INVALID_ROADTYPE;
2010  RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_TRAM) : INVALID_ROADTYPE;
2011  Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_ROAD) : _current_company;
2012  Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_TRAM) : _current_company;
2013 
2014  if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
2015  RemoveRoadStop(cur_tile, flags, specindex);
2016  }
2017 
2018  if (roadstopspec != nullptr) {
2019  /* Include this road stop spec's animation trigger bitmask
2020  * in the station's cached copy. */
2021  st->cached_roadstop_anim_triggers |= roadstopspec->animation.triggers;
2022  }
2023 
2024  RoadStop *road_stop = new RoadStop(cur_tile);
2025  /* Insert into linked list of RoadStops. */
2026  RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
2027  *currstop = road_stop;
2028 
2029  if (is_truck_stop) {
2030  st->truck_station.Add(cur_tile);
2031  } else {
2032  st->bus_station.Add(cur_tile);
2033  }
2034 
2035  /* Initialize an empty station. */
2036  st->AddFacility(is_truck_stop ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
2037 
2038  st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
2039 
2040  RoadStopType rs_type = is_truck_stop ? ROADSTOP_TRUCK : ROADSTOP_BUS;
2041  if (is_drive_through) {
2042  /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2043  * bits first. */
2044  if (IsNormalRoadTile(cur_tile)) {
2045  UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD)));
2046  UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM)));
2047  }
2048 
2049  if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2050  if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2051 
2052  MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, road_rt, tram_rt, axis);
2053  road_stop->MakeDriveThrough();
2054  } else {
2055  if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2056  if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2057  MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
2058  }
2061  Company::Get(st->owner)->infrastructure.station++;
2062 
2063  SetCustomRoadStopSpecIndex(cur_tile, specindex);
2064  if (roadstopspec != nullptr) {
2065  st->SetRoadStopRandomBits(cur_tile, GB(Random(), 0, 8));
2066  TriggerRoadStopAnimation(st, cur_tile, SAT_BUILT);
2067  }
2068 
2069  MarkTileDirtyByTile(cur_tile);
2070  }
2071 
2072  if (st != nullptr) {
2073  st->AfterStationTileSetChange(true, is_truck_stop ? STATION_TRUCK: STATION_BUS);
2074  }
2075  }
2076  return cost;
2077 }
2078 
2079 
2080 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
2081 {
2082  if (v->type == VEH_ROAD) {
2083  /* Okay... we are a road vehicle on a drive through road stop.
2084  * But that road stop has just been removed, so we need to make
2085  * sure we are in a valid state... however, vehicles can also
2086  * turn on road stop tiles, so only clear the 'road stop' state
2087  * bits and only when the state was 'in road stop', otherwise
2088  * we'll end up clearing the turn around bits. */
2089  RoadVehicle *rv = RoadVehicle::From(v);
2091  }
2092 
2093  return nullptr;
2094 }
2095 
2096 
2104 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2105 {
2106  Station *st = Station::GetByTile(tile);
2107 
2108  if (_current_company != OWNER_WATER) {
2109  CommandCost ret = CheckOwnership(st->owner);
2110  if (ret.Failed()) return ret;
2111  }
2112 
2113  bool is_truck = IsTruckStop(tile);
2114 
2115  RoadStop **primary_stop;
2116  RoadStop *cur_stop;
2117  if (is_truck) { // truck stop
2118  primary_stop = &st->truck_stops;
2119  cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
2120  } else {
2121  primary_stop = &st->bus_stops;
2122  cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
2123  }
2124 
2125  assert(cur_stop != nullptr);
2126 
2127  /* don't do the check for drive-through road stops when company bankrupts */
2128  if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
2129  /* remove the 'going through road stop' status from all vehicles on that tile */
2130  if (flags & DC_EXEC) FindVehicleOnPos(tile, nullptr, &ClearRoadStopStatusEnum);
2131  } else {
2133  if (ret.Failed()) return ret;
2134  }
2135 
2136  const RoadStopSpec *spec = GetRoadStopSpec(tile);
2137 
2138  if (flags & DC_EXEC) {
2139  if (*primary_stop == cur_stop) {
2140  /* removed the first stop in the list */
2141  *primary_stop = cur_stop->next;
2142  /* removed the only stop? */
2143  if (*primary_stop == nullptr) {
2144  st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
2146  }
2147  } else {
2148  /* tell the predecessor in the list to skip this stop */
2149  RoadStop *pred = *primary_stop;
2150  while (pred->next != cur_stop) pred = pred->next;
2151  pred->next = cur_stop->next;
2152  }
2153 
2154  /* Update company infrastructure counts. */
2155  for (RoadTramType rtt : _roadtramtypes) {
2156  RoadType rt = GetRoadType(tile, rtt);
2157  UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2158  }
2159 
2160  Company::Get(st->owner)->infrastructure.station--;
2162 
2163  DeleteAnimatedTile(tile);
2164 
2165  uint specindex = GetCustomRoadStopSpecIndex(tile);
2166 
2167  DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile.base());
2168 
2169  if (IsDriveThroughStopTile(tile)) {
2170  /* Clears the tile for us */
2171  cur_stop->ClearDriveThrough();
2172  } else {
2173  DoClearSquare(tile);
2174  }
2175 
2176  delete cur_stop;
2177 
2178  /* Make sure no vehicle is going to the old roadstop */
2179  for (RoadVehicle *v : RoadVehicle::Iterate()) {
2180  if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
2181  v->dest_tile == tile) {
2182  v->SetDestTile(v->GetOrderStationLocation(st->index));
2183  }
2184  }
2185 
2186  st->rect.AfterRemoveTile(st, tile);
2187 
2188  if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? STATION_TRUCK: STATION_BUS);
2189 
2190  st->RemoveRoadStopTileData(tile);
2191  if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex);
2192 
2193  /* Update the tile area of the truck/bus stop */
2194  if (is_truck) {
2195  st->truck_station.Clear();
2196  for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2197  } else {
2198  st->bus_station.Clear();
2199  for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2200  }
2201  }
2202 
2203  Price category = is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS;
2204  return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(category) : _price[category]);
2205 }
2206 
2217 CommandCost CmdRemoveRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
2218 {
2219  if (stop_type >= ROADSTOP_END) return CMD_ERROR;
2220  /* Check for incorrect width / height. */
2221  if (width == 0 || height == 0) return CMD_ERROR;
2222  /* Check if the first tile and the last tile are valid */
2223  if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2224  /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2225  if (remove_road && (flags & DC_BANKRUPT)) return CMD_ERROR;
2226 
2227  TileArea roadstop_area(tile, width, height);
2228 
2230  CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2231  bool had_success = false;
2232 
2233  for (TileIndex cur_tile : roadstop_area) {
2234  /* Make sure the specified tile is a road stop of the correct type */
2235  if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || GetRoadStopType(cur_tile) != stop_type) continue;
2236 
2237  /* Save information on to-be-restored roads before the stop is removed. */
2238  RoadBits road_bits = ROAD_NONE;
2239  RoadType road_type[] = { INVALID_ROADTYPE, INVALID_ROADTYPE };
2240  Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
2241  if (IsDriveThroughStopTile(cur_tile)) {
2242  for (RoadTramType rtt : _roadtramtypes) {
2243  road_type[rtt] = GetRoadType(cur_tile, rtt);
2244  if (road_type[rtt] == INVALID_ROADTYPE) continue;
2245  road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2246  /* If we don't want to preserve our roads then restore only roads of others. */
2247  if (remove_road && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2248  }
2249  road_bits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile)));
2250  }
2251 
2252  CommandCost ret = RemoveRoadStop(cur_tile, flags);
2253  if (ret.Failed()) {
2254  last_error = ret;
2255  continue;
2256  }
2257  cost.AddCost(ret);
2258  had_success = true;
2259 
2260  /* Restore roads. */
2261  if ((flags & DC_EXEC) && (road_type[RTT_ROAD] != INVALID_ROADTYPE || road_type[RTT_TRAM] != INVALID_ROADTYPE)) {
2262  MakeRoadNormal(cur_tile, road_bits, road_type[RTT_ROAD], road_type[RTT_TRAM], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2263  road_owner[RTT_ROAD], road_owner[RTT_TRAM]);
2264 
2265  /* Update company infrastructure counts. */
2266  int count = CountBits(road_bits);
2267  UpdateCompanyRoadInfrastructure(road_type[RTT_ROAD], road_owner[RTT_ROAD], count);
2268  UpdateCompanyRoadInfrastructure(road_type[RTT_TRAM], road_owner[RTT_TRAM], count);
2269  }
2270  }
2271 
2272  return had_success ? cost : last_error;
2273 }
2274 
2283 uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2284 {
2285  /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2286  * So no need to go any further*/
2287  if (as->noise_level < 2) return as->noise_level;
2288 
2289  /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2290  * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2291  * Basically, it says that the less tolerant a town is, the bigger the distance before
2292  * an actual decrease can be granted */
2293  uint8_t town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2294 
2295  /* now, we want to have the distance segmented using the distance judged bareable by town
2296  * This will give us the coefficient of reduction the distance provides. */
2297  uint noise_reduction = distance / town_tolerance_distance;
2298 
2299  /* If the noise reduction equals the airport noise itself, don't give it for free.
2300  * Otherwise, simply reduce the airport's level. */
2301  return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2302 }
2303 
2314 Town *AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
2315 {
2316  assert(Town::GetNumItems() > 0);
2317 
2318  Town *nearest = nullptr;
2319 
2320  auto width = as->size_x;
2321  auto height = as->size_y;
2322  if (rotation == DIR_E || rotation == DIR_W) std::swap(width, height);
2323 
2324  uint perimeter_min_x = TileX(tile);
2325  uint perimeter_min_y = TileY(tile);
2326  uint perimeter_max_x = perimeter_min_x + width - 1;
2327  uint perimeter_max_y = perimeter_min_y + height - 1;
2328 
2329  mindist = UINT_MAX - 1; // prevent overflow
2330 
2331  for (TileIndex cur_tile = *it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2332  assert(IsInsideBS(TileX(cur_tile), perimeter_min_x, width));
2333  assert(IsInsideBS(TileY(cur_tile), perimeter_min_y, height));
2334  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) {
2335  Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2336  if (t == nullptr) continue;
2337 
2338  uint dist = DistanceManhattan(t->xy, cur_tile);
2339  if (dist == mindist && t->index < nearest->index) nearest = t;
2340  if (dist < mindist) {
2341  nearest = t;
2342  mindist = dist;
2343  }
2344  }
2345  }
2346 
2347  return nearest;
2348 }
2349 
2357 static Town *AirportGetNearestTown(const Station *st, uint &mindist)
2358 {
2359  return AirportGetNearestTown(st->airport.GetSpec(), st->airport.rotation, st->airport.tile, AirportTileIterator(st), mindist);
2360 }
2361 
2362 
2365 {
2366  for (Town *t : Town::Iterate()) t->noise_reached = 0;
2367 
2368  for (const Station *st : Station::Iterate()) {
2369  if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2370  uint dist;
2371  Town *nearest = AirportGetNearestTown(st, dist);
2372  nearest->noise_reached += GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2373  }
2374  }
2375 }
2376 
2387 CommandCost CmdBuildAirport(DoCommandFlag flags, TileIndex tile, byte airport_type, byte layout, StationID station_to_join, bool allow_adjacent)
2388 {
2389  bool reuse = (station_to_join != NEW_STATION);
2390  if (!reuse) station_to_join = INVALID_STATION;
2391  bool distant_join = (station_to_join != INVALID_STATION);
2392 
2393  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2394 
2395  if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2396 
2397  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2398  if (ret.Failed()) return ret;
2399 
2400  /* Check if a valid, buildable airport was chosen for construction */
2401  const AirportSpec *as = AirportSpec::Get(airport_type);
2402  if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
2403  if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2404 
2405  Direction rotation = as->rotation[layout];
2406  int w = as->size_x;
2407  int h = as->size_y;
2408  if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2409  TileArea airport_area = TileArea(tile, w, h);
2410 
2412  return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2413  }
2414 
2415  AirportTileTableIterator tile_iter(as->table[layout], tile);
2416  CommandCost cost = CheckFlatLandAirport(tile_iter, flags);
2417  if (cost.Failed()) return cost;
2418 
2419  /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2420  uint dist;
2421  Town *nearest = AirportGetNearestTown(as, rotation, tile, std::move(tile_iter), dist);
2422  uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2423 
2424  /* Check if local auth would allow a new airport */
2425  StringID authority_refuse_message = STR_NULL;
2426  Town *authority_refuse_town = nullptr;
2427 
2429  /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2430  if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2431  authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2432  authority_refuse_town = nearest;
2433  }
2434  } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
2435  Town *t = ClosestTownFromTile(tile, UINT_MAX);
2436  uint num = 0;
2437  for (const Station *st : Station::Iterate()) {
2438  if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2439  }
2440  if (num >= 2) {
2441  authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2442  authority_refuse_town = t;
2443  }
2444  }
2445 
2446  if (authority_refuse_message != STR_NULL) {
2447  SetDParam(0, authority_refuse_town->index);
2448  return_cmd_error(authority_refuse_message);
2449  }
2450 
2451  Station *st = nullptr;
2452  ret = FindJoiningStation(INVALID_STATION, station_to_join, allow_adjacent, airport_area, &st);
2453  if (ret.Failed()) return ret;
2454 
2455  /* Distant join */
2456  if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2457 
2458  ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2459  if (ret.Failed()) return ret;
2460 
2461  if (st != nullptr && st->airport.tile != INVALID_TILE) {
2462  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2463  }
2464 
2465  for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2466  cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2467  }
2468 
2469  if (flags & DC_EXEC) {
2470  /* Always add the noise, so there will be no need to recalculate when option toggles */
2471  nearest->noise_reached += newnoise_level;
2472 
2473  st->AddFacility(FACIL_AIRPORT, tile);
2474  st->airport.type = airport_type;
2475  st->airport.layout = layout;
2476  st->airport.flags = 0;
2477  st->airport.rotation = rotation;
2478 
2479  st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2480 
2481  for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2482  Tile t(iter);
2483  MakeAirport(t, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2484  SetStationTileRandomBits(t, GB(Random(), 0, 4));
2485  st->airport.Add(iter);
2486 
2488  }
2489 
2490  /* Only call the animation trigger after all tiles have been built */
2491  for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2492  AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2493  }
2494 
2496 
2497  Company::Get(st->owner)->infrastructure.airport++;
2498 
2499  st->AfterStationTileSetChange(true, STATION_AIRPORT);
2501 
2503  SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2504  }
2505  }
2506 
2507  return cost;
2508 }
2509 
2517 {
2518  Station *st = Station::GetByTile(tile);
2519 
2520  if (_current_company != OWNER_WATER) {
2521  CommandCost ret = CheckOwnership(st->owner);
2522  if (ret.Failed()) return ret;
2523  }
2524 
2525  tile = st->airport.tile;
2526 
2528 
2529  for (const Aircraft *a : Aircraft::Iterate()) {
2530  if (!a->IsNormalAircraft()) continue;
2531  if (a->targetairport == st->index && a->state != FLYING) {
2532  return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2533  }
2534  }
2535 
2536  if (flags & DC_EXEC) {
2537  for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2538  TileIndex tile_cur = st->airport.GetHangarTile(i);
2539  OrderBackup::Reset(tile_cur, false);
2540  CloseWindowById(WC_VEHICLE_DEPOT, tile_cur);
2541  }
2542 
2543  /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2544  * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2545  * need of recalculation */
2546  uint dist;
2547  Town *nearest = AirportGetNearestTown(st, dist);
2549 
2551  SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2552  }
2553  }
2554 
2555  for (TileIndex tile_cur : st->airport) {
2556  if (!st->TileBelongsToAirport(tile_cur)) continue;
2557 
2558  CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2559  if (ret.Failed()) return ret;
2560 
2561  cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2562 
2563  if (flags & DC_EXEC) {
2564  DeleteAnimatedTile(tile_cur);
2565  DoClearSquare(tile_cur);
2566  DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur.base());
2567  }
2568  }
2569 
2570  if (flags & DC_EXEC) {
2571  /* Clear the persistent storage. */
2572  delete st->airport.psa;
2573 
2574  st->rect.AfterRemoveRect(st, st->airport);
2575 
2576  st->airport.Clear();
2577  st->facilities &= ~FACIL_AIRPORT;
2579 
2581 
2582  Company::Get(st->owner)->infrastructure.airport--;
2583 
2584  st->AfterStationTileSetChange(false, STATION_AIRPORT);
2585 
2586  DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2587  }
2588 
2589  return cost;
2590 }
2591 
2598 CommandCost CmdOpenCloseAirport(DoCommandFlag flags, StationID station_id)
2599 {
2600  if (!Station::IsValidID(station_id)) return CMD_ERROR;
2601  Station *st = Station::Get(station_id);
2602 
2603  if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2604 
2605  CommandCost ret = CheckOwnership(st->owner);
2606  if (ret.Failed()) return ret;
2607 
2608  if (flags & DC_EXEC) {
2611  }
2612  return CommandCost();
2613 }
2614 
2621 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2622 {
2623  for (const Vehicle *v : Vehicle::Iterate()) {
2624  if ((v->owner == company) == include_company) {
2625  for (const Order *order : v->Orders()) {
2626  if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
2627  return true;
2628  }
2629  }
2630  }
2631  }
2632  return false;
2633 }
2634 
2635 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2636  {-1, 0},
2637  { 0, 0},
2638  { 0, 0},
2639  { 0, -1}
2640 };
2641 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
2642 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
2643 
2652 CommandCost CmdBuildDock(DoCommandFlag flags, TileIndex tile, StationID station_to_join, bool adjacent)
2653 {
2654  bool reuse = (station_to_join != NEW_STATION);
2655  if (!reuse) station_to_join = INVALID_STATION;
2656  bool distant_join = (station_to_join != INVALID_STATION);
2657 
2658  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2659 
2661  if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2662  direction = ReverseDiagDir(direction);
2663 
2664  /* Docks cannot be placed on rapids */
2665  if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2666 
2667  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2668  if (ret.Failed()) return ret;
2669 
2670  if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2671 
2672  CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2673  ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
2674  if (ret.Failed()) return ret;
2675  cost.AddCost(ret);
2676 
2677  TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2678 
2679  if (!HasTileWaterGround(tile_cur) || !IsTileFlat(tile_cur)) {
2680  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2681  }
2682 
2683  if (IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2684 
2685  /* Get the water class of the water tile before it is cleared.*/
2686  WaterClass wc = GetWaterClass(tile_cur);
2687 
2688  bool add_cost = !IsWaterTile(tile_cur);
2689  ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
2690  if (ret.Failed()) return ret;
2691  if (add_cost) cost.AddCost(ret);
2692 
2693  tile_cur += TileOffsByDiagDir(direction);
2694  if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2695  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2696  }
2697 
2698  TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2699  _dock_w_chk[direction], _dock_h_chk[direction]);
2700 
2701  /* middle */
2702  Station *st = nullptr;
2703  ret = FindJoiningStation(INVALID_STATION, station_to_join, adjacent, dock_area, &st);
2704  if (ret.Failed()) return ret;
2705 
2706  /* Distant join */
2707  if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2708 
2709  ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2710  if (ret.Failed()) return ret;
2711 
2712  if (flags & DC_EXEC) {
2713  st->ship_station.Add(tile);
2714  TileIndex flat_tile = tile + TileOffsByDiagDir(direction);
2715  st->ship_station.Add(flat_tile);
2716  st->AddFacility(FACIL_DOCK, tile);
2717 
2718  st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2719 
2720  /* If the water part of the dock is on a canal, update infrastructure counts.
2721  * This is needed as we've cleared that tile before.
2722  * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
2723  * See: MakeWaterKeepingClass() */
2724  if (wc == WATER_CLASS_CANAL && !(HasTileWaterClass(flat_tile) && GetWaterClass(flat_tile) == WATER_CLASS_CANAL && IsTileOwner(flat_tile, _current_company))) {
2725  Company::Get(st->owner)->infrastructure.water++;
2726  }
2727  Company::Get(st->owner)->infrastructure.station += 2;
2728 
2729  MakeDock(tile, st->owner, st->index, direction, wc);
2730  UpdateStationDockingTiles(st);
2731 
2732  st->AfterStationTileSetChange(true, STATION_DOCK);
2733  }
2734 
2735  return cost;
2736 }
2737 
2738 void RemoveDockingTile(TileIndex t)
2739 {
2740  for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2741  TileIndex tile = t + TileOffsByDiagDir(d);
2742  if (!IsValidTile(tile)) continue;
2743 
2744  if (IsTileType(tile, MP_STATION)) {
2745  Station *st = Station::GetByTile(tile);
2746  if (st != nullptr) UpdateStationDockingTiles(st);
2747  } else if (IsTileType(tile, MP_INDUSTRY)) {
2748  Station *neutral = Industry::GetByTile(tile)->neutral_station;
2749  if (neutral != nullptr) UpdateStationDockingTiles(neutral);
2750  }
2751  }
2752 }
2753 
2760 {
2761  assert(IsValidTile(tile));
2762 
2763  /* Clear and maybe re-set docking tile */
2764  for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2765  TileIndex docking_tile = tile + TileOffsByDiagDir(d);
2766  if (!IsValidTile(docking_tile)) continue;
2767 
2768  if (IsPossibleDockingTile(docking_tile)) {
2769  SetDockingTile(docking_tile, false);
2770  CheckForDockingTile(docking_tile);
2771  }
2772  }
2773 }
2774 
2781 {
2782  assert(IsDockTile(t));
2783 
2784  StationGfx gfx = GetStationGfx(t);
2785  if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
2786 
2787  for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2788  TileIndex tile = t + TileOffsByDiagDir(d);
2789  if (!IsValidTile(tile)) continue;
2790  if (!IsDockTile(tile)) continue;
2791  if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
2792  }
2793 
2794  return INVALID_TILE;
2795 }
2796 
2804 {
2805  Station *st = Station::GetByTile(tile);
2806  CommandCost ret = CheckOwnership(st->owner);
2807  if (ret.Failed()) return ret;
2808 
2809  if (!IsDockTile(tile)) return CMD_ERROR;
2810 
2811  TileIndex tile1 = FindDockLandPart(tile);
2812  if (tile1 == INVALID_TILE) return CMD_ERROR;
2813  TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2814 
2815  ret = EnsureNoVehicleOnGround(tile1);
2816  if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2817  if (ret.Failed()) return ret;
2818 
2819  if (flags & DC_EXEC) {
2820  DoClearSquare(tile1);
2821  MarkTileDirtyByTile(tile1);
2822  MakeWaterKeepingClass(tile2, st->owner);
2823 
2824  st->rect.AfterRemoveTile(st, tile1);
2825  st->rect.AfterRemoveTile(st, tile2);
2826 
2827  MakeShipStationAreaSmaller(st);
2828  if (st->ship_station.tile == INVALID_TILE) {
2829  st->ship_station.Clear();
2830  st->docking_station.Clear();
2831  st->facilities &= ~FACIL_DOCK;
2833  }
2834 
2835  Company::Get(st->owner)->infrastructure.station -= 2;
2836 
2837  st->AfterStationTileSetChange(false, STATION_DOCK);
2838 
2841 
2842  for (Ship *s : Ship::Iterate()) {
2843  /* Find all ships going to our dock. */
2844  if (s->current_order.GetDestination() != st->index) {
2845  continue;
2846  }
2847 
2848  /* Find ships that are marked as "loading" but are no longer on a
2849  * docking tile. Force them to leave the station (as they were loading
2850  * on the removed dock). */
2851  if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
2852  s->LeaveStation();
2853  }
2854 
2855  /* If we no longer have a dock, mark the order as invalid and send
2856  * the ship to the next order (or, if there is none, make it
2857  * wander the world). */
2858  if (s->current_order.IsType(OT_GOTO_STATION) && !(st->facilities & FACIL_DOCK)) {
2859  s->SetDestTile(s->GetOrderStationLocation(st->index));
2860  }
2861  }
2862  }
2863 
2864  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
2865 }
2866 
2867 #include "table/station_land.h"
2868 
2869 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
2870 {
2871  return &_station_display_datas[st][gfx];
2872 }
2873 
2883 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
2884 {
2885  bool snow_desert;
2886  switch (*ground) {
2887  case SPR_RAIL_TRACK_X:
2888  case SPR_MONO_TRACK_X:
2889  case SPR_MGLV_TRACK_X:
2890  snow_desert = false;
2891  *overlay_offset = RTO_X;
2892  break;
2893 
2894  case SPR_RAIL_TRACK_Y:
2895  case SPR_MONO_TRACK_Y:
2896  case SPR_MGLV_TRACK_Y:
2897  snow_desert = false;
2898  *overlay_offset = RTO_Y;
2899  break;
2900 
2901  case SPR_RAIL_TRACK_X_SNOW:
2902  case SPR_MONO_TRACK_X_SNOW:
2903  case SPR_MGLV_TRACK_X_SNOW:
2904  snow_desert = true;
2905  *overlay_offset = RTO_X;
2906  break;
2907 
2908  case SPR_RAIL_TRACK_Y_SNOW:
2909  case SPR_MONO_TRACK_Y_SNOW:
2910  case SPR_MGLV_TRACK_Y_SNOW:
2911  snow_desert = true;
2912  *overlay_offset = RTO_Y;
2913  break;
2914 
2915  default:
2916  return false;
2917  }
2918 
2919  if (ti != nullptr) {
2920  /* Decide snow/desert from tile */
2922  case LT_ARCTIC:
2923  snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
2924  break;
2925 
2926  case LT_TROPIC:
2927  snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
2928  break;
2929 
2930  default:
2931  break;
2932  }
2933  }
2934 
2935  *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
2936  return true;
2937 }
2938 
2939 static void DrawTile_Station(TileInfo *ti)
2940 {
2941  const NewGRFSpriteLayout *layout = nullptr;
2942  DrawTileSprites tmp_rail_layout;
2943  const DrawTileSprites *t = nullptr;
2944  int32_t total_offset;
2945  const RailTypeInfo *rti = nullptr;
2946  uint32_t relocation = 0;
2947  uint32_t ground_relocation = 0;
2948  BaseStation *st = nullptr;
2949  const StationSpec *statspec = nullptr;
2950  uint tile_layout = 0;
2951 
2952  if (HasStationRail(ti->tile)) {
2953  rti = GetRailTypeInfo(GetRailType(ti->tile));
2954  total_offset = rti->GetRailtypeSpriteOffset();
2955 
2956  if (IsCustomStationSpecIndex(ti->tile)) {
2957  /* look for customization */
2958  st = BaseStation::GetByTile(ti->tile);
2959  statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
2960 
2961  if (statspec != nullptr) {
2962  tile_layout = GetStationGfx(ti->tile);
2963 
2965  uint16_t callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
2966  if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
2967  }
2968 
2969  /* Ensure the chosen tile layout is valid for this custom station */
2970  if (!statspec->renderdata.empty()) {
2971  layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
2972  if (!layout->NeedsPreprocessing()) {
2973  t = layout;
2974  layout = nullptr;
2975  }
2976  }
2977  }
2978  }
2979  } else {
2980  total_offset = 0;
2981  }
2982 
2983  StationGfx gfx = GetStationGfx(ti->tile);
2984  if (IsAirport(ti->tile)) {
2985  gfx = GetAirportGfx(ti->tile);
2986  if (gfx >= NEW_AIRPORTTILE_OFFSET) {
2987  const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
2988  if (ats->grf_prop.spritegroup[0] != nullptr && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), ats)) {
2989  return;
2990  }
2991  /* No sprite group (or no valid one) found, meaning no graphics associated.
2992  * Use the substitute one instead */
2993  assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
2994  gfx = ats->grf_prop.subst_id;
2995  }
2996  switch (gfx) {
2997  case APT_RADAR_GRASS_FENCE_SW:
2998  t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
2999  break;
3000  case APT_GRASS_FENCE_NE_FLAG:
3001  t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
3002  break;
3003  case APT_RADAR_FENCE_SW:
3004  t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
3005  break;
3006  case APT_RADAR_FENCE_NE:
3007  t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
3008  break;
3009  case APT_GRASS_FENCE_NE_FLAG_2:
3010  t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
3011  break;
3012  }
3013  }
3014 
3015  Owner owner = GetTileOwner(ti->tile);
3016 
3017  PaletteID palette;
3018  if (Company::IsValidID(owner)) {
3019  palette = COMPANY_SPRITE_COLOUR(owner);
3020  } else {
3021  /* Some stations are not owner by a company, namely oil rigs */
3022  palette = PALETTE_TO_GREY;
3023  }
3024 
3025  if (layout == nullptr && (t == nullptr || t->seq == nullptr)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
3026 
3027  /* don't show foundation for docks */
3028  if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
3029  if (statspec != nullptr && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
3030  /* Station has custom foundations.
3031  * Check whether the foundation continues beyond the tile's upper sides. */
3032  uint edge_info = 0;
3033  int z;
3034  Slope slope = GetFoundationPixelSlope(ti->tile, &z);
3035  if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
3036  if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
3037  SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
3038  if (image == 0) goto draw_default_foundation;
3039 
3040  if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
3041  /* Station provides extended foundations. */
3042 
3043  static const uint8_t foundation_parts[] = {
3044  0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3045  0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3046  0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3047  7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3048  };
3049 
3050  AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3051  } else {
3052  /* Draw simple foundations, built up from 8 possible foundation sprites. */
3053 
3054  /* Each set bit represents one of the eight composite sprites to be drawn.
3055  * 'Invalid' entries will not drawn but are included for completeness. */
3056  static const uint8_t composite_foundation_parts[] = {
3057  /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
3058  0x00, 0xD1, 0xE4, 0xE0,
3059  /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
3060  0xCA, 0xC9, 0xC4, 0xC0,
3061  /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
3062  0xD2, 0x91, 0xE4, 0xA0,
3063  /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
3064  0x4A, 0x09, 0x44
3065  };
3066 
3067  uint8_t parts = composite_foundation_parts[ti->tileh];
3068 
3069  /* If foundations continue beyond the tile's upper sides then
3070  * mask out the last two pieces. */
3071  if (HasBit(edge_info, 0)) ClrBit(parts, 6);
3072  if (HasBit(edge_info, 1)) ClrBit(parts, 7);
3073 
3074  if (parts == 0) {
3075  /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
3076  * correct offset for the childsprites.
3077  * So, draw the (completely empty) sprite of the default foundations. */
3078  goto draw_default_foundation;
3079  }
3080 
3082  for (int i = 0; i < 8; i++) {
3083  if (HasBit(parts, i)) {
3084  AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3085  }
3086  }
3087  EndSpriteCombine();
3088  }
3089 
3090  OffsetGroundSprite(0, -8);
3092  } else {
3093 draw_default_foundation:
3095  }
3096  }
3097 
3098  bool draw_ground = false;
3099 
3100  if (IsBuoy(ti->tile)) {
3101  DrawWaterClassGround(ti);
3102  SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
3103  if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
3104  } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
3105  if (ti->tileh == SLOPE_FLAT) {
3106  DrawWaterClassGround(ti);
3107  } else {
3108  assert(IsDock(ti->tile));
3109  TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
3110  WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WATER_CLASS_INVALID;
3111  if (wc == WATER_CLASS_SEA) {
3112  DrawShoreTile(ti->tileh);
3113  } else {
3114  DrawClearLandTile(ti, 3);
3115  }
3116  }
3117  } else {
3118  if (layout != nullptr) {
3119  /* Sprite layout which needs preprocessing */
3120  bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
3121  uint32_t var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
3122  for (uint8_t var10 : SetBitIterator(var10_values)) {
3123  uint32_t var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
3124  layout->ProcessRegisters(var10, var10_relocation, separate_ground);
3125  }
3126  tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
3127  t = &tmp_rail_layout;
3128  total_offset = 0;
3129  } else if (statspec != nullptr) {
3130  /* Simple sprite layout */
3131  ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
3132  if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
3133  ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
3134  }
3135  ground_relocation += rti->fallback_railtype;
3136  }
3137 
3138  draw_ground = true;
3139  }
3140 
3141  if (draw_ground && !IsRoadStop(ti->tile)) {
3142  SpriteID image = t->ground.sprite;
3143  PaletteID pal = t->ground.pal;
3144  RailTrackOffset overlay_offset;
3145  if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3146  SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
3147  DrawGroundSprite(image, PAL_NONE);
3148  DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3149 
3150  if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3151  SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
3152  DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3153  }
3154  } else {
3155  image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3156  if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3157  DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3158 
3159  /* PBS debugging, draw reserved tracks darker */
3160  if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3162  }
3163  }
3164  }
3165 
3167 
3168  if (IsRoadStop(ti->tile)) {
3169  RoadType road_rt = GetRoadTypeRoad(ti->tile);
3170  RoadType tram_rt = GetRoadTypeTram(ti->tile);
3171  const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3172  const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3173 
3174  Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
3175  DiagDirection dir = GetRoadStopDir(ti->tile);
3176  StationType type = GetStationType(ti->tile);
3177 
3178  const RoadStopSpec *stopspec = GetRoadStopSpec(ti->tile);
3179  if (stopspec != nullptr) {
3180  int view = dir;
3181  if (IsDriveThroughStopTile(ti->tile)) view += 4;
3182  st = BaseStation::GetByTile(ti->tile);
3183  RoadStopResolverObject object(stopspec, st, ti->tile, INVALID_ROADTYPE, type, view);
3184  const SpriteGroup *group = object.Resolve();
3185  if (group != nullptr && group->type == SGT_TILELAYOUT) {
3186  t = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(nullptr);
3187  }
3188  }
3189 
3190  /* Draw ground sprite */
3191  if (draw_ground) {
3192  SpriteID image = t->ground.sprite;
3193  PaletteID pal = t->ground.pal;
3194  image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3195  if (GB(image, 0, SPRITE_WIDTH) != 0) {
3196  if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3197  DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3198  }
3199  }
3200 
3201  if (IsDriveThroughStopTile(ti->tile)) {
3202  uint sprite_offset = axis == AXIS_X ? 1 : 0;
3203 
3204  DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3205  } else {
3206  /* Non-drivethrough road stops are only valid for roads. */
3207  assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3208 
3209  if ((stopspec == nullptr || (stopspec->draw_mode & ROADSTOP_DRAW_MODE_ROAD) != 0) && road_rti->UsesOverlay()) {
3210  SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_ROADSTOP);
3211  DrawGroundSprite(ground + dir, PAL_NONE);
3212  }
3213  }
3214 
3215  if (stopspec == nullptr || !HasBit(stopspec->flags, RSF_NO_CATENARY)) {
3216  /* Draw road, tram catenary */
3217  DrawRoadCatenary(ti);
3218  }
3219  }
3220 
3221  if (IsRailWaypoint(ti->tile)) {
3222  /* Don't offset the waypoint graphics; they're always the same. */
3223  total_offset = 0;
3224  }
3225 
3226  DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
3227 }
3228 
3229 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3230 {
3231  int32_t total_offset = 0;
3232  PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3233  const DrawTileSprites *t = GetStationTileLayout(st, image);
3234  const RailTypeInfo *railtype_info = nullptr;
3235 
3236  if (railtype != INVALID_RAILTYPE) {
3237  railtype_info = GetRailTypeInfo(railtype);
3238  total_offset = railtype_info->GetRailtypeSpriteOffset();
3239  }
3240 
3241  SpriteID img = t->ground.sprite;
3242  RailTrackOffset overlay_offset;
3243  if (railtype_info != nullptr && railtype_info->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3244  SpriteID ground = GetCustomRailSprite(railtype_info, INVALID_TILE, RTSG_GROUND);
3245  DrawSprite(img, PAL_NONE, x, y);
3246  DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3247  } else {
3248  DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3249  }
3250 
3251  if (roadtype != INVALID_ROADTYPE) {
3252  const RoadTypeInfo *roadtype_info = GetRoadTypeInfo(roadtype);
3253  if (image >= 4) {
3254  /* Drive-through stop */
3255  uint sprite_offset = 5 - image;
3256 
3257  /* Road underlay takes precedence over tram */
3258  if (roadtype_info->UsesOverlay()) {
3259  SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_GROUND);
3260  DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3261 
3262  SpriteID overlay = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_OVERLAY);
3263  if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3264  } else if (RoadTypeIsTram(roadtype)) {
3265  DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3266  }
3267  } else {
3268  /* Bay stop */
3269  if (RoadTypeIsRoad(roadtype) && roadtype_info->UsesOverlay()) {
3270  SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_ROADSTOP);
3271  DrawSprite(ground + image, PAL_NONE, x, y);
3272  }
3273  }
3274  }
3275 
3276  /* Default waypoint has no railtype specific sprites */
3277  DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
3278 }
3279 
3280 static int GetSlopePixelZ_Station(TileIndex tile, uint, uint, bool)
3281 {
3282  return GetTileMaxPixelZ(tile);
3283 }
3284 
3285 static Foundation GetFoundation_Station(TileIndex, Slope tileh)
3286 {
3287  return FlatteningFoundation(tileh);
3288 }
3289 
3290 static void FillTileDescRoadStop(TileIndex tile, TileDesc *td)
3291 {
3292  RoadType road_rt = GetRoadTypeRoad(tile);
3293  RoadType tram_rt = GetRoadTypeTram(tile);
3294  Owner road_owner = INVALID_OWNER;
3295  Owner tram_owner = INVALID_OWNER;
3296  if (road_rt != INVALID_ROADTYPE) {
3297  const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3298  td->roadtype = rti->strings.name;
3299  td->road_speed = rti->max_speed / 2;
3300  road_owner = GetRoadOwner(tile, RTT_ROAD);
3301  }
3302 
3303  if (tram_rt != INVALID_ROADTYPE) {
3304  const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3305  td->tramtype = rti->strings.name;
3306  td->tram_speed = rti->max_speed / 2;
3307  tram_owner = GetRoadOwner(tile, RTT_TRAM);
3308  }
3309 
3310  if (IsDriveThroughStopTile(tile)) {
3311  /* Is there a mix of owners? */
3312  if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3313  (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3314  uint i = 1;
3315  if (road_owner != INVALID_OWNER) {
3316  td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3317  td->owner[i] = road_owner;
3318  i++;
3319  }
3320  if (tram_owner != INVALID_OWNER) {
3321  td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3322  td->owner[i] = tram_owner;
3323  }
3324  }
3325  }
3326 }
3327 
3328 void FillTileDescRailStation(TileIndex tile, TileDesc *td)
3329 {
3330  const StationSpec *spec = GetStationSpec(tile);
3331 
3332  if (spec != nullptr) {
3334  td->station_name = spec->name;
3335 
3336  if (spec->grf_prop.grffile != nullptr) {
3337  const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3338  td->grf = gc->GetName();
3339  }
3340  }
3341 
3342  const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3343  td->rail_speed = rti->max_speed;
3344  td->railtype = rti->strings.name;
3345 }
3346 
3347 void FillTileDescAirport(TileIndex tile, TileDesc *td)
3348 {
3349  const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3351  td->airport_name = as->name;
3352 
3353  const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3354  td->airport_tile_name = ats->name;
3355 
3356  if (as->grf_prop.grffile != nullptr) {
3357  const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3358  td->grf = gc->GetName();
3359  } else if (ats->grf_prop.grffile != nullptr) {
3360  const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3361  td->grf = gc->GetName();
3362  }
3363 }
3364 
3365 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3366 {
3367  td->owner[0] = GetTileOwner(tile);
3369 
3370  if (IsRoadStop(tile)) FillTileDescRoadStop(tile, td);
3371  if (HasStationRail(tile)) FillTileDescRailStation(tile, td);
3372  if (IsAirport(tile)) FillTileDescAirport(tile, td);
3373 
3374  StringID str;
3375  switch (GetStationType(tile)) {
3376  default: NOT_REACHED();
3377  case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3378  case STATION_AIRPORT:
3379  str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3380  break;
3381  case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3382  case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3383  case STATION_OILRIG: {
3384  const Industry *i = Station::GetByTile(tile)->industry;
3385  const IndustrySpec *is = GetIndustrySpec(i->type);
3386  td->owner[0] = i->owner;
3387  str = is->name;
3388  if (is->grf_prop.grffile != nullptr) td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
3389  break;
3390  }
3391  case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3392  case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3393  case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3394  }
3395  td->str = str;
3396 }
3397 
3398 
3399 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3400 {
3401  TrackBits trackbits = TRACK_BIT_NONE;
3402 
3403  switch (mode) {
3404  case TRANSPORT_RAIL:
3405  if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3406  trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3407  }
3408  break;
3409 
3410  case TRANSPORT_WATER:
3411  /* buoy is coded as a station, it is always on open water */
3412  if (IsBuoy(tile)) {
3413  trackbits = TRACK_BIT_ALL;
3414  /* remove tracks that connect NE map edge */
3415  if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3416  /* remove tracks that connect NW map edge */
3417  if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3418  }
3419  break;
3420 
3421  case TRANSPORT_ROAD:
3422  if (IsRoadStop(tile)) {
3423  RoadTramType rtt = (RoadTramType)sub_mode;
3424  if (!HasTileRoadType(tile, rtt)) break;
3425 
3426  DiagDirection dir = GetRoadStopDir(tile);
3427  Axis axis = DiagDirToAxis(dir);
3428 
3429  if (side != INVALID_DIAGDIR) {
3430  if (axis != DiagDirToAxis(side) || (IsBayRoadStopTile(tile) && dir != side)) break;
3431  }
3432 
3433  trackbits = AxisToTrackBits(axis);
3434  }
3435  break;
3436 
3437  default:
3438  break;
3439  }
3440 
3442 }
3443 
3444 
3445 static void TileLoop_Station(TileIndex tile)
3446 {
3447  /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3448  * hardcoded.....not good */
3449  switch (GetStationType(tile)) {
3450  case STATION_AIRPORT:
3451  AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3452  break;
3453 
3454  case STATION_DOCK:
3455  if (!IsTileFlat(tile)) break; // only handle water part
3456  [[fallthrough]];
3457 
3458  case STATION_OILRIG: //(station part)
3459  case STATION_BUOY:
3460  TileLoop_Water(tile);
3461  break;
3462 
3463  default: break;
3464  }
3465 }
3466 
3467 
3468 static void AnimateTile_Station(TileIndex tile)
3469 {
3470  if (HasStationRail(tile)) {
3471  AnimateStationTile(tile);
3472  return;
3473  }
3474 
3475  if (IsAirport(tile)) {
3476  AnimateAirportTile(tile);
3477  return;
3478  }
3479 
3480  if (IsRoadStopTile(tile)) {
3481  AnimateRoadStopTile(tile);
3482  return;
3483  }
3484 }
3485 
3486 
3487 static bool ClickTile_Station(TileIndex tile)
3488 {
3489  const BaseStation *bst = BaseStation::GetByTile(tile);
3490 
3491  if (bst->facilities & FACIL_WAYPOINT) {
3493  } else if (IsHangar(tile)) {
3494  const Station *st = Station::From(bst);
3496  } else {
3498  }
3499  return true;
3500 }
3501 
3502 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3503 {
3504  if (v->type == VEH_TRAIN) {
3505  StationID station_id = GetStationIndex(tile);
3506  if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3507  if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3508 
3509  int station_ahead;
3510  int station_length;
3511  int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3512 
3513  /* Stop whenever that amount of station ahead + the distance from the
3514  * begin of the platform to the stop location is longer than the length
3515  * of the platform. Station ahead 'includes' the current tile where the
3516  * vehicle is on, so we need to subtract that. */
3517  if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3518 
3520 
3521  x &= 0xF;
3522  y &= 0xF;
3523 
3524  if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3525  if (y == TILE_SIZE / 2) {
3526  if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3527  stop &= TILE_SIZE - 1;
3528 
3529  if (x == stop) {
3530  return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3531  } else if (x < stop) {
3533  uint16_t spd = std::max(0, (stop - x) * 20 - 15);
3534  if (spd < v->cur_speed) v->cur_speed = spd;
3535  }
3536  }
3537  } else if (v->type == VEH_ROAD) {
3538  RoadVehicle *rv = RoadVehicle::From(v);
3539  if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3540  if (IsRoadStop(tile) && rv->IsFrontEngine()) {
3541  /* Attempt to allocate a parking bay in a road stop */
3543  }
3544  }
3545  }
3546 
3547  return VETSB_CONTINUE;
3548 }
3549 
3555 {
3556  /* Collect cargoes accepted since the last big tick. */
3557  CargoTypes cargoes = 0;
3558  for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3559  if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3560  }
3561 
3562  /* Anything to do? */
3563  if (cargoes == 0) return;
3564 
3565  /* Loop over all houses in the catchment. */
3567  for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3568  if (IsTileType(tile, MP_HOUSE)) {
3569  WatchedCargoCallback(tile, cargoes);
3570  }
3571  }
3572 }
3573 
3581 {
3582  if (!st->IsInUse()) {
3583  if (++st->delete_ctr >= 8) delete st;
3584  return false;
3585  }
3586 
3587  if (Station::IsExpected(st)) {
3589 
3590  for (GoodsEntry &ge : Station::From(st)->goods) {
3592  }
3593  }
3594 
3595 
3596  if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3597 
3598  return true;
3599 }
3600 
3601 static inline void byte_inc_sat(byte *p)
3602 {
3603  byte b = *p + 1;
3604  if (b != 0) *p = b;
3605 }
3606 
3613 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3614 {
3615  /* If truncating also punish the source stations' ratings to
3616  * decrease the flow of incoming cargo. */
3617 
3618  StationCargoAmountMap waiting_per_source;
3619  ge->cargo.Truncate(amount, &waiting_per_source);
3620  for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3621  Station *source_station = Station::GetIfValid(i->first);
3622  if (source_station == nullptr) continue;
3623 
3624  GoodsEntry &source_ge = source_station->goods[cs->Index()];
3625  source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3626  }
3627 }
3628 
3629 static void UpdateStationRating(Station *st)
3630 {
3631  bool waiting_changed = false;
3632 
3633  byte_inc_sat(&st->time_since_load);
3634  byte_inc_sat(&st->time_since_unload);
3635 
3636  for (const CargoSpec *cs : CargoSpec::Iterate()) {
3637  GoodsEntry *ge = &st->goods[cs->Index()];
3638  /* Slowly increase the rating back to its original level in the case we
3639  * didn't deliver cargo yet to this station. This happens when a bribe
3640  * failed while you didn't moved that cargo yet to a station. */
3641  if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3642  ge->rating++;
3643  }
3644 
3645  /* Only change the rating if we are moving this cargo */
3646  if (ge->HasRating()) {
3647  byte_inc_sat(&ge->time_since_pickup);
3648  if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3650  ge->last_speed = 0;
3651  TruncateCargo(cs, ge);
3652  waiting_changed = true;
3653  continue;
3654  }
3655 
3656  bool skip = false;
3657  int rating = 0;
3658  uint waiting = ge->cargo.AvailableCount();
3659 
3660  /* num_dests is at least 1 if there is any cargo as
3661  * INVALID_STATION is also a destination.
3662  */
3663  uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3664 
3665  /* Average amount of cargo per next hop, but prefer solitary stations
3666  * with only one or two next hops. They are allowed to have more
3667  * cargo waiting per next hop.
3668  * With manual cargo distribution waiting_avg = waiting / 2 as then
3669  * INVALID_STATION is the only destination.
3670  */
3671  uint waiting_avg = waiting / (num_dests + 1);
3672 
3674  ge->rating = rating = MAX_STATION_RATING;
3675  skip = true;
3676  } else if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3677  /* Perform custom station rating. If it succeeds the speed, days in transit and
3678  * waiting cargo ratings must not be executed. */
3679 
3680  /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3681  uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3682 
3683  uint32_t var18 = ClampTo<uint8_t>(ge->time_since_pickup)
3684  | (ClampTo<uint16_t>(ge->max_waiting_cargo) << 8)
3685  | (ClampTo<uint8_t>(last_speed) << 24);
3686  /* Convert to the 'old' vehicle types */
3687  uint32_t var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3688  uint16_t callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3689  if (callback != CALLBACK_FAILED) {
3690  skip = true;
3691  rating = GB(callback, 0, 14);
3692 
3693  /* Simulate a 15 bit signed value */
3694  if (HasBit(callback, 14)) rating -= 0x4000;
3695  }
3696  }
3697 
3698  if (!skip) {
3699  int b = ge->last_speed - 85;
3700  if (b >= 0) rating += b >> 2;
3701 
3702  byte waittime = ge->time_since_pickup;
3703  if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3704  if (waittime <= 21) rating += 25;
3705  if (waittime <= 12) rating += 25;
3706  if (waittime <= 6) rating += 45;
3707  if (waittime <= 3) rating += 35;
3708 
3709  rating -= 90;
3710  if (ge->max_waiting_cargo <= 1500) rating += 55;
3711  if (ge->max_waiting_cargo <= 1000) rating += 35;
3712  if (ge->max_waiting_cargo <= 600) rating += 10;
3713  if (ge->max_waiting_cargo <= 300) rating += 20;
3714  if (ge->max_waiting_cargo <= 100) rating += 10;
3715  }
3716 
3717  if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3718 
3719  byte age = ge->last_age;
3720  if (age < 3) rating += 10;
3721  if (age < 2) rating += 10;
3722  if (age < 1) rating += 13;
3723 
3724  {
3725  int or_ = ge->rating; // old rating
3726 
3727  /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3728  ge->rating = rating = or_ + Clamp(ClampTo<uint8_t>(rating) - or_, -2, 2);
3729 
3730  /* if rating is <= 64 and more than 100 items waiting on average per destination,
3731  * remove some random amount of goods from the station */
3732  if (rating <= 64 && waiting_avg >= 100) {
3733  int dec = Random() & 0x1F;
3734  if (waiting_avg < 200) dec &= 7;
3735  waiting -= (dec + 1) * num_dests;
3736  waiting_changed = true;
3737  }
3738 
3739  /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3740  if (rating <= 127 && waiting != 0) {
3741  uint32_t r = Random();
3742  if (rating <= (int)GB(r, 0, 7)) {
3743  /* Need to have int, otherwise it will just overflow etc. */
3744  waiting = std::max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3745  waiting_changed = true;
3746  }
3747  }
3748 
3749  /* At some point we really must cap the cargo. Previously this
3750  * was a strict 4095, but now we'll have a less strict, but
3751  * increasingly aggressive truncation of the amount of cargo. */
3752  static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3753  static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3754  static const uint MAX_WAITING_CARGO = 1 << 15;
3755 
3756  if (waiting > WAITING_CARGO_THRESHOLD) {
3757  uint difference = waiting - WAITING_CARGO_THRESHOLD;
3758  waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3759 
3760  waiting = std::min(waiting, MAX_WAITING_CARGO);
3761  waiting_changed = true;
3762  }
3763 
3764  /* We can't truncate cargo that's already reserved for loading.
3765  * Thus StoredCount() here. */
3766  if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3767  /* Feed back the exact own waiting cargo at this station for the
3768  * next rating calculation. */
3769  ge->max_waiting_cargo = 0;
3770 
3771  TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3772  } else {
3773  /* If the average number per next hop is low, be more forgiving. */
3774  ge->max_waiting_cargo = waiting_avg;
3775  }
3776  }
3777  }
3778  }
3779 
3780  StationID index = st->index;
3781  if (waiting_changed) {
3782  SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3783  } else {
3784  SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3785  }
3786 }
3787 
3796 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
3797 {
3798  GoodsEntry &ge = st->goods[c];
3799 
3800  /* Reroute cargo in station. */
3801  ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
3802 
3803  /* Reroute cargo staged to be transferred. */
3804  for (Vehicle *v : st->loading_vehicles) {
3805  for (Vehicle *u = v; u != nullptr; u = u->Next()) {
3806  if (u->cargo_type != c) continue;
3807  u->cargo.Reroute(UINT_MAX, &u->cargo, avoid, avoid2, &ge);
3808  }
3809  }
3810 }
3811 
3821 {
3822  for (CargoID c = 0; c < NUM_CARGO; ++c) {
3823  const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
3824  GoodsEntry &ge = from->goods[c];
3826  if (lg == nullptr) continue;
3827  std::vector<NodeID> to_remove{};
3828  for (Edge &edge : (*lg)[ge.node].edges) {
3829  Station *to = Station::Get((*lg)[edge.dest_node].station);
3830  assert(to->goods[c].node == edge.dest_node);
3831  assert(TimerGameEconomy::date >= edge.LastUpdate());
3832  auto timeout = TimerGameEconomy::Date(LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3));
3833  if (TimerGameEconomy::date - edge.LastUpdate() > timeout) {
3834  bool updated = false;
3835 
3836  if (auto_distributed) {
3837  /* Have all vehicles refresh their next hops before deciding to
3838  * remove the node. */
3839  std::vector<Vehicle *> vehicles;
3840  for (OrderList *l : OrderList::Iterate()) {
3841  bool found_from = false;
3842  bool found_to = false;
3843  for (Order *order = l->GetFirstOrder(); order != nullptr; order = order->next) {
3844  if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
3845  if (order->GetDestination() == from->index) {
3846  found_from = true;
3847  if (found_to) break;
3848  } else if (order->GetDestination() == to->index) {
3849  found_to = true;
3850  if (found_from) break;
3851  }
3852  }
3853  if (!found_to || !found_from) continue;
3854  vehicles.push_back(l->GetFirstSharedVehicle());
3855  }
3856 
3857  auto iter = vehicles.begin();
3858  while (iter != vehicles.end()) {
3859  Vehicle *v = *iter;
3860  /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
3862  LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
3863  }
3864  if (edge.LastUpdate() == TimerGameEconomy::date) {
3865  updated = true;
3866  break;
3867  }
3868 
3869  Vehicle *next_shared = v->NextShared();
3870  if (next_shared) {
3871  *iter = next_shared;
3872  ++iter;
3873  } else {
3874  iter = vehicles.erase(iter);
3875  }
3876 
3877  if (iter == vehicles.end()) iter = vehicles.begin();
3878  }
3879  }
3880 
3881  if (!updated) {
3882  /* If it's still considered dead remove it. */
3883  to_remove.emplace_back(to->goods[c].node);
3884  ge.flows.DeleteFlows(to->index);
3885  RerouteCargo(from, c, to->index, from->index);
3886  }
3887  } else if (edge.last_unrestricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_unrestricted_update > timeout) {
3888  edge.Restrict();
3889  ge.flows.RestrictFlows(to->index);
3890  RerouteCargo(from, c, to->index, from->index);
3891  } else if (edge.last_restricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_restricted_update > timeout) {
3892  edge.Release();
3893  }
3894  }
3895  /* Remove dead edges. */
3896  for (NodeID r : to_remove) (*lg)[ge.node].RemoveEdge(r);
3897 
3898  assert(TimerGameEconomy::date >= lg->LastCompression());
3900  lg->Compress();
3901  }
3902  }
3903 }
3904 
3914 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateMode mode)
3915 {
3916  GoodsEntry &ge1 = st->goods[cargo];
3917  Station *st2 = Station::Get(next_station_id);
3918  GoodsEntry &ge2 = st2->goods[cargo];
3919  LinkGraph *lg = nullptr;
3920  if (ge1.link_graph == INVALID_LINK_GRAPH) {
3921  if (ge2.link_graph == INVALID_LINK_GRAPH) {
3923  lg = new LinkGraph(cargo);
3925  ge2.link_graph = lg->index;
3926  ge2.node = lg->AddNode(st2);
3927  } else {
3928  Debug(misc, 0, "Can't allocate link graph");
3929  }
3930  } else {
3931  lg = LinkGraph::Get(ge2.link_graph);
3932  }
3933  if (lg) {
3934  ge1.link_graph = lg->index;
3935  ge1.node = lg->AddNode(st);
3936  }
3937  } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
3938  lg = LinkGraph::Get(ge1.link_graph);
3939  ge2.link_graph = lg->index;
3940  ge2.node = lg->AddNode(st2);
3941  } else {
3942  lg = LinkGraph::Get(ge1.link_graph);
3943  if (ge1.link_graph != ge2.link_graph) {
3944  LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
3945  if (lg->Size() < lg2->Size()) {
3947  lg2->Merge(lg); // Updates GoodsEntries of lg
3948  lg = lg2;
3949  } else {
3951  lg->Merge(lg2); // Updates GoodsEntries of lg2
3952  }
3953  }
3954  }
3955  if (lg != nullptr) {
3956  (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, mode);
3957  }
3958 }
3959 
3966 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32_t time)
3967 {
3968  for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
3969  if (v->refit_cap > 0) {
3970  /* The cargo count can indeed be higher than the refit_cap if
3971  * wagons have been auto-replaced and subsequently auto-
3972  * refitted to a higher capacity. The cargo gets redistributed
3973  * among the wagons in that case.
3974  * As usage is not such an important figure anyway we just
3975  * ignore the additional cargo then.*/
3976  IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
3977  std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EUM_INCREASE);
3978  }
3979  }
3980 }
3981 
3982 /* called for every station each tick */
3983 static void StationHandleSmallTick(BaseStation *st)
3984 {
3985  if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
3986 
3987  byte b = st->delete_ctr + 1;
3988  if (b >= Ticks::STATION_RATING_TICKS) b = 0;
3989  st->delete_ctr = b;
3990 
3991  if (b == 0) UpdateStationRating(Station::From(st));
3992 }
3993 
3994 void OnTick_Station()
3995 {
3996  if (_game_mode == GM_EDITOR) return;
3997 
3998  for (BaseStation *st : BaseStation::Iterate()) {
3999  StationHandleSmallTick(st);
4000 
4001  /* Clean up the link graph about once a week. */
4004  };
4005 
4006  /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */
4008  /* Stop processing this station if it was deleted */
4009  if (!StationHandleBigTick(st)) continue;
4010  }
4011 
4012  /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */
4014  TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
4015  TriggerRoadStopAnimation(st, st->xy, SAT_250_TICKS);
4016  if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
4017  }
4018  }
4019 }
4020 
4022 static IntervalTimer<TimerGameEconomy> _economy_stations_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::STATION}, [](auto)
4023 {
4024  for (Station *st : Station::Iterate()) {
4025  for (GoodsEntry &ge : st->goods) {
4028  }
4029  }
4030 });
4031 
4032 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
4033 {
4034  ForAllStationsRadius(tile, radius, [&](Station *st) {
4035  if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
4036  for (GoodsEntry &ge : st->goods) {
4037  if (ge.status != 0) {
4038  ge.rating = ClampTo<uint8_t>(ge.rating + amount);
4039  }
4040  }
4041  }
4042  });
4043 }
4044 
4045 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
4046 {
4047  /* We can't allocate a CargoPacket? Then don't do anything
4048  * at all; i.e. just discard the incoming cargo. */
4049  if (!CargoPacket::CanAllocateItem()) return 0;
4050 
4051  GoodsEntry &ge = st->goods[type];
4052  amount += ge.amount_fract;
4053  ge.amount_fract = GB(amount, 0, 8);
4054 
4055  amount >>= 8;
4056  /* No new "real" cargo item yet. */
4057  if (amount == 0) return 0;
4058 
4059  StationID next = ge.GetVia(st->index);
4060  ge.cargo.Append(new CargoPacket(st->index, amount, source_type, source_id), next);
4061  LinkGraph *lg = nullptr;
4062  if (ge.link_graph == INVALID_LINK_GRAPH) {
4064  lg = new LinkGraph(type);
4066  ge.link_graph = lg->index;
4067  ge.node = lg->AddNode(st);
4068  } else {
4069  Debug(misc, 0, "Can't allocate link graph");
4070  }
4071  } else {
4072  lg = LinkGraph::Get(ge.link_graph);
4073  }
4074  if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
4075 
4076  if (!ge.HasRating()) {
4079  }
4080 
4082  TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
4083  AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
4085  TriggerRoadStopAnimation(st, st->xy, SAT_NEW_CARGO, type);
4086 
4087 
4089  st->MarkTilesDirty(true);
4090  return amount;
4091 }
4092 
4093 static bool IsUniqueStationName(const std::string &name)
4094 {
4095  for (const Station *st : Station::Iterate()) {
4096  if (!st->name.empty() && st->name == name) return false;
4097  }
4098 
4099  return true;
4100 }
4101 
4109 CommandCost CmdRenameStation(DoCommandFlag flags, StationID station_id, const std::string &text)
4110 {
4111  Station *st = Station::GetIfValid(station_id);
4112  if (st == nullptr) return CMD_ERROR;
4113 
4114  CommandCost ret = CheckOwnership(st->owner);
4115  if (ret.Failed()) return ret;
4116 
4117  bool reset = text.empty();
4118 
4119  if (!reset) {
4121  if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
4122  }
4123 
4124  if (flags & DC_EXEC) {
4125  st->cached_name.clear();
4126  if (reset) {
4127  st->name.clear();
4128  } else {
4129  st->name = text;
4130  }
4131 
4132  st->UpdateVirtCoord();
4134  }
4135 
4136  return CommandCost();
4137 }
4138 
4139 static void AddNearbyStationsByCatchment(TileIndex tile, StationList *stations, StationList &nearby)
4140 {
4141  for (Station *st : nearby) {
4142  if (st->TileIsInCatchment(tile)) stations->insert(st);
4143  }
4144 }
4145 
4151 {
4152  if (this->tile != INVALID_TILE) {
4153  if (IsTileType(this->tile, MP_HOUSE)) {
4154  /* Town nearby stations need to be filtered per tile. */
4155  assert(this->w == 1 && this->h == 1);
4156  AddNearbyStationsByCatchment(this->tile, &this->stations, Town::GetByTile(this->tile)->stations_near);
4157  } else {
4158  ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex) {
4159  this->stations.insert(st);
4160  return true;
4161  });
4162  }
4163  this->tile = INVALID_TILE;
4164  }
4165  return &this->stations;
4166 }
4167 
4168 
4169 static bool CanMoveGoodsToStation(const Station *st, CargoID type)
4170 {
4171  /* Is the station reserved exclusively for somebody else? */
4172  if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
4173 
4174  /* Lowest possible rating, better not to give cargo anymore. */
4175  if (st->goods[type].rating == 0) return false;
4176 
4177  /* Selectively servicing stations, and not this one. */
4178  if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) return false;
4179 
4180  if (IsCargoInClass(type, CC_PASSENGERS)) {
4181  /* Passengers are never served by just a truck stop. */
4182  if (st->facilities == FACIL_TRUCK_STOP) return false;
4183  } else {
4184  /* Non-passengers are never served by just a bus stop. */
4185  if (st->facilities == FACIL_BUS_STOP) return false;
4186  }
4187  return true;
4188 }
4189 
4190 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations, Owner exclusivity)
4191 {
4192  /* Return if nothing to do. Also the rounding below fails for 0. */
4193  if (all_stations->empty()) return 0;
4194  if (amount == 0) return 0;
4195 
4196  Station *first_station = nullptr;
4197  typedef std::pair<Station *, uint> StationInfo;
4198  std::vector<StationInfo> used_stations;
4199 
4200  for (Station *st : *all_stations) {
4201  if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4202  if (!CanMoveGoodsToStation(st, type)) continue;
4203 
4204  /* Avoid allocating a vector if there is only one station to significantly
4205  * improve performance in this common case. */
4206  if (first_station == nullptr) {
4207  first_station = st;
4208  continue;
4209  }
4210  if (used_stations.empty()) {
4211  used_stations.reserve(2);
4212  used_stations.emplace_back(std::make_pair(first_station, 0));
4213  }
4214  used_stations.emplace_back(std::make_pair(st, 0));
4215  }
4216 
4217  /* no stations around at all? */
4218  if (first_station == nullptr) return 0;
4219 
4220  if (used_stations.empty()) {
4221  /* only one station around */
4222  amount *= first_station->goods[type].rating + 1;
4223  return UpdateStationWaiting(first_station, type, amount, source_type, source_id);
4224  }
4225 
4226  uint company_best[OWNER_NONE + 1] = {}; // best rating for each company, including OWNER_NONE
4227  uint company_sum[OWNER_NONE + 1] = {}; // sum of ratings for each company
4228  uint best_rating = 0;
4229  uint best_sum = 0; // sum of best ratings for each company
4230 
4231  for (auto &p : used_stations) {
4232  auto owner = p.first->owner;
4233  auto rating = p.first->goods[type].rating;
4234  if (rating > company_best[owner]) {
4235  best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
4236  company_best[owner] = rating;
4237  if (rating > best_rating) best_rating = rating;
4238  }
4239  company_sum[owner] += rating;
4240  }
4241 
4242  /* From now we'll calculate with fractional cargo amounts.
4243  * First determine how much cargo we really have. */
4244  amount *= best_rating + 1;
4245 
4246  uint moving = 0;
4247  for (auto &p : used_stations) {
4248  uint owner = p.first->owner;
4249  /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4250  * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4251  p.second = amount * company_best[owner] * p.first->goods[type].rating / best_sum / company_sum[owner];
4252  moving += p.second;
4253  }
4254 
4255  /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4256  if (amount > moving) {
4257  std::stable_sort(used_stations.begin(), used_stations.end(), [type](const StationInfo &a, const StationInfo &b) {
4258  return b.first->goods[type].rating < a.first->goods[type].rating;
4259  });
4260 
4261  assert(amount - moving <= used_stations.size());
4262  for (uint i = 0; i < amount - moving; i++) {
4263  used_stations[i].second++;
4264  }
4265  }
4266 
4267  uint moved = 0;
4268  for (auto &p : used_stations) {
4269  moved += UpdateStationWaiting(p.first, type, p.second, source_type, source_id);
4270  }
4271 
4272  return moved;
4273 }
4274 
4275 void UpdateStationDockingTiles(Station *st)
4276 {
4277  st->docking_station.Clear();
4278 
4279  /* For neutral stations, start with the industry area instead of dock area */
4280  const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4281 
4282  if (area->tile == INVALID_TILE) return;
4283 
4284  int x = TileX(area->tile);
4285  int y = TileY(area->tile);
4286 
4287  /* Expand the area by a tile on each side while
4288  * making sure that we remain inside the map. */
4289  int x2 = std::min<int>(x + area->w + 1, Map::SizeX());
4290  int x1 = std::max<int>(x - 1, 0);
4291 
4292  int y2 = std::min<int>(y + area->h + 1, Map::SizeY());
4293  int y1 = std::max<int>(y - 1, 0);
4294 
4295  TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4296  for (TileIndex tile : ta) {
4297  if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4298  }
4299 }
4300 
4301 void BuildOilRig(TileIndex tile)
4302 {
4303  if (!Station::CanAllocateItem()) {
4304  Debug(misc, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4305  return;
4306  }
4307 
4308  Station *st = new Station(tile);
4309  _station_kdtree.Insert(st->index);
4310  st->town = ClosestTownFromTile(tile, UINT_MAX);
4311 
4312  st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
4313 
4314  assert(IsTileType(tile, MP_INDUSTRY));
4315  /* Mark industry as associated both ways */
4316  st->industry = Industry::GetByTile(tile);
4317  st->industry->neutral_station = st;
4318  DeleteAnimatedTile(tile);
4319  MakeOilrig(tile, st->index, GetWaterClass(tile));
4320 
4321  st->owner = OWNER_NONE;
4322  st->airport.type = AT_OILRIG;
4323  st->airport.Add(tile);
4324  st->ship_station.Add(tile);
4327  UpdateStationDockingTiles(st);
4328 
4329  st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
4330 
4331  st->UpdateVirtCoord();
4332 
4333  /* An industry tile has now been replaced with a station tile, this may change the overlap between station catchments and industry tiles.
4334  * Recalculate the station catchment for all stations currently in the industry's nearby list.
4335  * Clear the industry's station nearby list first because Station::RecomputeCatchment cannot remove nearby industries in this case. */
4337  StationList nearby = std::move(st->industry->stations_near);
4338  st->industry->stations_near.clear();
4339  for (Station *near : nearby) {
4340  near->RecomputeCatchment(true);
4341  UpdateStationAcceptance(near, true);
4342  }
4343  }
4344 
4345  st->RecomputeCatchment();
4346  UpdateStationAcceptance(st, false);
4347 }
4348 
4349 void DeleteOilRig(TileIndex tile)
4350 {
4351  Station *st = Station::GetByTile(tile);
4352 
4353  MakeWaterKeepingClass(tile, OWNER_NONE);
4354 
4355  /* The oil rig station is not supposed to be shared with anything else */
4356  assert(st->facilities == (FACIL_AIRPORT | FACIL_DOCK) && st->airport.type == AT_OILRIG);
4357  if (st->industry != nullptr && st->industry->neutral_station == st) {
4358  /* Don't leave dangling neutral station pointer */
4359  st->industry->neutral_station = nullptr;
4360  }
4361  delete st;
4362 }
4363 
4364 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4365 {
4366  if (IsRoadStopTile(tile)) {
4367  for (RoadTramType rtt : _roadtramtypes) {
4368  /* Update all roadtypes, no matter if they are present */
4369  if (GetRoadOwner(tile, rtt) == old_owner) {
4370  RoadType rt = GetRoadType(tile, rtt);
4371  if (rt != INVALID_ROADTYPE) {
4372  /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4373  Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4374  if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4375  }
4376  SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4377  }
4378  }
4379  }
4380 
4381  if (!IsTileOwner(tile, old_owner)) return;
4382 
4383  if (new_owner != INVALID_OWNER) {
4384  /* Update company infrastructure counts. Only do it here
4385  * if the new owner is valid as otherwise the clear
4386  * command will do it for us. No need to dirty windows
4387  * here, we'll redraw the whole screen anyway.*/
4388  Company *old_company = Company::Get(old_owner);
4389  Company *new_company = Company::Get(new_owner);
4390 
4391  /* Update counts for underlying infrastructure. */
4392  switch (GetStationType(tile)) {
4393  case STATION_RAIL:
4394  case STATION_WAYPOINT:
4395  if (!IsStationTileBlocked(tile)) {
4396  old_company->infrastructure.rail[GetRailType(tile)]--;
4397  new_company->infrastructure.rail[GetRailType(tile)]++;
4398  }
4399  break;
4400 
4401  case STATION_BUS:
4402  case STATION_TRUCK:
4403  /* Road stops were already handled above. */
4404  break;
4405 
4406  case STATION_BUOY:
4407  case STATION_DOCK:
4408  if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
4409  old_company->infrastructure.water--;
4410  new_company->infrastructure.water++;
4411  }
4412  break;
4413 
4414  default:
4415  break;
4416  }
4417 
4418  /* Update station tile count. */
4419  if (!IsBuoy(tile) && !IsAirport(tile)) {
4420  old_company->infrastructure.station--;
4421  new_company->infrastructure.station++;
4422  }
4423 
4424  /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4425  SetTileOwner(tile, new_owner);
4427  } else {
4428  if (IsDriveThroughStopTile(tile)) {
4429  /* Remove the drive-through road stop */
4430  Command<CMD_REMOVE_ROAD_STOP>::Do(DC_EXEC | DC_BANKRUPT, tile, 1, 1, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, false);
4431  assert(IsTileType(tile, MP_ROAD));
4432  /* Change owner of tile and all roadtypes */
4433  ChangeTileOwner(tile, old_owner, new_owner);
4434  } else {
4436  /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4437  * Update owner of buoy if it was not removed (was in orders).
4438  * Do not update when owned by OWNER_WATER (sea and rivers). */
4439  if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4440  }
4441  }
4442 }
4443 
4453 {
4454  /* Water flooding can always clear road stops. */
4455  if (_current_company == OWNER_WATER) return CommandCost();
4456 
4457  CommandCost ret;
4458 
4459  if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4460  Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
4461  if (tram_owner != OWNER_NONE) {
4462  ret = CheckOwnership(tram_owner);
4463  if (ret.Failed()) return ret;
4464  }
4465  }
4466 
4467  if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4468  Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
4469  if (road_owner == OWNER_TOWN) {
4470  ret = CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, RTT_ROAD), OWNER_TOWN, RTT_ROAD, flags);
4471  if (ret.Failed()) return ret;
4472  } else if (road_owner != OWNER_NONE) {
4473  ret = CheckOwnership(road_owner);
4474  if (ret.Failed()) return ret;
4475  }
4476  }
4477 
4478  return CommandCost();
4479 }
4480 
4488 {
4489  if (flags & DC_AUTO) {
4490  switch (GetStationType(tile)) {
4491  default: break;
4492  case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4493  case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4494  case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4495  case STATION_TRUCK: return_cmd_error(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4496  case STATION_BUS: return_cmd_error(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4497  case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4498  case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4499  case STATION_OILRIG:
4500  SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4501  return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4502  }
4503  }
4504 
4505  switch (GetStationType(tile)) {
4506  case STATION_RAIL: return RemoveRailStation(tile, flags);
4507  case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4508  case STATION_AIRPORT: return RemoveAirport(tile, flags);
4509  case STATION_TRUCK: [[fallthrough]];
4510  case STATION_BUS:
4511  if (IsDriveThroughStopTile(tile)) {
4512  CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4513  if (remove_road.Failed()) return remove_road;
4514  }
4515  return RemoveRoadStop(tile, flags);
4516  case STATION_BUOY: return RemoveBuoy(tile, flags);
4517  case STATION_DOCK: return RemoveDock(tile, flags);
4518  default: break;
4519  }
4520 
4521  return CMD_ERROR;
4522 }
4523 
4524 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4525 {
4527  /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4528  * TTDP does not call it.
4529  */
4530  if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4531  switch (GetStationType(tile)) {
4532  case STATION_WAYPOINT:
4533  case STATION_RAIL: {
4534  DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4535  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4536  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4537  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4538  }
4539 
4540  case STATION_AIRPORT:
4541  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4542 
4543  case STATION_TRUCK:
4544  case STATION_BUS: {
4545  DiagDirection direction = GetRoadStopDir(tile);
4546  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4547  if (IsDriveThroughStopTile(tile)) {
4548  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4549  }
4550  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4551  }
4552 
4553  default: break;
4554  }
4555  }
4556  }
4557  return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
4558 }
4559 
4565 uint FlowStat::GetShare(StationID st) const
4566 {
4567  uint32_t prev = 0;
4568  for (const auto &it : this->shares) {
4569  if (it.second == st) {
4570  return it.first - prev;
4571  } else {
4572  prev = it.first;
4573  }
4574  }
4575  return 0;
4576 }
4577 
4584 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4585 {
4586  if (this->unrestricted == 0) return INVALID_STATION;
4587  assert(!this->shares.empty());
4588  SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4589  assert(it != this->shares.end() && it->first <= this->unrestricted);
4590  if (it->second != excluded && it->second != excluded2) return it->second;
4591 
4592  /* We've hit one of the excluded stations.
4593  * Draw another share, from outside its range. */
4594 
4595  uint end = it->first;
4596  uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4597  uint interval = end - begin;
4598  if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4599  uint new_max = this->unrestricted - interval;
4600  uint rand = RandomRange(new_max);
4601  SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4602  this->shares.upper_bound(rand + interval);
4603  assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4604  if (it2->second != excluded && it2->second != excluded2) return it2->second;
4605 
4606  /* We've hit the second excluded station.
4607  * Same as before, only a bit more complicated. */
4608 
4609  uint end2 = it2->first;
4610  uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4611  uint interval2 = end2 - begin2;
4612  if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4613  new_max -= interval2;
4614  if (begin > begin2) {
4615  Swap(begin, begin2);
4616  Swap(end, end2);
4617  Swap(interval, interval2);
4618  }
4619  rand = RandomRange(new_max);
4620  SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4621  if (rand < begin) {
4622  it3 = this->shares.upper_bound(rand);
4623  } else if (rand < begin2 - interval) {
4624  it3 = this->shares.upper_bound(rand + interval);
4625  } else {
4626  it3 = this->shares.upper_bound(rand + interval + interval2);
4627  }
4628  assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4629  return it3->second;
4630 }
4631 
4638 {
4639  assert(!this->shares.empty());
4640  SharesMap new_shares;
4641  uint i = 0;
4642  for (const auto &it : this->shares) {
4643  new_shares[++i] = it.second;
4644  if (it.first == this->unrestricted) this->unrestricted = i;
4645  }
4646  this->shares.swap(new_shares);
4647  assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4648 }
4649 
4656 void FlowStat::ChangeShare(StationID st, int flow)
4657 {
4658  /* We assert only before changing as afterwards the shares can actually
4659  * be empty. In that case the whole flow stat must be deleted then. */
4660  assert(!this->shares.empty());
4661 
4662  uint removed_shares = 0;
4663  uint added_shares = 0;
4664  uint last_share = 0;
4665  SharesMap new_shares;
4666  for (const auto &it : this->shares) {
4667  if (it.second == st) {
4668  if (flow < 0) {
4669  uint share = it.first - last_share;
4670  if (flow == INT_MIN || (uint)(-flow) >= share) {
4671  removed_shares += share;
4672  if (it.first <= this->unrestricted) this->unrestricted -= share;
4673  if (flow != INT_MIN) flow += share;
4674  last_share = it.first;
4675  continue; // remove the whole share
4676  }
4677  removed_shares += (uint)(-flow);
4678  } else {
4679  added_shares += (uint)(flow);
4680  }
4681  if (it.first <= this->unrestricted) this->unrestricted += flow;
4682 
4683  /* If we don't continue above the whole flow has been added or
4684  * removed. */
4685  flow = 0;
4686  }
4687  new_shares[it.first + added_shares - removed_shares] = it.second;
4688  last_share = it.first;
4689  }
4690  if (flow > 0) {
4691  new_shares[last_share + (uint)flow] = st;
4692  if (this->unrestricted < last_share) {
4693  this->ReleaseShare(st);
4694  } else {
4695  this->unrestricted += flow;
4696  }
4697  }
4698  this->shares.swap(new_shares);
4699 }
4700 
4706 void FlowStat::RestrictShare(StationID st)
4707 {
4708  assert(!this->shares.empty());
4709  uint flow = 0;
4710  uint last_share = 0;
4711  SharesMap new_shares;
4712  for (auto &it : this->shares) {
4713  if (flow == 0) {
4714  if (it.first > this->unrestricted) return; // Not present or already restricted.
4715  if (it.second == st) {
4716  flow = it.first - last_share;
4717  this->unrestricted -= flow;
4718  } else {
4719  new_shares[it.first] = it.second;
4720  }
4721  } else {
4722  new_shares[it.first - flow] = it.second;
4723  }
4724  last_share = it.first;
4725  }
4726  if (flow == 0) return;
4727  new_shares[last_share + flow] = st;
4728  this->shares.swap(new_shares);
4729  assert(!this->shares.empty());
4730 }
4731 
4737 void FlowStat::ReleaseShare(StationID st)
4738 {
4739  assert(!this->shares.empty());
4740  uint flow = 0;
4741  uint next_share = 0;
4742  bool found = false;
4743  for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4744  if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4745  if (found) {
4746  flow = next_share - it->first;
4747  this->unrestricted += flow;
4748  break;
4749  } else {
4750  if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4751  if (it->second == st) found = true;
4752  }
4753  next_share = it->first;
4754  }
4755  if (flow == 0) return;
4756  SharesMap new_shares;
4757  new_shares[flow] = st;
4758  for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4759  if (it->second != st) {
4760  new_shares[flow + it->first] = it->second;
4761  } else {
4762  flow = 0;
4763  }
4764  }
4765  this->shares.swap(new_shares);
4766  assert(!this->shares.empty());
4767 }
4768 
4774 void FlowStat::ScaleToMonthly(uint runtime)
4775 {
4776  assert(runtime > 0);
4777  SharesMap new_shares;
4778  uint share = 0;
4779  for (auto i : this->shares) {
4780  share = std::max(share + 1, i.first * 30 / runtime);
4781  new_shares[share] = i.second;
4782  if (this->unrestricted == i.first) this->unrestricted = share;
4783  }
4784  this->shares.swap(new_shares);
4785 }
4786 
4793 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
4794 {
4795  FlowStatMap::iterator origin_it = this->find(origin);
4796  if (origin_it == this->end()) {
4797  this->insert(std::make_pair(origin, FlowStat(via, flow)));
4798  } else {
4799  origin_it->second.ChangeShare(via, flow);
4800  assert(!origin_it->second.GetShares()->empty());
4801  }
4802 }
4803 
4812 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
4813 {
4814  FlowStatMap::iterator prev_it = this->find(origin);
4815  if (prev_it == this->end()) {
4816  FlowStat fs(via, flow);
4817  fs.AppendShare(INVALID_STATION, flow);
4818  this->insert(std::make_pair(origin, fs));
4819  } else {
4820  prev_it->second.ChangeShare(via, flow);
4821  prev_it->second.ChangeShare(INVALID_STATION, flow);
4822  assert(!prev_it->second.GetShares()->empty());
4823  }
4824 }
4825 
4831 {
4832  for (auto &i : *this) {
4833  FlowStat &fs = i.second;
4834  uint local = fs.GetShare(INVALID_STATION);
4835  if (local > INT_MAX) { // make sure it fits in an int
4836  fs.ChangeShare(self, -INT_MAX);
4837  fs.ChangeShare(INVALID_STATION, -INT_MAX);
4838  local -= INT_MAX;
4839  }
4840  fs.ChangeShare(self, -(int)local);
4841  fs.ChangeShare(INVALID_STATION, -(int)local);
4842 
4843  /* If the local share is used up there must be a share for some
4844  * remote station. */
4845  assert(!fs.GetShares()->empty());
4846  }
4847 }
4848 
4856 {
4857  StationIDStack ret;
4858  for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
4859  FlowStat &s_flows = f_it->second;
4860  s_flows.ChangeShare(via, INT_MIN);
4861  if (s_flows.GetShares()->empty()) {
4862  ret.Push(f_it->first);
4863  this->erase(f_it++);
4864  } else {
4865  ++f_it;
4866  }
4867  }
4868  return ret;
4869 }
4870 
4875 void FlowStatMap::RestrictFlows(StationID via)
4876 {
4877  for (auto &it : *this) {
4878  it.second.RestrictShare(via);
4879  }
4880 }
4881 
4886 void FlowStatMap::ReleaseFlows(StationID via)
4887 {
4888  for (auto &it : *this) {
4889  it.second.ReleaseShare(via);
4890  }
4891 }
4892 
4898 {
4899  uint ret = 0;
4900  for (const auto &it : *this) {
4901  ret += (--(it.second.GetShares()->end()))->first;
4902  }
4903  return ret;
4904 }
4905 
4911 uint FlowStatMap::GetFlowVia(StationID via) const
4912 {
4913  uint ret = 0;
4914  for (const auto &it : *this) {
4915  ret += it.second.GetShare(via);
4916  }
4917  return ret;
4918 }
4919 
4925 uint FlowStatMap::GetFlowFrom(StationID from) const
4926 {
4927  FlowStatMap::const_iterator i = this->find(from);
4928  if (i == this->end()) return 0;
4929  return (--(i->second.GetShares()->end()))->first;
4930 }
4931 
4938 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
4939 {
4940  FlowStatMap::const_iterator i = this->find(from);
4941  if (i == this->end()) return 0;
4942  return i->second.GetShare(via);
4943 }
4944 
4945 extern const TileTypeProcs _tile_type_station_procs = {
4946  DrawTile_Station, // draw_tile_proc
4947  GetSlopePixelZ_Station, // get_slope_z_proc
4948  ClearTile_Station, // clear_tile_proc
4949  nullptr, // add_accepted_cargo_proc
4950  GetTileDesc_Station, // get_tile_desc_proc
4951  GetTileTrackStatus_Station, // get_tile_track_status_proc
4952  ClickTile_Station, // click_tile_proc
4953  AnimateTile_Station, // animate_tile_proc
4954  TileLoop_Station, // tile_loop_proc
4955  ChangeTileOwner_Station, // change_tile_owner_proc
4956  nullptr, // add_produced_cargo_proc
4957  VehicleEnter_Station, // vehicle_enter_tile_proc
4958  GetFoundation_Station, // get_foundation_proc
4959  TerraformTile_Station, // terraform_tile_proc
4960 };
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
VETS_STATION_ID_OFFSET
@ VETS_STATION_ID_OFFSET
Shift the VehicleEnterTileStatus this many bits to the right to get the station ID when VETS_ENTERED_...
Definition: tile_cmd.h:31
AllocateSpecToStation
int AllocateSpecToStation(const StationSpec *statspec, BaseStation *st, bool exec)
Allocate a StationSpec to a Station.
Definition: newgrf_station.cpp:689
RoadVehicle
Buses, trucks and trams belong to this class.
Definition: roadveh.h:106
AAT_STATION_250_TICKS
@ AAT_STATION_250_TICKS
Triggered every 250 ticks (for all tiles at the same time).
Definition: newgrf_animation_type.h:51
TileY
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:437
TileInfo::z
int z
Height.
Definition: tile_cmd.h:48
TileDesc::airport_class
StringID airport_class
Name of the airport class.
Definition: tile_cmd.h:60
Vehicle::IsFrontEngine
debug_inline bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:941
MP_HOUSE
@ MP_HOUSE
A house by a town.
Definition: tile_type.h:51
DeleteNewGRFInspectWindow
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Definition: newgrf_debug_gui.cpp:739
IsTileFlat
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:100
BaseStation::facilities
StationFacility facilities
The facilities that this station has.
Definition: base_station_base.h:75
DIAGDIR_SE
@ DIAGDIR_SE
Southeast.
Definition: direction_type.h:76
TileDesc::grf
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:63
SplitGroundSpriteForOverlay
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...
Definition: station_cmd.cpp:2883
RemoveRailWaypoint
static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
Remove a rail waypoint.
Definition: station_cmd.cpp:1825
VETSB_CANNOT_ENTER
@ VETSB_CANNOT_ENTER
The vehicle cannot enter the tile.
Definition: tile_cmd.h:38
VehicleCargoList::StoredCount
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:434
CmdBuildRoadStop
CommandCost CmdBuildRoadStop(DoCommandFlag 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.
Definition: station_cmd.cpp:1930
TROPICZONE_DESERT
@ TROPICZONE_DESERT
Tile is desert.
Definition: tile_type.h:78
INVALID_AIRPORTTILE
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition: airport.h:25
FlowStat::ScaleToMonthly
void ScaleToMonthly(uint runtime)
Scale all shares from link graph's runtime to monthly values.
Definition: station_cmd.cpp:4774
BaseStation::speclist
std::vector< StationSpecList > speclist
List of rail station specs of this station.
Definition: base_station_base.h:77
RoadTypeInfo
Definition: road.h:78
RoadVehicle::state
byte state
Definition: roadveh.h:108
Station::docking_station
TileArea docking_station
Tile area the docking tiles cover.
Definition: station_base.h:458
AIRPORT_CLOSED_block
static const uint64_t AIRPORT_CLOSED_block
Dummy block for indicating a closed airport.
Definition: airport.h:128
ROTSG_GROUND
@ ROTSG_GROUND
Required: Main group of ground images.
Definition: road.h:62
CanExpandRailStation
CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta)
Check whether we can expand the rail part of the given station.
Definition: station_cmd.cpp:1078
InvalidateWindowData
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:3204
Industry::owner
Owner owner
owner of the industry. Which SHOULD always be (imho) OWNER_NONE
Definition: industry.h:105
WID_SV_ACCEPT_RATING_LIST
@ WID_SV_ACCEPT_RATING_LIST
List of accepted cargoes / rating of cargoes.
Definition: station_widget.h:22
FlowStat::Invalidate
void Invalidate()
Reduce all flows to minimum capacity so that they don't get in the way of link usage statistics too m...
Definition: station_cmd.cpp:4637
GroundSpritePaletteTransform
PaletteID GroundSpritePaletteTransform(SpriteID image, PaletteID pal, PaletteID default_pal)
Applies PALETTE_MODIFIER_COLOUR to a palette entry of a ground sprite.
Definition: sprite.h:168
SmallStack
Minimal stack that uses a pool to avoid pointers.
Definition: smallstack_type.hpp:135
AXIS_Y
@ AXIS_Y
The y axis.
Definition: direction_type.h:118
Airport::flags
uint64_t flags
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
Definition: station_base.h:293
Station::goods
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:471
TRACK_BIT_NONE
@ TRACK_BIT_NONE
No track.
Definition: track_type.h:36
ROADSTOPTYPE_ALL
@ ROADSTOPTYPE_ALL
This RoadStop is for both types of station road stops.
Definition: newgrf_roadstop.h:49
NUM_INDUSTRYTYPES
static const IndustryType NUM_INDUSTRYTYPES
total number of industry types, new and old; limited to 240 because we need some special ids like INV...
Definition: industry_type.h:26
StationRect
StationRect - used to track station spread out rectangle - cheaper than scanning whole map.
Definition: base_station_base.h:41
GoodsEntry::rating
uint8_t rating
Station rating for this cargo.
Definition: station_base.h:226
StationGfx
byte StationGfx
Copy from station_map.h.
Definition: newgrf_airport.h:22
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
linkgraph_base.h
newgrf_station.h
newgrf_house.h
GetAcceptanceAroundStation
static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
Get the acceptance of cargoes around the station in.
Definition: station_cmd.cpp:603
FlowStat::unrestricted
uint unrestricted
Limit for unrestricted shares.
Definition: station_base.h:144
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:71
Pool::PoolItem<&_industry_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:339
GetDisallowedRoadDirections
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
Definition: road_map.h:301
MakeRoadStop
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.
Definition: station_map.h:682
TimerGameTick::counter
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Definition: timer_game_tick.h:60
StationSpec::flags
byte flags
Bitmask of flags, bit 0: use different sprite set; bit 1: divide cargo about by station size.
Definition: newgrf_station.h:159
station_kdtree.h
Direction
Direction
Defines the 8 directions on the map.
Definition: direction_type.h:24
FindJoiningWaypoint
CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
Find a nearby waypoint that joins this waypoint.
Definition: station_cmd.cpp:1218
FlowStatMap::GetFlowVia
uint GetFlowVia(StationID via) const
Get the sum of flows via a specific station from this FlowStatMap.
Definition: station_cmd.cpp:4911
Airport::GetHangarNum
uint GetHangarNum(TileIndex tile) const
Get the hangar number of the hangar at a specific tile.
Definition: station_base.h:388
GameSettings::station
StationSettings station
settings related to station management
Definition: settings_type.h:629
AirportSpec::IsWithinMapBounds
bool IsWithinMapBounds(byte table, TileIndex index) const
Check if the airport would be within the map bounds at the given tile.
Definition: newgrf_airport.cpp:95
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3086
water.h
LinkGraph
A connected component of a link graph.
Definition: linkgraph.h:37
GetTileMaxZ
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:141
StationSpec::renderdata
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
Definition: newgrf_station.h:147
GetAcceptanceAroundTiles
CargoArray GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad, CargoTypes *always_accepted)
Get the acceptance of cargoes around the tile in 1/8.
Definition: station_cmd.cpp:581
Station::AfterStationTileSetChange
void AfterStationTileSetChange(bool adding, StationType type)
After adding/removing tiles to station, update some station-related stuff.
Definition: station_cmd.cpp:749
FlowStatMap::GetFlow
uint GetFlow() const
Get the sum of all flows from this FlowStatMap.
Definition: station_cmd.cpp:4897
train.h
RoadStopType
RoadStopType
Types of RoadStops.
Definition: station_type.h:43
ROADSTOP_TRUCK
@ ROADSTOP_TRUCK
A standard stop for trucks.
Definition: station_type.h:45
ValParamRailType
bool ValParamRailType(const RailType rail)
Validate functions for rail building.
Definition: rail.cpp:206
command_func.h
SmallStack::Push
void Push(const Titem &item)
Pushes a new item onto the stack if there is still space in the underlying pool.
Definition: smallstack_type.hpp:192
RoadStopSpec
Road stop specification.
Definition: newgrf_roadstop.h:122
YapfNotifyTrackLayoutChange
void YapfNotifyTrackLayoutChange(TileIndex tile, Track track)
Use this function to notify YAPF that track layout (or signal configuration) has change.
Definition: yapf_rail.cpp:644
Swap
constexpr void Swap(T &a, T &b)
Type safe swap operation.
Definition: math_func.hpp:283
Pool::PoolItem<&_link_graph_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:350
RerouteCargo
void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
Reroute cargo of type c at station st or in any vehicles unloading there.
Definition: station_cmd.cpp:3796
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
UpdateAirplanesOnNewStation
void UpdateAirplanesOnNewStation(const Station *st)
Updates the status of the Aircraft heading or in the station.
Definition: aircraft_cmd.cpp:2162
FlatteningFoundation
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:369
CanBuildDepotByTileh
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
GetRailTypeInfo
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:307
RailTypeInfo::GetRailtypeSpriteOffset
uint GetRailtypeSpriteOffset() const
Offset between the current railtype and normal rail.
Definition: rail.h:295
SSF_EXTENDED_FOUNDATIONS
@ SSF_EXTENDED_FOUNDATIONS
Extended foundation block instead of simple.
Definition: newgrf_station.h:98
ClosestTownFromTile
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition: town_cmd.cpp:3783
SAT_250_TICKS
@ SAT_250_TICKS
Trigger station every 250 ticks.
Definition: newgrf_animation_type.h:33
TO_BUILDINGS
@ TO_BUILDINGS
company buildings - depots, stations, HQ, ...
Definition: transparency.h:27
TileInfo
Tile information, used while rendering the tile.
Definition: tile_cmd.h:43
StationHandleBigTick
static bool StationHandleBigTick(BaseStation *st)
This function is called for each station once every 250 ticks.
Definition: station_cmd.cpp:3580
IsRailStation
bool IsRailStation(Tile t)
Is this station tile a rail station?
Definition: station_map.h:92
FlowStat::ReleaseShare
void ReleaseShare(StationID st)
Release ("unrestrict") a flow by moving it to the begin of the map and increasing the amount of unres...
Definition: station_cmd.cpp:4737
GetWaterClass
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition: water_map.h:115
SPRITE_WIDTH
@ SPRITE_WIDTH
number of bits for the sprite number
Definition: sprites.h:1527
GameCreationSettings::landscape
byte landscape
the landscape we're currently in
Definition: settings_type.h:355
TileDesc::railtype
StringID railtype
Type of rail on the tile.
Definition: tile_cmd.h:64
Town::statues
CompanyMask statues
which companies have a statue?
Definition: town.h:66
company_base.h
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:628
tunnelbridge_map.h
CargoList::Packets
const Tcont * Packets() const
Returns a pointer to the cargo packet list (so you can iterate over it etc).
Definition: cargopacket.h:329
BaseStation::town
Town * town
The town this station is associated with.
Definition: base_station_base.h:73
timer_game_calendar.h
SetRailStationPlatformReservation
void SetRailStationPlatformReservation(TileIndex start, DiagDirection dir, bool b)
Set the reservation for a complete station platform.
Definition: pbs.cpp:57
FACIL_TRUCK_STOP
@ FACIL_TRUCK_STOP
Station with truck stops.
Definition: station_type.h:53
CBM_CARGO_STATION_RATING_CALC
@ CBM_CARGO_STATION_RATING_CALC
custom station rating for this cargo type
Definition: newgrf_callbacks.h:357
TileDesc::owner
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:55
AirportSpec::size_y
byte size_y
size of airport in y direction
Definition: newgrf_airport.h:108
Axis
Axis
Allow incrementing of DiagDirDiff variables.
Definition: direction_type.h:116
CBID_STATION_AVAILABILITY
@ CBID_STATION_AVAILABILITY
Determine whether a newstation should be made available to build.
Definition: newgrf_callbacks.h:39
Station
Station data structure.
Definition: station_base.h:442
BaseStation::GetByTile
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
Definition: base_station_base.h:171
NewGRFClass::GetSpecCount
uint GetSpecCount() const
Get the number of allocated specs within the class.
Definition: newgrf_class.h:44
company_gui.h
AAT_STATION_NEW_CARGO
@ AAT_STATION_NEW_CARGO
Triggered when new cargo arrives at the station (for all tiles at the same time).
Definition: newgrf_animation_type.h:49
PALETTE_MODIFIER_COLOUR
@ PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition: sprites.h:1542
TrackdirToExitdir
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Definition: track_func.h:439
elrail_func.h
waypoint_cmd.h
AnimationInfo::triggers
uint16_t triggers
The triggers that trigger animation.
Definition: newgrf_animation_type.h:22
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
Price
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:89
AirportSpec::name
StringID name
name of this airport
Definition: newgrf_airport.h:113
CanRemoveRoadWithStop
static CommandCost CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
Check if a drive-through road stop tile can be cleared.
Definition: station_cmd.cpp:4452
CMSAWater
static bool CMSAWater(TileIndex tile)
Check whether the tile is water.
Definition: station_cmd.cpp:194
SAT_NEW_CARGO
@ SAT_NEW_CARGO
Trigger station on new cargo arrival.
Definition: newgrf_animation_type.h:28
TileDesc::station_class
StringID station_class
Class of station.
Definition: tile_cmd.h:58
RemoveRailStation
CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
Remove a rail station/waypoint.
Definition: station_cmd.cpp:1770
TileDesc::road_speed
uint16_t road_speed
Speed limit of road (bridges and track)
Definition: tile_cmd.h:67
DifficultySettings::town_council_tolerance
byte town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition: settings_type.h:116
CloseWindowById
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:1141
BitmapTileIterator
Iterator to iterate over all tiles belonging to a bitmaptilearea.
Definition: bitmap_type.h:106
ROADSTOPTYPE_FREIGHT
@ ROADSTOPTYPE_FREIGHT
This RoadStop is for freight (truck) stops.
Definition: newgrf_roadstop.h:48
Vehicle::vehstatus
byte vehstatus
Status.
Definition: vehicle_base.h:349
IntervalTimer
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition: timer.h:76
GB
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
AAT_BUILT
@ AAT_BUILT
Triggered when the airport is built (for all tiles at the same time).
Definition: newgrf_animation_type.h:47
LinkGraphSchedule::instance
static LinkGraphSchedule instance
Static instance of LinkGraphSchedule.
Definition: linkgraphschedule.h:52
DIAGDIR_END
@ DIAGDIR_END
Used for iterations.
Definition: direction_type.h:79
AutoslopeEnabled
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:44
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:238
DrawRoadCatenary
void DrawRoadCatenary(const TileInfo *ti)
Draws the catenary for the given tile.
Definition: road_cmd.cpp:1451
RVSB_IN_ROAD_STOP
@ RVSB_IN_ROAD_STOP
The vehicle is in a road stop.
Definition: roadveh.h:49
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:131
DiagDirToAxis
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
Definition: direction_func.h:214
CmdOpenCloseAirport
CommandCost CmdOpenCloseAirport(DoCommandFlag flags, StationID station_id)
Open/close an airport to incoming aircraft.
Definition: station_cmd.cpp:2598
FindJoiningBaseStation
CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
Find a nearby station that joins this station.
Definition: station_cmd.cpp:1159
GetAcceptanceMask
CargoTypes GetAcceptanceMask(const Station *st)
Get a mask of the cargo types that the station accepts.
Definition: station_cmd.cpp:497
CargoArray
Class for storing amounts of cargo.
Definition: cargo_type.h:114
TRACK_X
@ TRACK_X
Track along the x-axis (north-east to south-west)
Definition: track_type.h:21
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:23
DT_MANUAL
@ DT_MANUAL
Manual distribution. No link graph calculations are run.
Definition: linkgraph_type.h:25
AirportSpec::noise_level
byte noise_level
noise that this airport generates
Definition: newgrf_airport.h:109
FlowStatMap::PassOnFlow
void PassOnFlow(StationID origin, StationID via, uint amount)
Pass on some flow, remembering it as invalid, for later subtraction from locally consumed flow.
Definition: station_cmd.cpp:4812
LinkGraph::STALE_LINK_DEPOT_TIMEOUT
static constexpr TimerGameEconomy::Date STALE_LINK_DEPOT_TIMEOUT
Number of days before deleting links served only by vehicles stopped in depot.
Definition: linkgraph.h:173
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition: settings_type.h:617
GetTileZ
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition: tile_map.cpp:121
ship.h
CBID_CARGO_STATION_RATING_CALC
@ CBID_CARGO_STATION_RATING_CALC
Called to calculate part of a station rating.
Definition: newgrf_callbacks.h:200
INVALID_TILE
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:95
IsOilRig
bool IsOilRig(Tile t)
Is tile t part of an oilrig?
Definition: station_map.h:275
RailTypeInfo
This struct contains all the info that is needed to draw and construct tracks.
Definition: rail.h:127
VETSB_CONTINUE
@ VETSB_CONTINUE
Bit sets of the above specified bits.
Definition: tile_cmd.h:35
SetStationTileHaveWires
void SetStationTileHaveWires(Tile t, bool b)
Set the catenary wires state of the rail station.
Definition: station_map.h:374
Station::MoveSign
void MoveSign(TileIndex new_xy) override
Move the station main coordinate somewhere else.
Definition: station_cmd.cpp:460
Waypoint
Representation of a waypoint.
Definition: waypoint_base.h:16
CBM_STATION_SLOPE_CHECK
@ CBM_STATION_SLOPE_CHECK
Check slope of new station tiles.
Definition: newgrf_callbacks.h:314
SetStationTileHavePylons
void SetStationTileHavePylons(Tile t, bool b)
Set the catenary pylon state of the rail station.
Definition: station_map.h:398
station_land.h
Airport::layout
byte layout
Airport layout number.
Definition: station_base.h:295
IsCompatibleTrainStationTile
bool IsCompatibleTrainStationTile(Tile test_tile, Tile station_tile)
Check if a tile is a valid continuation to a railstation tile.
Definition: station_map.h:451
RoadStop::GetByTile
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
Definition: roadstop.cpp:266
GetAirportNoiseLevelForDistance
uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
Get a possible noise reduction factor based on distance from town center.
Definition: station_cmd.cpp:2283
IsSteepSlope
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:36
IsRailStationTile
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
Definition: station_map.h:102
EUM_INCREASE
@ EUM_INCREASE
Increase capacity.
Definition: linkgraph_type.h:48
aircraft.h
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
Tile
Wrapper class to abstract away the way the tiles are stored.
Definition: map_func.h:25
Industry::produced
ProducedCargoArray produced
INDUSTRY_NUM_OUTPUTS production cargo slots.
Definition: industry.h:99
CargoSpec::Iterate
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:187
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:259
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:54
DrawRailTileSeqInGUI
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:99
Town::xy
TileIndex xy
town center tile
Definition: town.h:51
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:68
GetRoadStopDir
DiagDirection GetRoadStopDir(Tile t)
Gets the direction the road stop entrance points towards.
Definition: station_map.h:258
SpecializedStation< Station, false >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index is a valid index for station of this type.
Definition: base_station_base.h:250
MP_INDUSTRY
@ MP_INDUSTRY
Part of an industry.
Definition: tile_type.h:56
TRANSPORT_WATER
@ TRANSPORT_WATER
Transport over water.
Definition: transport_type.h:29
newgrf_debug.h
town.h
GetGRFConfig
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:716
TileInfo::y
int y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:45
CC_LIQUID
@ CC_LIQUID
Liquids (Oil, Water, Rubber)
Definition: cargotype.h:56
OrthogonalTileArea::Add
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
Definition: tilearea.cpp:43
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
TileDesc::airport_tile_name
StringID airport_tile_name
Name of the airport tile.
Definition: tile_cmd.h:62
ClampU
constexpr uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
Definition: math_func.hpp:150
GetFoundationPixelSlope
Slope GetFoundationPixelSlope(TileIndex tile, int *z)
Get slope of a tile on top of a (possible) foundation If a tile does not have a foundation,...
Definition: landscape.h:66
Company::infrastructure
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
Definition: company_base.h:143
GetDockDirection
DiagDirection GetDockDirection(Tile t)
Get the direction of a dock.
Definition: station_map.h:502
VS_TRAIN_SLOWING
@ VS_TRAIN_SLOWING
Train is slowing down.
Definition: vehicle_base.h:37
LinkGraph::Size
NodeID Size() const
Get the current size of the component.
Definition: linkgraph.h:230
RemoveRoadStop
static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index=-1)
Remove a bus station/truck stop.
Definition: station_cmd.cpp:2104
WC_STATION_VIEW
@ WC_STATION_VIEW
Station view; Window numbers:
Definition: window_type.h:345
IsWaterTile
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
Definition: water_map.h:193
IndustrySpec::station_name
StringID station_name
Default name for nearby station.
Definition: industrytype.h:132
DIR_W
@ DIR_W
West.
Definition: direction_type.h:32
RoadStop::Enter
bool Enter(RoadVehicle *rv)
Enter the road stop.
Definition: roadstop.cpp:233
NewGRFSpriteLayout::ProcessRegisters
void ProcessRegisters(uint8_t resolved_var10, uint32_t resolved_sprite, bool separate_ground) const
Evaluates the register modifiers and integrates them into the preprocessed sprite layout.
Definition: newgrf_commons.cpp:710
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
CC_PASSENGERS
@ CC_PASSENGERS
Passengers.
Definition: cargotype.h:50
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:240
Industry
Defines the internal data of a functional industry.
Definition: industry.h:68
RailTypeInfo::strings
struct RailTypeInfo::@26 strings
Strings associated with the rail type.
GetRailType
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition: rail_map.h:115
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:305
RestoreTrainReservation
static void RestoreTrainReservation(Train *v)
Restore platform reservation during station building/removing.
Definition: station_cmd.cpp:1239
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
GetStationAround
CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st)
Look for a station owned by the given company around the given tile area.
Definition: station_cmd.cpp:115
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:371
DeallocateSpecFromStation
void DeallocateSpecFromStation(BaseStation *st, byte specindex)
Deallocate a StationSpec from a Station.
Definition: newgrf_station.cpp:731
PaletteID
uint32_t PaletteID
The number of the palette.
Definition: gfx_type.h:18
FlowStatMap::FinalizeLocalConsumption
void FinalizeLocalConsumption(StationID self)
Subtract invalid flows from locally consumed flow.
Definition: station_cmd.cpp:4830
TriggerRoadStopRandomisation
void TriggerRoadStopRandomisation(Station *st, TileIndex tile, RoadStopRandomTrigger trigger, CargoID cargo_type=INVALID_CARGO)
Trigger road stop randomisation.
Definition: newgrf_roadstop.cpp:392
BaseStation::owner
Owner owner
The owner of this station.
Definition: base_station_base.h:74
Station::RecomputeCatchment
void RecomputeCatchment(bool no_clear_nearby_lists=false)
Recompute tiles covered in our catchment area.
Definition: station.cpp:456
MP_ROAD
@ MP_ROAD
A tile with road (or tram tracks)
Definition: tile_type.h:50
AirportSpec
Defines the data structure for an airport.
Definition: newgrf_airport.h:100
MakeRailStation
void MakeRailStation(Tile t, Owner o, StationID sid, Axis a, byte section, RailType rt)
Make the given tile a rail station tile.
Definition: station_map.h:649
CmdBuildRailStation
CommandCost CmdBuildRailStation(DoCommandFlag flags, TileIndex tile_org, RailType rt, Axis axis, byte numtracks, byte plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
Build rail station.
Definition: station_cmd.cpp:1310
WATER_CLASS_INVALID
@ WATER_CLASS_INVALID
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition: water_map.h:51
TileDesc
Tile description for the 'land area information' tool.
Definition: tile_cmd.h:52
FlowStat::GetShare
uint GetShare(StationID st) const
Get flow for a station.
Definition: station_cmd.cpp:4565
GetCustomStationRelocation
SpriteID GetCustomStationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint32_t var10)
Resolve sprites for drawing a station tile.
Definition: newgrf_station.cpp:615
HasExactlyOneBit
constexpr bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit set.
Definition: bitmath_func.hpp:259
TileDesc::airport_name
StringID airport_name
Name of the airport.
Definition: tile_cmd.h:61
CheckIfAuthorityAllowsNewStation
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road,...
Definition: town_cmd.cpp:3741
GetRailStationAxis
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
Definition: station_map.h:410
GoodsEntry::status
byte status
Status of this cargo, see GoodsEntryStatus.
Definition: station_base.h:217
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:369
INVALID_ROADTYPE
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:30
Foundation
Foundation
Enumeration for Foundations.
Definition: slope_type.h:93
EdgeUpdateMode
EdgeUpdateMode
Special modes for updating links.
Definition: linkgraph_type.h:47
OrthogonalTileArea::h
uint16_t h
The height of the area.
Definition: tilearea_type.h:21
EnsureNoVehicleOnGround
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
Definition: vehicle.cpp:546
CompanyInfrastructure::station
uint32_t station
Count of company owned station tiles.
Definition: company_base.h:37
GoodsEntry::time_since_pickup
uint8_t time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
Definition: station_base.h:224
Industry::neutral_station
Station * neutral_station
Associated neutral station.
Definition: industry.h:98
TRACK_BIT_UPPER
@ TRACK_BIT_UPPER
Upper track.
Definition: track_type.h:39
GetAirport
const AirportFTAClass * GetAirport(const byte airport_type)
Get the finite state machine of an airport type.
Definition: airport.cpp:207
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:162
TrackToTrackBits
TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
Definition: track_func.h:77
pbs.h
RandomRange
static uint32_t RandomRange(uint32_t limit)
Pick a random number between 0 and limit - 1, inclusive.
Definition: random_func.hpp:81
Kdtree::Remove
void Remove(const T &element)
Remove a single element from the tree, if it exists.
Definition: kdtree.hpp:417
BaseStation::TileBelongsToRailStation
virtual bool TileBelongsToRailStation(TileIndex tile) const =0
Check whether a specific tile belongs to this station.
AAT_TILELOOP
@ AAT_TILELOOP
Triggered in the periodic tile loop.
Definition: newgrf_animation_type.h:48
BaseStation::string_id
StringID string_id
Default name (town area) of station.
Definition: base_station_base.h:70
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:618
RoadStop::MakeDriveThrough
void MakeDriveThrough()
Join this road stop to another 'base' road stop if possible; fill all necessary data to become an act...
Definition: roadstop.cpp:62
OrthogonalTileArea::Clear
void Clear()
Clears the 'tile area', i.e.
Definition: tilearea_type.h:40
FlowStatMap::RestrictFlows
void RestrictFlows(StationID via)
Restrict all flows at a station for specific cargo and destination.
Definition: station_cmd.cpp:4875
SpecializedStation< Station, false >::Iterate
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Definition: base_station_base.h:310
TRACK_BIT_RIGHT
@ TRACK_BIT_RIGHT
Right track.
Definition: track_type.h:42
FlowStatMap::GetFlowFrom
uint GetFlowFrom(StationID from) const
Get the sum of flows from a specific station from this FlowStatMap.
Definition: station_cmd.cpp:4925
Aircraft
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition: aircraft.h:74
TileInfo::tileh
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:46
ROAD_X
@ ROAD_X
Full road along the x-axis (south-west + north-east)
Definition: road_type.h:58
SSF_SEPARATE_GROUND
@ SSF_SEPARATE_GROUND
Use different sprite set for ground sprites.
Definition: newgrf_station.h:94
RSF_NO_CATENARY
@ RSF_NO_CATENARY
Do not show catenary.
Definition: newgrf_roadstop.h:67
HasPowerOnRoad
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:242
FlowStat
Flow statistics telling how much flow should be sent along a link.
Definition: station_base.h:32
ClearDockingTilesCheckingNeighbours
void ClearDockingTilesCheckingNeighbours(TileIndex tile)
Clear docking tile status from tiles around a removed dock, if the tile has no neighbours which would...
Definition: station_cmd.cpp:2759
ChangeTileOwner
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
Definition: landscape.cpp:567
GetStringWithArgs
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:261
GoodsEntry::cargo
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Definition: station_base.h:210
LinkGraphSchedule::Queue
void Queue(LinkGraph *lg)
Queue a link graph for execution.
Definition: linkgraphschedule.h:67
Vehicle::date_of_last_service
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
Definition: vehicle_base.h:291
StationType
StationType
Station types.
Definition: station_type.h:31
RoadBuildCost
Money RoadBuildCost(RoadType roadtype)
Returns the cost of building the specified roadtype.
Definition: road.h:252
DrawTileSprites::ground
PalSpriteID ground
Palette and sprite for the ground.
Definition: sprite.h:59
include
bool include(Container &container, typename Container::const_reference &item)
Helper function to append an item to a container if it is not already contained.
Definition: container_func.hpp:24
IsDock
bool IsDock(Tile t)
Is tile t a dock tile?
Definition: station_map.h:286
AirportTileSpec
Defines the data structure of each individual tile of an airport.
Definition: newgrf_airporttiles.h:68
StationSpec::cls_id
StationClassID cls_id
The class to which this spec belongs.
Definition: newgrf_station.h:125
TileDesc::build_date
TimerGameCalendar::Date build_date
Date of construction of tile contents.
Definition: tile_cmd.h:57
IsTruckStop
bool IsTruckStop(Tile t)
Is the station at t a truck stop?
Definition: station_map.h:180
RailTypeInfo::name
StringID name
Name of this rail type.
Definition: rail.h:176
GetCustomRoadSprite
SpriteID GetCustomRoadSprite(const RoadTypeInfo *rti, TileIndex tile, RoadTypeSpriteGroup rtsg, TileContext context, uint *num_results)
Get the sprite to draw for the given tile.
Definition: newgrf_roadtype.cpp:101
Utf8StringLength
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition: string.cpp:378
newgrf_airporttiles.h
GameSettings::order
OrderSettings order
settings related to orders
Definition: settings_type.h:625
ROAD_Y
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
Definition: road_type.h:59
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
Vehicle::Orders
IterateWrapper Orders() const
Returns an iterable ensemble of orders of a vehicle.
Definition: vehicle_base.h:1080
GetStationLayout
void GetStationLayout(byte *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
Create the station layout for the given number of tracks and platform length.
Definition: station_cmd.cpp:1123
CheckBuildableTile
CommandCost CheckBuildableTile(TileIndex tile, uint 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.
Definition: station_cmd.cpp:799
DistanceManhattan
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:159
DIAGDIR_SW
@ DIAGDIR_SW
Southwest.
Definition: direction_type.h:77
RoadStop::next
struct RoadStop * next
Next stop of the given type at this station.
Definition: roadstop_base.h:69
FACIL_BUS_STOP
@ FACIL_BUS_STOP
Station with bus stops.
Definition: station_type.h:54
Airport::rotation
Direction rotation
How this airport is rotated.
Definition: station_base.h:296
GetProductionAroundTiles
CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
Get the cargo types being produced around the tile (in a rectangle).
Definition: station_cmd.cpp:543
FlowStatMap::DeleteFlows
StationIDStack DeleteFlows(StationID via)
Delete all flows at a station for specific cargo and destination.
Definition: station_cmd.cpp:4855
IsInsideBS
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.
Definition: math_func.hpp:252
CheckForDockingTile
void CheckForDockingTile(TileIndex t)
Mark the supplied tile as a docking tile if it is suitable for docking.
Definition: water_cmd.cpp:184
CargoSpec::Index
CargoID Index() const
Determines index of this cargospec.
Definition: cargotype.h:102
AirportSpec::rotation
const Direction * rotation
the rotation of each tiletable
Definition: newgrf_airport.h:103
LinkGraph::COMPRESSION_INTERVAL
static constexpr TimerGameEconomy::Date COMPRESSION_INTERVAL
Minimum number of days between subsequent compressions of a LG.
Definition: linkgraph.h:176
landscape_cmd.h
MakeAirport
void MakeAirport(Tile t, Owner o, StationID sid, byte section, WaterClass wc)
Make the given tile an airport tile.
Definition: station_map.h:718
AnimationInfo::status
uint8_t status
Status; 0: no looping, 1: looping, 0xFF: no animation.
Definition: newgrf_animation_type.h:20
EconomySettings::station_noise_level
bool station_noise_level
build new airports when the town noise level is still within accepted limits
Definition: settings_type.h:556
StationCargoList::Reroute
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.
Definition: cargopacket.cpp:854
TRANSPORT_RAIL
@ TRANSPORT_RAIL
Transport by train.
Definition: transport_type.h:27
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition: company_cmd.cpp:361
Vehicle::dest_tile
TileIndex dest_tile
Heading for this tile.
Definition: vehicle_base.h:267
StationSettings::serve_neutral_industries
bool serve_neutral_industries
company stations can serve industries with attached neutral stations
Definition: settings_type.h:590
GetStationGfx
StationGfx GetStationGfx(Tile t)
Get the station graphics of this tile.
Definition: station_map.h:68
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:38
StationFinder::stations
StationList stations
List of stations nearby.
Definition: station_type.h:101
SetCustomStationSpecIndex
void SetCustomStationSpecIndex(Tile t, byte specindex)
Set the custom station spec for this tile.
Definition: station_map.h:537
TrackBitsToTrackdirBits
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition: track_func.h:319
ToTileIndexDiff
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition: map_func.h:452
IsBayRoadStopTile
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
Definition: station_map.h:223
CheckFlatLandAirport
static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlag flags)
Checks if an airport can be built at the given location and clear the area.
Definition: station_cmd.cpp:849
EXPENSES_CONSTRUCTION
@ EXPENSES_CONSTRUCTION
Construction costs.
Definition: economy_type.h:173
BaseStation::sign
TrackedViewportSign sign
NOSAVE: Dimensions of sign.
Definition: base_station_base.h:66
Industry::stations_near
StationList stations_near
NOSAVE: List of nearby stations.
Definition: industry.h:112
RailType
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
TileAddWrap
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:116
STAT_CLASS_WAYP
@ STAT_CLASS_WAYP
Waypoint class.
Definition: newgrf_station.h:86
FlowStatMap::ReleaseFlows
void ReleaseFlows(StationID via)
Release all flows at a station for specific cargo and destination.
Definition: station_cmd.cpp:4886
M
#define M(x)
Helper for creating a bitset of slopes.
Definition: slope_type.h:84
CommandCost
Common return value for all commands.
Definition: command_type.h:23
GetSnowLine
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:611
Industry::location
TileArea location
Location of the industry.
Definition: industry.h:96
TRACK_Y
@ TRACK_Y
Track along the y-axis (north-west to south-east)
Definition: track_type.h:22
WaterClass
WaterClass
classes of water (for WATER_TILE_CLEAR water tile type).
Definition: water_map.h:47
GetRailStationTrack
Track GetRailStationTrack(Tile t)
Get the rail track of a rail station tile.
Definition: station_map.h:422
AirportSpec::Get
static const AirportSpec * Get(byte type)
Retrieve airport spec for the given airport.
Definition: newgrf_airport.cpp:54
IsWater
bool IsWater(Tile t)
Is it a plain water tile?
Definition: water_map.h:150
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition: bitmath_func.hpp:282
RemoveFirstTrack
Track RemoveFirstTrack(TrackBits *tracks)
Removes first Track from TrackBits and returns it.
Definition: track_func.h:131
AirportSpec::cls_id
AirportClassID cls_id
the class to which this airport type belongs
Definition: newgrf_airport.h:115
Train::GetVehicleTrackdir
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
Definition: train_cmd.cpp:4224
NT_ACCEPTANCE
@ NT_ACCEPTANCE
A type of cargo is (no longer) accepted.
Definition: news_type.h:37
CircularTileSearch
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
Function performing a search around a center tile and going outward, thus in circle.
Definition: map.cpp:260
RemoveAirport
static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
Remove an airport.
Definition: station_cmd.cpp:2516
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:147
clear_func.h
SetStationGfx
void SetStationGfx(Tile t, StationGfx gfx)
Set the station graphics of this tile.
Definition: station_map.h:80
BaseStation::train_station
TileArea train_station
Tile area the train 'station' part covers.
Definition: base_station_base.h:89
NF_INCOLOUR
@ NF_INCOLOUR
Bit value for coloured news.
Definition: news_type.h:74
Industry::GetByTile
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:207
AirportSpec::num_table
byte num_table
number of elements in the table
Definition: newgrf_airport.h:104
DirtyCompanyInfrastructureWindows
void DirtyCompanyInfrastructureWindows(CompanyID company)
Redraw all windows with company infrastructure counts.
Definition: company_gui.cpp:2670
GetSlopeMaxZ
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:160
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
CalcClosestTownFromTile
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3765
StationSpec::layouts
std::vector< std::vector< std::vector< byte > > > layouts
Custom platform layouts.
Definition: newgrf_station.h:175
WID_SV_ROADVEHS
@ WID_SV_ROADVEHS
List of scheduled road vehs button.
Definition: station_widget.h:28
Industry::type
IndustryType type
type of industry.
Definition: industry.h:104
roadstop_base.h
BaseStation::rect
StationRect rect
NOSAVE: Station spread out rectangle maintained by StationRect::xxx() functions.
Definition: base_station_base.h:90
TriggerWatchedCargoCallbacks
void TriggerWatchedCargoCallbacks(Station *st)
Run the watched cargo callback for all houses in the catchment area.
Definition: station_cmd.cpp:3554
GoodsEntry::HasRating
bool HasRating() const
Does this cargo have a rating at this station?
Definition: station_base.h:258
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:260
StationSpec::pylons
byte pylons
Bitmask of base tiles (0 - 7) which should contain elrail pylons.
Definition: newgrf_station.h:161
RoadStopResolverObject
Road stop resolver.
Definition: newgrf_roadstop.h:96
FindNearIndustryName
static bool FindNearIndustryName(TileIndex tile, void *user_data)
Find a station action 0 property 24 station name, or reduce the free_names if needed.
Definition: station_cmd.cpp:234
autoslope.h
TileIterator
Base class for tile iterators.
Definition: tilearea_type.h:105
MayHaveRoad
bool MayHaveRoad(Tile t)
Test whether a tile can have road/tram types.
Definition: road_map.h:33
CMSAMine
static bool CMSAMine(TileIndex tile)
Check whether the tile is a mine.
Definition: station_cmd.cpp:167
DistanceFromEdge
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition: map.cpp:219
Station::MarkTilesDirty
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Definition: station.cpp:244
Kdtree::Insert
void Insert(const T &element)
Insert a single element in the tree.
Definition: kdtree.hpp:398
TileDesc::roadtype
StringID roadtype
Type of road on the tile.
Definition: tile_cmd.h:66
RoadStopSpec::GetClearCost
Money GetClearCost(Price category) const
Get the cost for clearing a road stop of this type.
Definition: newgrf_roadstop.h:159
ROADSTOP_END
@ ROADSTOP_END
End of valid types.
Definition: station_type.h:46
TransportType
TransportType
Available types of transport.
Definition: transport_type.h:19
GetRailReservationTrackBits
TrackBits GetRailReservationTrackBits(Tile t)
Returns the reserved track bits of the tile.
Definition: rail_map.h:194
rail_cmd.h
CheckFlatLandRoadStop
static CommandCost CheckFlatLandRoadStop(TileIndex cur_tile, int &allowed_z, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadType rt)
Checks if a road stop can be built at the given tile.
Definition: station_cmd.cpp:967
GoodsEntry::GES_ACCEPTED_BIGTICK
@ GES_ACCEPTED_BIGTICK
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval.
Definition: station_base.h:207
_cheats
Cheats _cheats
All the cheats.
Definition: cheat.cpp:16
FlowStat::GetShares
const SharesMap * GetShares() const
Get the actual shares as a const pointer so that they can be iterated over.
Definition: station_base.h:88
GoodsEntry::GetVia
StationID GetVia(StationID source) const
Get the best next hop for a cargo packet from station source.
Definition: station_base.h:268
TRACKDIR_BIT_NONE
@ TRACKDIR_BIT_NONE
No track build.
Definition: track_type.h:99
SpecializedStation< Waypoint, true >::IsExpected
static bool IsExpected(const BaseStation *st)
Helper for checking whether the given station is of this type.
Definition: base_station_base.h:240
INVALID_OWNER
@ INVALID_OWNER
An invalid owner.
Definition: company_type.h:29
MP_WATER
@ MP_WATER
Water tile.
Definition: tile_type.h:54
Station::truck_station
TileArea truck_station
Tile area the truck 'station' part covers.
Definition: station_base.h:454
UpdateAirportsNoise
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
Definition: station_cmd.cpp:2364
ReverseDiagDir
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Definition: direction_func.h:118
GoodsEntry::node
NodeID node
ID of node in link graph referring to this goods entry.
Definition: station_base.h:214
station_cmd.h
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:341
FreeTrainReservation
static void FreeTrainReservation(Train *v)
Clear platform reservation during station building/removing.
Definition: station_cmd.cpp:1227
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:171
FindRoadStopSpot
static RoadStop ** FindRoadStopSpot(bool truck_station, Station *st)
Definition: station_cmd.cpp:1841
station_func.h
Vehicle::current_order
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:350
Airport::GetHangarTile
TileIndex GetHangarTile(uint hangar_num) const
Get the first tile of the given hangar.
Definition: station_base.h:358
WATER_CLASS_CANAL
@ WATER_CLASS_CANAL
Canal.
Definition: water_map.h:49
LinkGraph::BaseEdge
An edge in the link graph.
Definition: linkgraph.h:42
Station::airport
Airport airport
Tile area the airport covers.
Definition: station_base.h:456
AirportTileTableIterator
Iterator to iterate over all tiles belonging to an airport spec.
Definition: newgrf_airport.h:31
OrthogonalTileArea
Represents the covered area of e.g.
Definition: tilearea_type.h:18
Station::AddFacility
void AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
Called when new facility is built on the station.
Definition: station.cpp:227
AxisToDiagDir
DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
Definition: direction_func.h:232
MultiMap::MapSize
size_t MapSize() const
Count the number of ranges with equal keys in this MultiMap.
Definition: multimap.hpp:347
EndSpriteCombine
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
Definition: viewport.cpp:779
SourceID
uint16_t SourceID
Contains either industry ID, town ID or company ID (or INVALID_SOURCE)
Definition: cargo_type.h:143
Town::MaxTownNoise
uint16_t MaxTownNoise() const
Calculate the max town noise.
Definition: town.h:121
HasStationTileRail
bool HasStationTileRail(Tile t)
Has this station tile a rail? In other words, is this station tile a rail station or rail waypoint?
Definition: station_map.h:146
CMSATree
static bool CMSATree(TileIndex tile)
Check whether the tile is a tree.
Definition: station_cmd.cpp:204
Vehicle::cur_speed
uint16_t cur_speed
current speed
Definition: vehicle_base.h:324
GetEmptyMask
CargoTypes GetEmptyMask(const Station *st)
Get a mask of the cargo types that are empty at the station.
Definition: station_cmd.cpp:512
SRT_NEW_CARGO
@ SRT_NEW_CARGO
Trigger station on new cargo arrival.
Definition: newgrf_station.h:103
ReverseTrackdir
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition: track_func.h:247
AirportTileSpec::GetByTile
static const AirportTileSpec * GetByTile(TileIndex tile)
Retrieve airport tile spec for the given airport tile.
Definition: newgrf_airporttiles.cpp:50
StationNameInformation::indtypes
std::bitset< NUM_INDUSTRYTYPES > indtypes
Bit set indicating when an industry type has been found.
Definition: station_cmd.cpp:223
TileDiffXY
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition: map_func.h:401
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:55
Station::indtype
IndustryType indtype
Industry type to get the name from.
Definition: station_base.h:460
IsTileOnWater
bool IsTileOnWater(Tile t)
Tests if the tile was built on water.
Definition: water_map.h:139
timer_game_tick.h
IsBuoyTile
bool IsBuoyTile(Tile t)
Is tile t a buoy tile?
Definition: station_map.h:317
ANIM_STATUS_NO_ANIMATION
static const uint8_t ANIM_STATUS_NO_ANIMATION
There is no animation.
Definition: newgrf_animation_type.h:15
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:627
MakeDriveThroughRoadStop
void MakeDriveThroughRoadStop(Tile t, Owner station, Owner road, Owner tram, StationID sid, RoadStopType rst, RoadType road_rt, RoadType tram_rt, Axis a)
Make the given tile a drivethrough roadstop tile.
Definition: station_map.h:702
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:50
RemoveDock
static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
Remove a dock.
Definition: station_cmd.cpp:2803
TRACK_BIT_X
@ TRACK_BIT_X
X-axis track.
Definition: track_type.h:37
GetIndustryIndex
IndustryID GetIndustryIndex(Tile t)
Get the industry ID of the given tile.
Definition: industry_map.h:63
NewGRFSpriteLayout
NewGRF supplied spritelayout.
Definition: newgrf_commons.h:112
industry.h
safeguards.h
StationSpec::name
StringID name
Name of this station.
Definition: newgrf_station.h:126
timer.h
ROTSG_ROADSTOP
@ ROTSG_ROADSTOP
Required: Bay stop surface.
Definition: road.h:70
ClearTile_Station
CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
Clear a single tile of a station.
Definition: station_cmd.cpp:4487
NewGRFSpriteLayout::NeedsPreprocessing
bool NeedsPreprocessing() const
Tests whether this spritelayout needs preprocessing by PrepareLayout() and ProcessRegisters(),...
Definition: newgrf_commons.h:149
IsNormalRoadTile
static debug_inline bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
Definition: road_map.h:74
Train
'Train' is either a loco or a wagon.
Definition: train.h:89
VEH_INVALID
@ VEH_INVALID
Non-existing type of vehicle.
Definition: vehicle_type.h:35
_economy_stations_monthly
static IntervalTimer< TimerGameEconomy > _economy_stations_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::STATION}, [](auto) { for(Station *st :Station::Iterate()) { for(GoodsEntry &ge :st->goods) { SB(ge.status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge.status, GoodsEntry::GES_CURRENT_MONTH, 1));ClrBit(ge.status, GoodsEntry::GES_CURRENT_MONTH);} } })
Economy monthly loop for stations.
FreeTrainTrackReservation
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
Definition: train_cmd.cpp:2395
HasTileRoadType
bool HasTileRoadType(Tile t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition: road_map.h:211
GetCanalSprite
SpriteID GetCanalSprite(CanalFeature feature, TileIndex tile)
Lookup the base sprite to use for a canal.
Definition: newgrf_canal.cpp:140
GetTileSlope
Slope GetTileSlope(TileIndex tile, int *h)
Return the slope of a given tile inside the map.
Definition: tile_map.cpp:59
DirToDiagDir
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Definition: direction_func.h:166
LinkGraph::LastCompression
TimerGameEconomy::Date LastCompression() const
Get date of last compression.
Definition: linkgraph.h:236
SPRITE_MODIFIER_CUSTOM_SPRITE
@ SPRITE_MODIFIER_CUSTOM_SPRITE
Set when a sprite originates from an Action 1.
Definition: sprites.h:1539
NUM_AIRPORTS
@ NUM_AIRPORTS
Maximal number of airports in total.
Definition: airport.h:41
BaseStation::name
std::string name
Custom name.
Definition: base_station_base.h:69
DrawTileSprites
Ground palette sprite of a tile, together with its sprite layout.
Definition: sprite.h:58
RoadStopSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_roadstop.h:129
FlowStat::RestrictShare
void RestrictShare(StationID st)
Restrict a flow by moving it to the end of the map and decreasing the amount of unrestricted flow.
Definition: station_cmd.cpp:4706
GetTileOwner
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition: tile_map.h:178
StartSpriteCombine
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
Definition: viewport.cpp:769
INVALID_DIAGDIR
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
Definition: direction_type.h:80
DrawSprite
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:1003
RSF_DRIVE_THROUGH_ONLY
@ RSF_DRIVE_THROUGH_ONLY
Stop is drive-through only.
Definition: newgrf_roadstop.h:68
Station::bus_station
TileArea bus_station
Tile area the bus 'station' part covers.
Definition: station_base.h:452
RemoveBuoy
CommandCost RemoveBuoy(TileIndex tile, DoCommandFlag flags)
Remove a buoy.
Definition: waypoint_cmd.cpp:367
GetPlatformInfo
uint32_t GetPlatformInfo(Axis axis, byte tile, int platforms, int length, int x, int y, bool centred)
Evaluate a tile's position within a station, and return the result in a bit-stuffed format.
Definition: newgrf_station.cpp:103
road_internal.h
waypoint_func.h
RTSG_GROUND
@ RTSG_GROUND
Main group of ground images.
Definition: rail.h:52
airporttile_ids.h
TileIndexDiff
int32_t TileIndexDiff
An offset value between two tiles.
Definition: map_func.h:376
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
Point
Coordinates of a point in 2D.
Definition: geometry_type.hpp:21
TileDesc::station_name
StringID station_name
Type of station within the class.
Definition: tile_cmd.h:59
RoadTypeInfo::name
StringID name
Name of this rail type.
Definition: road.h:103
ValParamRoadType
bool ValParamRoadType(RoadType roadtype)
Validate functions for rail building.
Definition: road.cpp:153
GameSettings::linkgraph
LinkGraphSettings linkgraph
settings for link graph calculations
Definition: settings_type.h:628
DeleteStaleLinks
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 ...
Definition: station_cmd.cpp:3820
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition: direction_type.h:73
CalculateRailStationCost
static CommandCost CalculateRailStationCost(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector< Train * > &affected_vehicles, StationClassID spec_class, uint16_t spec_index, byte plat_len, byte numtracks)
Calculates cost of new rail stations within the area.
Definition: station_cmd.cpp:1261
StationCargoList::AvailableCount
uint AvailableCount() const
Returns sum of cargo still available for loading at the sation.
Definition: cargopacket.h:588
GFX_DOCK_BASE_WATER_PART
static const int GFX_DOCK_BASE_WATER_PART
The offset for the water parts.
Definition: station_map.h:35
TRACK_BIT_ALL
@ TRACK_BIT_ALL
All possible tracks.
Definition: track_type.h:50
FACIL_DOCK
@ FACIL_DOCK
Station with a dock.
Definition: station_type.h:56
OffsetGroundSprite
void OffsetGroundSprite(int x, int y)
Called when a foundation has been drawn for the current tile.
Definition: viewport.cpp:601
GenerateStationName
static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
Definition: station_cmd.cpp:250
newgrf_roadstop.h
CombineTrackStatus
TrackStatus CombineTrackStatus(TrackdirBits trackdirbits, TrackdirBits red_signals)
Builds a TrackStatus.
Definition: track_func.h:388
FlowStat::AppendShare
void AppendShare(StationID st, uint flow, bool restricted=false)
Add some flow to the end of the shares map.
Definition: station_base.h:66
CBM_STATION_AVAIL
@ CBM_STATION_AVAIL
Availability of station in construction window.
Definition: newgrf_callbacks.h:310
CalculateRoadStopCost
static CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlag flags, bool is_drive_through, bool is_truck_stop, Axis axis, DiagDirection ddir, StationID *est, RoadType rt, Money unit_cost)
Calculates cost of new road stops within the area.
Definition: station_cmd.cpp:1885
SpecializedStation< Station, false >::From
static Station * From(BaseStation *st)
Converts a BaseStation to SpecializedStation with type checking.
Definition: base_station_base.h:288
StationSettings::station_spread
byte station_spread
amount a station may spread
Definition: settings_type.h:594
GetCustomRoadStopSpecIndex
uint GetCustomRoadStopSpecIndex(Tile t)
Get the custom road stop spec for this tile.
Definition: station_map.h:585
Station::always_accepted
CargoTypes always_accepted
Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn't accept c...
Definition: station_base.h:472
WID_SV_TRAINS
@ WID_SV_TRAINS
List of scheduled trains button.
Definition: station_widget.h:27
ShowStationViewWindow
void ShowStationViewWindow(StationID station)
Opens StationViewWindow for given station.
Definition: station_gui.cpp:2145
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:63
TruncateCargo
static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount=UINT_MAX)
Truncate the cargo by a specific amount.
Definition: station_cmd.cpp:3613
CBID_STATION_TILE_LAYOUT
@ CBID_STATION_TILE_LAYOUT
Called when building a station to customize the tile layout.
Definition: newgrf_callbacks.h:96
GUISettings::show_track_reservation
bool show_track_reservation
highlight reserved tracks.
Definition: settings_type.h:185
IsValidAxis
bool IsValidAxis(Axis d)
Checks if an integer value is a valid Axis.
Definition: direction_func.h:43
StationSpec::disallowed_platforms
byte disallowed_platforms
Bitmask of number of platforms available for the station.
Definition: newgrf_station.h:132
stdafx.h
CheckAllowRemoveRoad
CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadTramType rtt, DoCommandFlag flags, bool town_check)
Is it allowed to remove the given road bits from the given tile?
Definition: road_cmd.cpp:262
SetStationTileRandomBits
void SetStationTileRandomBits(Tile t, byte random_bits)
Set the random bits for a station tile.
Definition: station_map.h:597
DrawRoadOverlays
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.
Definition: road_cmd.cpp:1515
TileTypeProcs
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:158
SetAnimationFrame
void SetAnimationFrame(Tile t, byte frame)
Set a new animation frame.
Definition: tile_map.h:262
StationFinder::GetStations
const StationList * GetStations()
Run a tile loop to find stations around a tile, on demand.
Definition: station_cmd.cpp:4150
SAT_BUILT
@ SAT_BUILT
Trigger tile when built.
Definition: newgrf_animation_type.h:27
BuildStationPart
static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
Common part of building various station parts and possibly attaching them to an existing one.
Definition: station_cmd.cpp:697
GoodsEntry::link_graph
LinkGraphID link_graph
Link graph this station belongs to.
Definition: station_base.h:215
SetTileOwner
void SetTileOwner(Tile tile, Owner owner)
Sets the owner of a tile.
Definition: tile_map.h:198
DRD_NONE
@ DRD_NONE
None of the directions are disallowed.
Definition: road_type.h:74
Station::truck_stops
RoadStop * truck_stops
All the truck stops.
Definition: station_base.h:453
IndustrySpec
Defines the data structure for constructing industry.
Definition: industrytype.h:105
NewGRFSpriteLayout::PrepareLayout
uint32_t PrepareLayout(uint32_t orig_offset, uint32_t newgrf_ground_offset, uint32_t newgrf_offset, uint constr_stage, bool separate_ground) const
Prepares a sprite layout before resolving action-1-2-3 chains.
Definition: newgrf_commons.cpp:639
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
CountBits
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
Definition: bitmath_func.hpp:243
Station::industry
Industry * industry
NOSAVE: Associated industry for neutral stations. (Rebuilt on load from Industry->st)
Definition: station_base.h:475
SetStationTileBlocked
void SetStationTileBlocked(Tile t, bool b)
Set the blocked state of the rail station.
Definition: station_map.h:350
Cheat::value
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:18
OrderBackup::Reset
static void Reset(TileIndex tile=INVALID_TILE, bool from_gui=true)
Reset the OrderBackups from GUI/game logic.
Definition: order_backup.cpp:187
DC_BANKRUPT
@ DC_BANKRUPT
company bankrupts, skip money check, skip vehicle on tile check in some cases
Definition: command_type.h:377
WATER_CLASS_SEA
@ WATER_CLASS_SEA
Sea.
Definition: water_map.h:48
AirportTileIterator
Iterator to iterate over all tiles belonging to an airport.
Definition: station_base.h:528
CmdBuildDock
CommandCost CmdBuildDock(DoCommandFlag flags, TileIndex tile, StationID station_to_join, bool adjacent)
Build a dock/haven.
Definition: station_cmd.cpp:2652
AirportSpec::IsAvailable
bool IsAvailable() const
Check whether this airport is available to build.
Definition: newgrf_airport.cpp:81
RTSG_OVERLAY
@ RTSG_OVERLAY
Images for overlaying track.
Definition: rail.h:51
viewport_func.h
StationList
std::set< Station *, StationCompare > StationList
List of stations.
Definition: station_type.h:94
GetStationType
StationType GetStationType(Tile t)
Get the station type of this tile.
Definition: station_map.h:44
TileLoop_Water
void TileLoop_Water(TileIndex tile)
Let a water tile floods its diagonal adjoining tiles called from tunnelbridge_cmd,...
Definition: water_cmd.cpp:1233
bridge_map.h
GetTrainStopLocation
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, 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.
Definition: train_cmd.cpp:264
FACIL_WAYPOINT
@ FACIL_WAYPOINT
Station is a waypoint.
Definition: station_type.h:57
animated_tile_func.h
HasTileWaterClass
bool HasTileWaterClass(Tile t)
Checks whether the tile has an waterclass associated.
Definition: water_map.h:104
IsPlainRailTile
static debug_inline bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition: rail_map.h:60
AddSortableSpriteToDraw
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition: viewport.cpp:673
IncreaseStats
void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateMode mode)
Increase capacity for a link stat given by station cargo and next hop.
Definition: station_cmd.cpp:3914
FindJoiningRoadStop
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.
Definition: station_cmd.cpp:1867
IsValidTile
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition: tile_map.h:161
yapf_cache.h
GetTrackBits
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Definition: rail_map.h:136
Vehicle::direction
Direction direction
facing
Definition: vehicle_base.h:303
RailTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:231
FlowStatMap::AddFlow
void AddFlow(StationID origin, StationID via, uint amount)
Add some flow from "origin", going via "via".
Definition: station_cmd.cpp:4793
IsTileForestIndustry
bool IsTileForestIndustry(TileIndex tile)
Check whether the tile is a forest.
Definition: industry_cmd.cpp:974
TileOffsByDiagDir
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:563
Ticks::STATION_LINKGRAPH_TICKS
static constexpr TimerGameTick::Ticks STATION_LINKGRAPH_TICKS
Cycle duration for cleaning dead links.
Definition: timer_game_tick.h:80
DistanceMax
uint DistanceMax(TileIndex t0, TileIndex t1)
Gets the biggest distance component (x or y) between the two given tiles.
Definition: map.cpp:191
RailTypeInfo::single_x
SpriteID single_x
single piece of rail in X direction, without ground
Definition: rail.h:137
AirportSpec::size_x
byte size_x
size of airport in x direction
Definition: newgrf_airport.h:107
MP_TREES
@ MP_TREES
Tile got trees.
Definition: tile_type.h:52
GetRoadTypeInfo
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition: road.h:227
TileIndexDiffC
A pair-construct of a TileIndexDiff.
Definition: map_type.h:31
DrawFoundation
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:427
MAX_LENGTH_STATION_NAME_CHARS
static const uint MAX_LENGTH_STATION_NAME_CHARS
The maximum length of a station name in characters including '\0'.
Definition: station_type.h:87
Map::SizeX
static debug_inline uint SizeX()
Get the size of the map along the X.
Definition: map_func.h:270
SSF_CUSTOM_FOUNDATIONS
@ SSF_CUSTOM_FOUNDATIONS
Draw custom foundations.
Definition: newgrf_station.h:97
TileDesc::tram_speed
uint16_t tram_speed
Speed limit of tram (bridges and track)
Definition: tile_cmd.h:69
ForAllStationsRadius
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
Definition: station_kdtree.h:29
FlowStat::empty_sharesmap
static const SharesMap empty_sharesmap
Static instance of FlowStat::SharesMap.
Definition: station_base.h:36
ConstructionSettings::road_stop_on_competitor_road
bool road_stop_on_competitor_road
allow building of drive-through road stops on roads owned by competitors
Definition: settings_type.h:378
SetCustomRoadStopSpecIndex
void SetCustomRoadStopSpecIndex(Tile t, byte specindex)
Set the custom road stop spec for this tile.
Definition: station_map.h:573
RemoveFromRailBaseStation
CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector< T * > &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
Remove a number of tiles from any rail station within the area.
Definition: station_cmd.cpp:1609
string_func.h
IndustrySpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:140
GetAnyRoadBits
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition: road_map.cpp:33
GoodsEntry::GES_CURRENT_MONTH
@ GES_CURRENT_MONTH
Set when cargo was delivered for final delivery this month.
Definition: station_base.h:201
ROADSTOP_CLASS_WAYP
@ ROADSTOP_CLASS_WAYP
Waypoint class (unimplemented: this is reserved for future use with road waypoints).
Definition: newgrf_roadstop.h:28
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:420
ROADSTOP_BUS
@ ROADSTOP_BUS
A standard stop for buses.
Definition: station_type.h:44
RemapCoords2
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:98
IsValidDiagDirection
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Definition: direction_func.h:21
Ship
All ships have this type.
Definition: ship.h:24
GoodsEntry
Stores station stats for a single cargo.
Definition: station_base.h:166
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:51
vehicle_func.h
WC_SELECT_STATION
@ WC_SELECT_STATION
Select station (when joining stations); Window numbers:
Definition: window_type.h:242
station_base.h
SourceType
SourceType
Types of cargo source and destination.
Definition: cargo_type.h:137
DeleteStationIfEmpty
static void DeleteStationIfEmpty(BaseStation *st)
This is called right after a station was deleted.
Definition: station_cmd.cpp:734
PALETTE_CRASH
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition: sprites.h:1602
Pool::PoolItem<&_station_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:388
GRFFilePropsBase::spritegroup
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
Definition: newgrf_commons.h:320
IsBuoy
bool IsBuoy(Tile t)
Is tile t a buoy tile?
Definition: station_map.h:307
StationSpec
Station specification.
Definition: newgrf_station.h:112
Vehicle::First
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:641
CountMapSquareAround
static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
Counts the numbers of tiles matching a specific type in the area around.
Definition: station_cmd.cpp:148
newgrf_roadtype.h
TRACK_BIT_LEFT
@ TRACK_BIT_LEFT
Left track.
Definition: track_type.h:41
GoodsEntry::amount_fract
uint8_t amount_fract
Fractional part of the amount in the cargo list.
Definition: station_base.h:245
LinkGraph::AddNode
NodeID AddNode(const Station *st)
Add a node to the component and create empty edges associated with it.
Definition: linkgraph.cpp:149
refresh.h
Pool::PoolItem<&_town_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:369
DeleteAnimatedTile
void DeleteAnimatedTile(TileIndex tile)
Removes the given tile from the animated tile table.
Definition: animated_tile.cpp:25
IsDockingTile
bool IsDockingTile(Tile t)
Checks whether the tile is marked as a dockling tile.
Definition: water_map.h:374
RoadStop::ClearDriveThrough
void ClearDriveThrough()
Prepare for removal of this stop; update other neighbouring stops if needed.
Definition: roadstop.cpp:130
RailTypeInfo::fallback_railtype
byte fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition: rail.h:201
PerformStationTileSlopeCheck
CommandCost PerformStationTileSlopeCheck(TileIndex north_tile, TileIndex cur_tile, const StationSpec *statspec, Axis axis, byte plat_len, byte numtracks)
Check the slope of a tile of a new station.
Definition: newgrf_station.cpp:661
FACIL_TRAIN
@ FACIL_TRAIN
Station with train station.
Definition: station_type.h:52
TrackedViewportSign::UpdatePosition
void UpdatePosition(int center, int top, StringID str, StringID str_small=STR_NULL)
Update the position of the viewport sign.
Definition: viewport_type.h:56
IsCustomStationSpecIndex
bool IsCustomStationSpecIndex(Tile t)
Is there a custom rail station spec on this tile?
Definition: station_map.h:525
TryPathReserve
bool TryPathReserve(Train *v, bool mark_as_stuck=false, bool first_tile_okay=false)
Try to reserve a path to a safe position.
Definition: train_cmd.cpp:2860
SpecializedVehicle< RoadVehicle, Type >::From
static RoadVehicle * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1211
AirportGetNearestTown
Town * AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
Finds the town nearest to given airport.
Definition: station_cmd.cpp:2314
Map::Size
static debug_inline uint Size()
Get the size of the map.
Definition: map_func.h:288
GoodsEntry::flows
FlowStatMap flows
Planned flows through this station.
Definition: station_base.h:211
RailTrackOffset
RailTrackOffset
Offsets for sprites within an overlay/underlay set.
Definition: rail.h:70
SetDParam
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings.cpp:104
GetStationIndex
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition: station_map.h:28
ROADSTOP_DRAW_MODE_ROAD
@ ROADSTOP_DRAW_MODE_ROAD
Bay stops: Draw the road itself.
Definition: newgrf_roadstop.h:60
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
HasStationReservation
bool HasStationReservation(Tile t)
Get the reservation state of the rail station.
Definition: station_map.h:466
LinkGraph::MIN_TIMEOUT_DISTANCE
static const uint MIN_TIMEOUT_DISTANCE
Minimum effective distance for timeout calculation.
Definition: linkgraph.h:170
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:370
ROTSG_OVERLAY
@ ROTSG_OVERLAY
Optional: Images for overlaying track.
Definition: road.h:61
InvalidateWindowClassesData
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:3221
RSRT_NEW_CARGO
@ RSRT_NEW_CARGO
Trigger roadstop on arrival of new cargo.
Definition: newgrf_roadstop.h:35
HasStationRail
bool HasStationRail(Tile t)
Has this station tile a rail? In other words, is this station tile a rail station or rail waypoint?
Definition: station_map.h:135
RTO_X
@ RTO_X
Piece of rail in X direction.
Definition: rail.h:71
AirportSpec::grf_prop
struct GRFFileProps grf_prop
Properties related to the grf file.
Definition: newgrf_airport.h:120
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition: order_base.h:260
GoodsEntry::last_age
uint8_t last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
Definition: station_base.h:243
cheat_type.h
GetAirportGfx
StationGfx GetAirportGfx(Tile t)
Get the station graphics of this airport tile.
Definition: station_map.h:246
HasSignals
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition: rail_map.h:72
MarkTileDirtyByTile
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Definition: viewport.cpp:2051
Vehicle::NextShared
Vehicle * NextShared() const
Get the next vehicle of the shared vehicle chain.
Definition: vehicle_base.h:710
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
AddNewsItem
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32_t ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32_t ref2=UINT32_MAX, const NewsAllocatedData *data=nullptr)
Add a new newsitem to be shown.
Definition: news_gui.cpp:827
SetDockingTile
void SetDockingTile(Tile t, bool b)
Set the docking tile state of a tile.
Definition: water_map.h:364
FOUNDATION_LEVELED
@ FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Definition: slope_type.h:95
Station::UpdateVirtCoord
void UpdateVirtCoord() override
Update the virtual coords needed to draw the station sign.
Definition: station_cmd.cpp:438
IsRoadStop
bool IsRoadStop(Tile t)
Is the station at t a road station?
Definition: station_map.h:202
StationNameInformation::free_names
uint32_t free_names
Current bitset of free names (we can remove names).
Definition: station_cmd.cpp:222
IsHangar
bool IsHangar(Tile t)
Check whether the given tile is a hangar.
Definition: station_cmd.cpp:89
WC_VEHICLE_DEPOT
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
Definition: window_type.h:351
GetRoadOwner
Owner GetRoadOwner(Tile t, RoadTramType rtt)
Get the owner of a specific road type.
Definition: road_map.h:234
MP_STATION
@ MP_STATION
A tile of a station.
Definition: tile_type.h:53
RoadStopSpec::GetBuildCost
Money GetBuildCost(Price category) const
Get the cost for building a road stop of this type.
Definition: newgrf_roadstop.h:153
TimerGameConst< struct Economy >::INVALID_DATE
static constexpr TimerGame< struct Economy >::Date INVALID_DATE
Representation of an invalid date.
Definition: timer_game_common.h:193
IndustrySpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:141
GoodsEntry::GES_ACCEPTANCE
@ GES_ACCEPTANCE
Set when the station accepts the cargo currently for final deliveries.
Definition: station_base.h:173
SpecializedStation< Station, false >::GetByTile
static Station * GetByTile(TileIndex tile)
Get the station belonging to a specific tile.
Definition: base_station_base.h:278
waypoint_base.h
StationClassID
StationClassID
Definition: newgrf_station.h:83
BaseStation::cached_name
std::string cached_name
NOSAVE: Cache of the resolved name of the station, if not using a custom name.
Definition: base_station_base.h:71
TrackedViewportSign::kdtree_valid
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Definition: viewport_type.h:50
ForAllStationsAroundTiles
void ForAllStationsAroundTiles(const TileArea &ta, Func func)
Call a function on all stations that have any part of the requested area within their catchment.
Definition: station_base.h:567
FindVehicleOnPos
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
Definition: vehicle.cpp:505
UpdateCompanyRoadInfrastructure
void UpdateCompanyRoadInfrastructure(RoadType rt, Owner o, int count)
Update road infrastructure counts for a company.
Definition: road_cmd.cpp:190
RTO_Y
@ RTO_Y
Piece of rail in Y direction.
Definition: rail.h:72
Pool::PoolItem<&_station_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:309
HasRailCatenaryDrawn
bool HasRailCatenaryDrawn(RailType rt)
Test if we should draw rail catenary.
Definition: elrail_func.h:30
FlowStat::GetVia
StationID GetVia() const
Get a station a package can be routed to.
Definition: station_base.h:130
DIAGDIR_BEGIN
@ DIAGDIR_BEGIN
Used for iterations.
Definition: direction_type.h:74
CmdRemoveFromRailWaypoint
CommandCost CmdRemoveFromRailWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
Remove a single tile from a waypoint.
Definition: station_cmd.cpp:1749
NewGRFClass::name
StringID name
Name of this class.
Definition: newgrf_class.h:39
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:25
GetRoadBits
RoadBits GetRoadBits(Tile t, RoadTramType rtt)
Get the present road bits for a specific road type.
Definition: road_map.h:128
Station::catchment_tiles
BitmapTileArea catchment_tiles
NOSAVE: Set of individual tiles covered by catchment area.
Definition: station_base.h:462
LinkGraph::Merge
void Merge(LinkGraph *other)
Merge a link graph with another one.
Definition: linkgraph.cpp:90
CheckFlatLandRailStation
static CommandCost CheckFlatLandRailStation(TileIndex tile_cur, TileIndex north_tile, int &allowed_z, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector< Train * > &affected_vehicles, StationClassID spec_class, uint16_t spec_index, byte plat_len, byte numtracks)
Checks if a rail station can be built at the given tile.
Definition: station_cmd.cpp:883
CmdRemoveFromRailStation
CommandCost CmdRemoveFromRailStation(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
Remove a single tile from a rail station.
Definition: station_cmd.cpp:1716
IsBridgeAbove
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
TileDesc::str
StringID str
Description of the tile.
Definition: tile_cmd.h:53
ShowRejectOrAcceptNews
static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
Add news item for when a station changes which cargoes it accepts.
Definition: station_cmd.cpp:528
GetTranslatedAirportTileID
StationGfx GetTranslatedAirportTileID(StationGfx gfx)
Do airporttile gfx ID translation for NewGRFs.
Definition: newgrf_airporttiles.cpp:96
DC_AUTO
@ DC_AUTO
don't allow building on structures
Definition: command_type.h:372
BaseStation::xy
TileIndex xy
Base tile of the station.
Definition: base_station_base.h:65
AddTrackToSignalBuffer
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
Definition: signal.cpp:578
container_func.hpp
BaseStation
Base class for all station-ish types.
Definition: base_station_base.h:64
BaseStation::cached_anim_triggers
uint8_t cached_anim_triggers
NOSAVE: Combined animation trigger bitmask, used to determine if trigger processing should happen.
Definition: base_station_base.h:84
HasStationInUse
bool HasStationInUse(StationID station, bool include_company, CompanyID company)
Tests whether the company's vehicles have this station in orders.
Definition: station_cmd.cpp:2621
RoadTypeInfo::strings
struct RoadTypeInfo::@29 strings
Strings associated with the rail type.
SetRoadOwner
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition: road_map.h:251
RoadBits
RoadBits
Enumeration for the road parts on a tile.
Definition: road_type.h:52
IsReversingRoadTrackdir
bool IsReversingRoadTrackdir(Trackdir dir)
Checks whether the trackdir means that we are reversing.
Definition: track_func.h:673
WID_SV_SHIPS
@ WID_SV_SHIPS
List of scheduled ships button.
Definition: station_widget.h:29
SpecializedVehicle< RoadVehicle, Type >::Iterate
static Pool::IterateWrapper< RoadVehicle > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
Definition: vehicle_base.h:1280
AxisToTrack
Track AxisToTrack(Axis a)
Convert an Axis to the corresponding Track AXIS_X -> TRACK_X AXIS_Y -> TRACK_Y Uses the fact that the...
Definition: track_func.h:66
BaseStation::delete_ctr
byte delete_ctr
Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is ...
Definition: base_station_base.h:67
IndustrySpec::life_type
IndustryLifeType life_type
This is also known as Industry production flag, in newgrf specs.
Definition: industrytype.h:123
AXIS_X
@ AXIS_X
The X axis.
Definition: direction_type.h:117
Order::ShouldStopAtStation
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...
Definition: order_cmd.cpp:2233
OrthogonalTileArea::w
uint16_t w
The width of the area.
Definition: tilearea_type.h:20
ErrorUnknownCallbackResult
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Definition: newgrf_commons.cpp:499
TileArea
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition: tilearea_type.h:102
TriggerStationRandomisation
void TriggerStationRandomisation(Station *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
Definition: newgrf_station.cpp:923
StationSettings::distant_join_stations
bool distant_join_stations
allow to join non-adjacent stations
Definition: settings_type.h:592
Airport::GetNumHangars
uint GetNumHangars() const
Get the number of hangars on this airport.
Definition: station_base.h:395
TrackBits
TrackBits
Allow incrementing of Track variables.
Definition: track_type.h:35
GetRoadStopType
RoadStopType GetRoadStopType(Tile t)
Get the road stop type of this tile.
Definition: station_map.h:56
CommandHelper
Definition: command_func.h:93
SpriteGroup::Resolve
virtual const SpriteGroup * Resolve([[maybe_unused]] ResolverObject &object) const
Base sprite group resolver.
Definition: newgrf_spritegroup.h:61
DrawTileSprites::seq
const DrawTileSeqStruct * seq
Array of child sprites. Terminated with a terminator entry.
Definition: sprite.h:60
BaseStation::cached_roadstop_anim_triggers
uint8_t cached_roadstop_anim_triggers
NOSAVE: Combined animation trigger bitmask for road stops, used to determine if trigger processing sh...
Definition: base_station_base.h:85
StationSettings::adjacent_stations
bool adjacent_stations
allow stations to be built directly adjacent to other stations
Definition: settings_type.h:591
IsStationTileBlocked
bool IsStationTileBlocked(Tile t)
Is tile t a blocked tile?
Definition: station_map.h:338
RoadTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:142
Town
Town data structure.
Definition: town.h:50
GetAnimationFrame
byte GetAnimationFrame(Tile t)
Get the current animation frame.
Definition: tile_map.h:250
StationSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_station.h:124
ROAD_NONE
@ ROAD_NONE
No road-part is build.
Definition: road_type.h:53
LinkRefresher::Run
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
NewGRFClass::Get
static NewGRFClass * Get(Tid cls_id)
Get a particular class.
Definition: newgrf_class_func.h:98
CargoPacket
Container for cargo from the same location and time.
Definition: cargopacket.h:40
TileXY
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:385
random_func.hpp
GetTileMaxPixelZ
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:304
SpecializedStation< Station, false >::GetIfValid
static Station * GetIfValid(size_t index)
Returns station if the index is a valid index for this station type.
Definition: base_station_base.h:268
CBM_ROAD_STOP_AVAIL
@ CBM_ROAD_STOP_AVAIL
Availability of road stop in construction window.
Definition: newgrf_callbacks.h:321
RailTypeInfo::base_sprites
struct RailTypeInfo::@23 base_sprites
Struct containing the main sprites.
newgrf_canal.h
TILE_HEIGHT
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in #ZOOM_LVL_BASE.
Definition: tile_type.h:18
OverflowSafeInt< int64_t >
Airport::type
byte type
Type of this airport,.
Definition: station_base.h:294
NF_SMALL
@ NF_SMALL
Small news item. (Information window with text and viewport)
Definition: news_type.h:80
Vehicle::IsStoppedInDepot
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Definition: vehicle_base.h:556
GetCustomStationFoundationRelocation
SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint layout, uint edge_info)
Resolve the sprites for custom station foundations.
Definition: newgrf_station.cpp:632
MakeRoadNormal
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:635
DrawRailCatenary
void DrawRailCatenary(const TileInfo *ti)
Draws overhead wires and pylons for electric railways.
Definition: elrail.cpp:568
IsShipDestinationTile
bool IsShipDestinationTile(TileIndex tile, StationID station)
Test if a tile is a docking tile for the given station.
Definition: ship_cmd.cpp:663
DrawRailTileSeq
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:89
NEW_AIRPORTTILE_OFFSET
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition: airport.h:24
NewGRFSpriteLayout::GetLayout
const DrawTileSeqStruct * GetLayout(PalSpriteID *ground) const
Returns the result spritelayout after preprocessing.
Definition: newgrf_commons.h:162
TRANSPORT_ROAD
@ TRANSPORT_ROAD
Transport by road vehicle.
Definition: transport_type.h:28
VETSB_ENTERED_STATION
@ VETSB_ENTERED_STATION
The vehicle entered a station.
Definition: tile_cmd.h:36
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:337
GoodsEntry::max_waiting_cargo
uint max_waiting_cargo
Max cargo from this station waiting at any station.
Definition: station_base.h:213
IsValidCargoID
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition: cargo_type.h:107
OrthogonalTileArea::Expand
OrthogonalTileArea & Expand(int rad)
Expand a tile area by rad tiles in each direction, keeping within map bounds.
Definition: tilearea.cpp:123
Ticks::STATION_RATING_TICKS
static constexpr TimerGameTick::Ticks STATION_RATING_TICKS
Cycle duration for updating station rating.
Definition: timer_game_tick.h:78
WID_SV_CLOSE_AIRPORT
@ WID_SV_CLOSE_AIRPORT
'Close airport' button.
Definition: station_widget.h:26
StationCargoList::Append
void Append(CargoPacket *cp, StationID next)
Appends the given cargo packet to the range of packets with the same next station.
Definition: cargopacket.cpp:684
WC_TOWN_VIEW
@ WC_TOWN_VIEW
Town view; Window numbers:
Definition: window_type.h:333
TileDesc::owner_type
StringID owner_type[4]
Type of each owner.
Definition: tile_cmd.h:56
GetIndustryType
IndustryType GetIndustryType(Tile tile)
Retrieve the type for this industry.
Definition: industry_cmd.cpp:106
AxisToTrackBits
TrackBits AxisToTrackBits(Axis a)
Maps an Axis to the corresponding TrackBits value.
Definition: track_func.h:88
Station::bus_stops
RoadStop * bus_stops
All the road stops.
Definition: station_base.h:451
RVS_IN_DT_ROAD_STOP
@ RVS_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition: roadveh.h:46
ROAD_STOP_TRACKBIT_FACTOR
static const uint ROAD_STOP_TRACKBIT_FACTOR
Multiplier for how many regular track bits a bay stop counts.
Definition: economy_type.h:247
Town::noise_reached
uint16_t noise_reached
level of noise that all the airports are generating
Definition: town.h:64
TileInfo::x
int x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:44
SB
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
Definition: bitmath_func.hpp:58
LinkGraphSchedule::Unqueue
void Unqueue(LinkGraph *lg)
Remove a link graph from the execution queue.
Definition: linkgraphschedule.h:77
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:24
BaseStation::IsInUse
bool IsInUse() const
Check whether the base station currently is in use; in use means that it is not scheduled for deletio...
Definition: base_station_base.h:182
TRACK_BIT_Y
@ TRACK_BIT_Y
Y-axis track.
Definition: track_type.h:38
TimerGameCalendar::date
static Date date
Current date in days (day counter).
Definition: timer_game_calendar.h:34
TileInfo::tile
TileIndex tile
Tile index.
Definition: tile_cmd.h:47
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:619
FlowStat::shares
SharesMap shares
Shares of flow to be sent via specified station (or consumed locally).
Definition: station_base.h:143
GetAllRoadBits
RoadBits GetAllRoadBits(Tile tile)
Get all set RoadBits on the given tile.
Definition: road_map.h:141
Trackdir
Trackdir
Enumeration for tracks and directions.
Definition: track_type.h:67
Cheats::station_rating
Cheat station_rating
Fix station ratings at 100%.
Definition: cheat_type.h:35
IsDockTile
bool IsDockTile(Tile t)
Is tile t a dock tile?
Definition: station_map.h:296
GetIndustrySpec
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
Definition: industry_cmd.cpp:123
AirportSpec::nof_depots
byte nof_depots
the number of hangar tiles in this airport
Definition: newgrf_airport.h:106
CmdRemoveRoadStop
CommandCost CmdRemoveRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
Remove bus or truck stops.
Definition: station_cmd.cpp:2217
StationSpec::callback_mask
byte callback_mask
Bitmask of station callbacks that have to be called.
Definition: newgrf_station.h:157
OrderSettings::selectgoods
bool selectgoods
only send the goods to station if a train has been there
Definition: settings_type.h:507
TileDesc::rail_speed
uint16_t rail_speed
Speed limit of rail (bridges and track)
Definition: tile_cmd.h:65
IsTileType
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
IsRailWaypoint
bool IsRailWaypoint(Tile t)
Is this station tile a rail waypoint?
Definition: station_map.h:113
Vehicle::GetOrderStationLocation
virtual TileIndex GetOrderStationLocation([[maybe_unused]] StationID station)
Determine the location for the station where the vehicle goes to next.
Definition: vehicle_base.h:792
IndustrySpec::name
StringID name
Displayed name of the industry.
Definition: industrytype.h:127
Pool::PoolItem<&_link_graph_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:328
StationSpec::disallowed_lengths
byte disallowed_lengths
Bitmask of platform lengths available for the station.
Definition: newgrf_station.h:137
RoadStop
A Stop for a Road Vehicle.
Definition: roadstop_base.h:22
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:51
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
BaseStation::UpdateVirtCoord
virtual void UpdateVirtCoord()=0
Update the coordinated of the sign (as shown in the viewport).
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:319
FACIL_AIRPORT
@ FACIL_AIRPORT
Station with an airport.
Definition: station_type.h:55
TileX
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:427
TileDesc::tramtype
StringID tramtype
Type of tram on the tile.
Definition: tile_cmd.h:68
CBM_STATION_SPRITE_LAYOUT
@ CBM_STATION_SPRITE_LAYOUT
Use callback to select a sprite layout to use.
Definition: newgrf_callbacks.h:311
AirportTileSpec::name
StringID name
Tile Subname string, land information on this tile will give you "AirportName (TileSubname)".
Definition: newgrf_airporttiles.h:70
WatchedCargoCallback
void WatchedCargoCallback(TileIndex tile, CargoTypes trigger_cargoes)
Run watched cargo accepted callback for a house.
Definition: newgrf_house.cpp:655
NUM_CARGO
static const CargoID NUM_CARGO
Maximum number of cargo types in a game.
Definition: cargo_type.h:74
HasPowerOnRail
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:335
Airport::psa
PersistentStorage * psa
Persistent storage for NewGRF airports.
Definition: station_base.h:298
SLOPE_FLAT
@ SLOPE_FLAT
a flat tile
Definition: slope_type.h:49
Track
Track
These are used to specify a single track.
Definition: track_type.h:19
Airport::GetSpec
const AirportSpec * GetSpec() const
Get the AirportSpec that from the airport type of this airport.
Definition: station_base.h:305
IsRoadStopTile
bool IsRoadStopTile(Tile t)
Is tile t a road stop station?
Definition: station_map.h:213
order_backup.h
AirportSpec::table
const AirportTileTable *const * table
list of the tiles composing the airport
Definition: newgrf_airport.h:102
AirportTileSpec::Get
static const AirportTileSpec * Get(StationGfx gfx)
Retrieve airport tile spec for the given airport tile.
Definition: newgrf_airporttiles.cpp:37
ShowDepotWindow
void ShowDepotWindow(TileIndex tile, VehicleType type)
Opens a depot window.
Definition: depot_gui.cpp:1141
DIAGDIR_NE
@ DIAGDIR_NE
Northeast, upper right on your monitor.
Definition: direction_type.h:75
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
RoadStopClassID
RoadStopClassID
Definition: newgrf_roadstop.h:25
Station::GetTileArea
void GetTileArea(TileArea *ta, StationType type) const override
Get the tile area for a given station type.
Definition: station_cmd.cpp:407
IsCargoInClass
bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
Definition: cargotype.h:230
Company
Definition: company_base.h:129
CMSAMatcher
bool(* CMSAMatcher)(TileIndex tile)
Function to check whether the given tile matches some criterion.
Definition: station_cmd.cpp:140
AirportFTAClass::AIRPLANES
@ AIRPLANES
Can planes land on this airport type?
Definition: airport.h:147
SpecializedVehicle::Last
T * Last()
Get the last vehicle in the chain.
Definition: vehicle_base.h:1114
CC_MAIL
@ CC_MAIL
Mail.
Definition: cargotype.h:51
Town::exclusivity
CompanyID exclusivity
which company has exclusivity
Definition: town.h:71
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
IsTileOwner
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
AirportTileSpec::grf_prop
GRFFileProps grf_prop
properties related the the grf file
Definition: newgrf_airporttiles.h:74
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3112
SetWindowWidgetDirty
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:3099
UpdateAllStationVirtCoords
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
Definition: station_cmd.cpp:472
OWNER_WATER
@ OWNER_WATER
The tile/execution is done by "water".
Definition: company_type.h:26
GetTropicZone
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Definition: tile_map.h:238
NR_STATION
@ NR_STATION
Reference station. Scroll to station when clicking on the news. Delete news when station is deleted.
Definition: news_type.h:56
WC_STATION_LIST
@ WC_STATION_LIST
Station list; Window numbers:
Definition: window_type.h:302
Order::next
Order * next
Pointer to next order. If nullptr, end of list.
Definition: order_base.h:59
ShowWaypointWindow
void ShowWaypointWindow(const Waypoint *wp)
Show the window for the given waypoint.
Definition: waypoint_gui.cpp:197
GetInclinedSlopeDirection
DiagDirection GetInclinedSlopeDirection(Slope s)
Returns the direction of an inclined slope.
Definition: slope_func.h:239
Order
Definition: order_base.h:36
HasTileWaterGround
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
Definition: water_map.h:353
CBID_STATION_SPRITE_LAYOUT
@ CBID_STATION_SPRITE_LAYOUT
Choose a sprite layout to draw, instead of the standard 0-7 range.
Definition: newgrf_callbacks.h:42
ApplyPixelFoundationToSlope
uint ApplyPixelFoundationToSlope(Foundation f, Slope *s)
Applies a foundation to a slope.
Definition: landscape.h:129
GetClosestDeletedStation
static Station * GetClosestDeletedStation(TileIndex tile)
Find the closest deleted station of the current company.
Definition: station_cmd.cpp:384
newgrf_cargo.h
FindJoiningStation
static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
Find a nearby station that joins this station.
Definition: station_cmd.cpp:1204
GoodsEntry::GES_RATING
@ GES_RATING
This indicates whether a cargo has a rating at the station.
Definition: station_base.h:183
GoodsEntry::HasVehicleEverTriedLoading
bool HasVehicleEverTriedLoading() const
Reports whether a vehicle has ever tried to load the cargo at this station.
Definition: station_base.h:252
Convert8bitBooleanCallback
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
Definition: newgrf_commons.cpp:548
Ticks::STATION_ACCEPTANCE_TICKS
static constexpr TimerGameTick::Ticks STATION_ACCEPTANCE_TICKS
Cycle duration for updating station acceptance.
Definition: timer_game_tick.h:79
StationCargoList::Truncate
uint Truncate(uint max_move=UINT_MAX, StationCargoAmountMap *cargo_per_source=nullptr)
Truncates where each destination loses roughly the same percentage of its cargo.
Definition: cargopacket.cpp:763
CompanyInfrastructure::water
uint32_t water
Count of company owned track bits for canals.
Definition: company_base.h:36
Town::exclusive_counter
uint8_t exclusive_counter
months till the exclusivity expires
Definition: town.h:72
SpriteGroup
Definition: newgrf_spritegroup.h:57
Station::ship_station
TileArea ship_station
Tile area the ship 'station' part covers.
Definition: station_base.h:457
IsAirport
bool IsAirport(Tile t)
Is this station tile an airport?
Definition: station_map.h:157
RailTypeInfo::single_y
SpriteID single_y
single piece of rail in Y direction, without ground
Definition: rail.h:138
AxisToRoadBits
RoadBits AxisToRoadBits(Axis a)
Create the road-part which belongs to the given Axis.
Definition: road_func.h:111
FlowStat::ChangeShare
void ChangeShare(StationID st, int flow)
Change share for specified station.
Definition: station_cmd.cpp:4656
VehicleEnterTileStatus
VehicleEnterTileStatus
The returned bits of VehicleEnterTile.
Definition: tile_cmd.h:21
FLYING
@ FLYING
Vehicle is flying in the air.
Definition: airport.h:75
CmdRenameStation
CommandCost CmdRenameStation(DoCommandFlag flags, StationID station_id, const std::string &text)
Rename a station.
Definition: station_cmd.cpp:4109
OWNER_TOWN
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
Definition: company_type.h:24
StationSpec::wires
byte wires
Bitmask of base tiles (0 - 7) which should contain elrail wires.
Definition: newgrf_station.h:162
FindDockLandPart
static TileIndex FindDockLandPart(TileIndex t)
Find the part of a dock that is land-based.
Definition: station_cmd.cpp:2780
newgrf_railtype.h
ConstructionSettings::road_stop_on_town_road
bool road_stop_on_town_road
allow building of drive-through road stops on town owned roads
Definition: settings_type.h:377
MakeDock
void MakeDock(Tile t, Owner o, StationID sid, DiagDirection d, WaterClass wc)
Make the given tile a dock tile.
Definition: station_map.h:745
timer_game_economy.h
IsDriveThroughStopTile
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station?
Definition: station_map.h:233
FlowStatMap::GetFlowFromVia
uint GetFlowFromVia(StationID from, StationID via) const
Get the flow from a specific station via a specific other station.
Definition: station_cmd.cpp:4938
GoodsEntry::last_speed
uint8_t last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
Definition: station_base.h:237
DrawGroundSprite
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:589
AT_OILRIG
@ AT_OILRIG
Oilrig airport.
Definition: airport.h:38
StationNameInformation
Information to handle station action 0 property 24 correctly.
Definition: station_cmd.cpp:221
RailBuildCost
Money RailBuildCost(RailType railtype)
Returns the cost of building the specified railtype.
Definition: rail.h:375
RVSB_ROAD_STOP_TRACKDIR_MASK
@ RVSB_ROAD_STOP_TRACKDIR_MASK
Only bits 0 and 3 are used to encode the trackdir for road stops.
Definition: roadveh.h:57
Map::SizeY
static uint SizeY()
Get the size of the map along the Y.
Definition: map_func.h:279
WC_VEHICLE_ORDERS
@ WC_VEHICLE_ORDERS
Vehicle orders; Window numbers:
Definition: window_type.h:212
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:635
station_widget.h
StationSpec::blocked
byte blocked
Bitmask of base tiles (0 - 7) which are blocked to trains.
Definition: newgrf_station.h:163
debug.h
GetTrainForReservation
Train * GetTrainForReservation(TileIndex tile, Track track)
Find the train which has reserved a specific path.
Definition: pbs.cpp:330
CmdBuildAirport
CommandCost CmdBuildAirport(DoCommandFlag flags, TileIndex tile, byte airport_type, byte layout, StationID station_to_join, bool allow_adjacent)
Place an Airport.
Definition: station_cmd.cpp:2387
Vehicle::refit_cap
uint16_t refit_cap
Capacity left over from before last refit.
Definition: vehicle_base.h:340
TileLayoutSpriteGroup
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
Definition: newgrf_spritegroup.h:259
MakeOilrig
void MakeOilrig(Tile t, StationID sid, WaterClass wc)
Make the given tile an oilrig tile.
Definition: station_map.h:757
CompanyInfrastructure::rail
uint32_t rail[RAILTYPE_END]
Count of company owned track bits for each rail type.
Definition: company_base.h:35
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:98
GoodsEntry::GES_LAST_MONTH
@ GES_LAST_MONTH
Set when cargo was delivered for final delivery last month.
Definition: station_base.h:195
UpdateStationAcceptance
void UpdateStationAcceptance(Station *st, bool show_msg)
Update the acceptance for a station.
Definition: station_cmd.cpp:621
GetCustomRailSprite
SpriteID GetCustomRailSprite(const RailTypeInfo *rti, TileIndex tile, RailTypeSpriteGroup rtsg, TileContext context, uint *num_results)
Get the sprite to draw for the given tile.
Definition: newgrf_railtype.cpp:96
AirportTileSpec::animation
AnimationInfo animation
Information about the animation.
Definition: newgrf_airporttiles.h:69
news_func.h
AddAnimatedTile
void AddAnimatedTile(TileIndex tile)
Add the given tile to the animated tile table (if it does not exist on that table yet).
Definition: animated_tile.cpp:40
roadveh.h
CargoSpec::classes
uint16_t classes
Classes of this cargo type.
Definition: cargotype.h:75
ROADSTOPTYPE_PASSENGER
@ ROADSTOPTYPE_PASSENGER
This RoadStop is for passenger (bus) stops.
Definition: newgrf_roadstop.h:47
INVALID_RAILTYPE
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition: rail_type.h:34
AutoslopeCheckForEntranceEdge
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
BaseStation::build_date
TimerGameCalendar::Date build_date
Date of construction.
Definition: base_station_base.h:80
GetCustomStationSpecIndex
uint GetCustomStationSpecIndex(Tile t)
Get the custom station spec for this tile.
Definition: station_map.h:549
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition: timer_game_economy.h:37
FindFirstBit
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
Definition: bitmath_func.hpp:194
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
INDUSTRYLIFE_EXTRACTIVE
@ INDUSTRYLIFE_EXTRACTIVE
Like mines.
Definition: industrytype.h:28