OpenTTD
station_cmd.cpp
Go to the documentation of this file.
1 /* $Id: station_cmd.cpp 26891 2014-09-21 16:19:52Z fonsinchen $ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #include "stdafx.h"
13 #include "aircraft.h"
14 #include "bridge_map.h"
15 #include "cmd_helper.h"
16 #include "viewport_func.h"
17 #include "command_func.h"
18 #include "town.h"
19 #include "news_func.h"
20 #include "train.h"
21 #include "ship.h"
22 #include "roadveh.h"
23 #include "industry.h"
24 #include "newgrf_cargo.h"
25 #include "newgrf_debug.h"
26 #include "newgrf_station.h"
27 #include "newgrf_canal.h" /* For the buoy */
29 #include "road_internal.h" /* For drawing catenary/checking road removal */
30 #include "autoslope.h"
31 #include "water.h"
32 #include "strings_func.h"
33 #include "clear_func.h"
34 #include "date_func.h"
35 #include "vehicle_func.h"
36 #include "string_func.h"
37 #include "animated_tile_func.h"
38 #include "elrail_func.h"
39 #include "station_base.h"
40 #include "roadstop_base.h"
41 #include "newgrf_railtype.h"
42 #include "waypoint_base.h"
43 #include "waypoint_func.h"
44 #include "pbs.h"
45 #include "debug.h"
46 #include "core/random_func.hpp"
47 #include "company_base.h"
48 #include "table/airporttile_ids.h"
49 #include "newgrf_airporttiles.h"
50 #include "order_backup.h"
51 #include "newgrf_house.h"
52 #include "company_gui.h"
54 #include "linkgraph/refresh.h"
55 #include "widgets/station_widget.h"
56 
57 #include "table/strings.h"
58 
59 #include "safeguards.h"
60 
68 {
69  assert(IsTileType(t, MP_STATION));
70 
71  /* If the tile isn't an airport there's no chance it's a hangar. */
72  if (!IsAirport(t)) return false;
73 
74  const Station *st = Station::GetByTile(t);
75  const AirportSpec *as = st->airport.GetSpec();
76 
77  for (uint i = 0; i < as->nof_depots; i++) {
78  if (st->airport.GetHangarTile(i) == t) return true;
79  }
80 
81  return false;
82 }
83 
91 template <class T>
92 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
93 {
94  ta.tile -= TileDiffXY(1, 1);
95  ta.w += 2;
96  ta.h += 2;
97 
98  /* check around to see if there's any stations there */
99  TILE_AREA_LOOP(tile_cur, ta) {
100  if (IsTileType(tile_cur, MP_STATION)) {
101  StationID t = GetStationIndex(tile_cur);
102  if (!T::IsValidID(t)) continue;
103 
104  if (closest_station == INVALID_STATION) {
105  closest_station = t;
106  } else if (closest_station != t) {
107  return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
108  }
109  }
110  }
111  *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
112  return CommandCost();
113 }
114 
120 typedef bool (*CMSAMatcher)(TileIndex tile);
121 
129 {
130  int num = 0;
131 
132  for (int dx = -3; dx <= 3; dx++) {
133  for (int dy = -3; dy <= 3; dy++) {
134  TileIndex t = TileAddWrap(tile, dx, dy);
135  if (t != INVALID_TILE && cmp(t)) num++;
136  }
137  }
138 
139  return num;
140 }
141 
147 static bool CMSAMine(TileIndex tile)
148 {
149  /* No industry */
150  if (!IsTileType(tile, MP_INDUSTRY)) return false;
151 
152  const Industry *ind = Industry::GetByTile(tile);
153 
154  /* No extractive industry */
155  if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
156 
157  for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
158  /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
159  * Also the production of passengers and mail is ignored. */
160  if (ind->produced_cargo[i] != CT_INVALID &&
162  return true;
163  }
164  }
165 
166  return false;
167 }
168 
174 static bool CMSAWater(TileIndex tile)
175 {
176  return IsTileType(tile, MP_WATER) && IsWater(tile);
177 }
178 
184 static bool CMSATree(TileIndex tile)
185 {
186  return IsTileType(tile, MP_TREES);
187 }
188 
189 #define M(x) ((x) - STR_SV_STNAME)
190 
191 enum StationNaming {
192  STATIONNAMING_RAIL,
193  STATIONNAMING_ROAD,
194  STATIONNAMING_AIRPORT,
195  STATIONNAMING_OILRIG,
196  STATIONNAMING_DOCK,
197  STATIONNAMING_HELIPORT,
198 };
199 
202  uint32 free_names;
203  bool *indtypes;
204 };
205 
214 static bool FindNearIndustryName(TileIndex tile, void *user_data)
215 {
216  /* All already found industry types */
218  if (!IsTileType(tile, MP_INDUSTRY)) return false;
219 
220  /* If the station name is undefined it means that it doesn't name a station */
221  IndustryType indtype = GetIndustryType(tile);
222  if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
223 
224  /* In all cases if an industry that provides a name is found two of
225  * the standard names will be disabled. */
226  sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
227  return !sni->indtypes[indtype];
228 }
229 
230 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
231 {
232  static const uint32 _gen_station_name_bits[] = {
233  0, // STATIONNAMING_RAIL
234  0, // STATIONNAMING_ROAD
235  1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
236  1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
237  1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
238  1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
239  };
240 
241  const Town *t = st->town;
242  uint32 free_names = UINT32_MAX;
243 
244  bool indtypes[NUM_INDUSTRYTYPES];
245  memset(indtypes, 0, sizeof(indtypes));
246 
247  const Station *s;
248  FOR_ALL_STATIONS(s) {
249  if (s != st && s->town == t) {
250  if (s->indtype != IT_INVALID) {
251  indtypes[s->indtype] = true;
253  if (name != STR_UNDEFINED) {
254  /* Filter for other industrytypes with the same name */
255  for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
256  const IndustrySpec *indsp = GetIndustrySpec(it);
257  if (indsp->enabled && indsp->station_name == name) indtypes[it] = true;
258  }
259  }
260  continue;
261  }
262  uint str = M(s->string_id);
263  if (str <= 0x20) {
264  if (str == M(STR_SV_STNAME_FOREST)) {
265  str = M(STR_SV_STNAME_WOODS);
266  }
267  ClrBit(free_names, str);
268  }
269  }
270  }
271 
272  TileIndex indtile = tile;
273  StationNameInformation sni = { free_names, indtypes };
274  if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
275  /* An industry has been found nearby */
276  IndustryType indtype = GetIndustryType(indtile);
277  const IndustrySpec *indsp = GetIndustrySpec(indtype);
278  /* STR_NULL means it only disables oil rig/mines */
279  if (indsp->station_name != STR_NULL) {
280  st->indtype = indtype;
281  return STR_SV_STNAME_FALLBACK;
282  }
283  }
284 
285  /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
286  free_names = sni.free_names;
287 
288  /* check default names */
289  uint32 tmp = free_names & _gen_station_name_bits[name_class];
290  if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
291 
292  /* check mine? */
293  if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
294  if (CountMapSquareAround(tile, CMSAMine) >= 2) {
295  return STR_SV_STNAME_MINES;
296  }
297  }
298 
299  /* check close enough to town to get central as name? */
300  if (DistanceMax(tile, t->xy) < 8) {
301  if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
302 
303  if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
304  }
305 
306  /* Check lakeside */
307  if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
308  DistanceFromEdge(tile) < 20 &&
309  CountMapSquareAround(tile, CMSAWater) >= 5) {
310  return STR_SV_STNAME_LAKESIDE;
311  }
312 
313  /* Check woods */
314  if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
315  CountMapSquareAround(tile, CMSATree) >= 8 ||
317  ) {
318  return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
319  }
320 
321  /* check elevation compared to town */
322  int z = GetTileZ(tile);
323  int z2 = GetTileZ(t->xy);
324  if (z < z2) {
325  if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
326  } else if (z > z2) {
327  if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
328  }
329 
330  /* check direction compared to town */
331  static const int8 _direction_and_table[] = {
332  ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
333  ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
334  ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
335  ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
336  };
337 
338  free_names &= _direction_and_table[
339  (TileX(tile) < TileX(t->xy)) +
340  (TileY(tile) < TileY(t->xy)) * 2];
341 
342  tmp = free_names & ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 12) | (1 << 26) | (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30));
343  return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
344 }
345 #undef M
346 
353 {
354  uint threshold = 8;
355  Station *best_station = NULL;
356  Station *st;
357 
358  FOR_ALL_STATIONS(st) {
359  if (!st->IsInUse() && st->owner == _current_company) {
360  uint cur_dist = DistanceManhattan(tile, st->xy);
361 
362  if (cur_dist < threshold) {
363  threshold = cur_dist;
364  best_station = st;
365  }
366  }
367  }
368 
369  return best_station;
370 }
371 
372 
374 {
375  switch (type) {
376  case STATION_RAIL:
377  *ta = this->train_station;
378  return;
379 
380  case STATION_AIRPORT:
381  *ta = this->airport;
382  return;
383 
384  case STATION_TRUCK:
385  *ta = this->truck_station;
386  return;
387 
388  case STATION_BUS:
389  *ta = this->bus_station;
390  return;
391 
392  case STATION_DOCK:
393  case STATION_OILRIG:
394  ta->tile = this->dock_tile;
395  break;
396 
397  default: NOT_REACHED();
398  }
399 
400  ta->w = 1;
401  ta->h = 1;
402 }
403 
408 {
409  Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
410 
411  pt.y -= 32 * ZOOM_LVL_BASE;
412  if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
413 
414  SetDParam(0, this->index);
415  SetDParam(1, this->facilities);
416  this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
417 
419 }
420 
423 {
424  BaseStation *st;
425 
426  FOR_ALL_BASE_STATIONS(st) {
427  st->UpdateVirtCoord();
428  }
429 }
430 
436 static uint GetAcceptanceMask(const Station *st)
437 {
438  uint mask = 0;
439 
440  for (CargoID i = 0; i < NUM_CARGO; i++) {
441  if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) mask |= 1 << i;
442  }
443  return mask;
444 }
445 
450 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
451 {
452  for (uint i = 0; i < num_items; i++) {
453  SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
454  }
455 
456  SetDParam(0, st->index);
458 }
459 
467 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
468 {
469  CargoArray produced;
470 
471  int x = TileX(tile);
472  int y = TileY(tile);
473 
474  /* expand the region by rad tiles on each side
475  * while making sure that we remain inside the board. */
476  int x2 = min(x + w + rad, MapSizeX());
477  int x1 = max(x - rad, 0);
478 
479  int y2 = min(y + h + rad, MapSizeY());
480  int y1 = max(y - rad, 0);
481 
482  assert(x1 < x2);
483  assert(y1 < y2);
484  assert(w > 0);
485  assert(h > 0);
486 
487  TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
488 
489  /* Loop over all tiles to get the produced cargo of
490  * everything except industries */
491  TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
492 
493  /* Loop over the industries. They produce cargo for
494  * anything that is within 'rad' from their bounding
495  * box. As such if you have e.g. a oil well the tile
496  * area loop might not hit an industry tile while
497  * the industry would produce cargo for the station.
498  */
499  const Industry *i;
500  FOR_ALL_INDUSTRIES(i) {
501  if (!ta.Intersects(i->location)) continue;
502 
503  for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
504  CargoID cargo = i->produced_cargo[j];
505  if (cargo != CT_INVALID) produced[cargo]++;
506  }
507  }
508 
509  return produced;
510 }
511 
520 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
521 {
522  CargoArray acceptance;
523  if (always_accepted != NULL) *always_accepted = 0;
524 
525  int x = TileX(tile);
526  int y = TileY(tile);
527 
528  /* expand the region by rad tiles on each side
529  * while making sure that we remain inside the board. */
530  int x2 = min(x + w + rad, MapSizeX());
531  int y2 = min(y + h + rad, MapSizeY());
532  int x1 = max(x - rad, 0);
533  int y1 = max(y - rad, 0);
534 
535  assert(x1 < x2);
536  assert(y1 < y2);
537  assert(w > 0);
538  assert(h > 0);
539 
540  for (int yc = y1; yc != y2; yc++) {
541  for (int xc = x1; xc != x2; xc++) {
542  TileIndex tile = TileXY(xc, yc);
543  AddAcceptedCargo(tile, acceptance, always_accepted);
544  }
545  }
546 
547  return acceptance;
548 }
549 
555 void UpdateStationAcceptance(Station *st, bool show_msg)
556 {
557  /* old accepted goods types */
558  uint old_acc = GetAcceptanceMask(st);
559 
560  /* And retrieve the acceptance. */
561  CargoArray acceptance;
562  if (!st->rect.IsEmpty()) {
563  acceptance = GetAcceptanceAroundTiles(
564  TileXY(st->rect.left, st->rect.top),
565  st->rect.right - st->rect.left + 1,
566  st->rect.bottom - st->rect.top + 1,
567  st->GetCatchmentRadius(),
568  &st->always_accepted
569  );
570  }
571 
572  /* Adjust in case our station only accepts fewer kinds of goods */
573  for (CargoID i = 0; i < NUM_CARGO; i++) {
574  uint amt = acceptance[i];
575 
576  /* Make sure the station can accept the goods type. */
577  bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
578  if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
579  (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
580  amt = 0;
581  }
582 
583  GoodsEntry &ge = st->goods[i];
584  SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
586  (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
587  }
588  }
589 
590  /* Only show a message in case the acceptance was actually changed. */
591  uint new_acc = GetAcceptanceMask(st);
592  if (old_acc == new_acc) return;
593 
594  /* show a message to report that the acceptance was changed? */
595  if (show_msg && st->owner == _local_company && st->IsInUse()) {
596  /* List of accept and reject strings for different number of
597  * cargo types */
598  static const StringID accept_msg[] = {
599  STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
600  STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
601  };
602  static const StringID reject_msg[] = {
603  STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
604  STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
605  };
606 
607  /* Array of accepted and rejected cargo types */
608  CargoID accepts[2] = { CT_INVALID, CT_INVALID };
609  CargoID rejects[2] = { CT_INVALID, CT_INVALID };
610  uint num_acc = 0;
611  uint num_rej = 0;
612 
613  /* Test each cargo type to see if its acceptance has changed */
614  for (CargoID i = 0; i < NUM_CARGO; i++) {
615  if (HasBit(new_acc, i)) {
616  if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
617  /* New cargo is accepted */
618  accepts[num_acc++] = i;
619  }
620  } else {
621  if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
622  /* Old cargo is no longer accepted */
623  rejects[num_rej++] = i;
624  }
625  }
626  }
627 
628  /* Show news message if there are any changes */
629  if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
630  if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
631  }
632 
633  /* redraw the station view since acceptance changed */
635 }
636 
637 static void UpdateStationSignCoord(BaseStation *st)
638 {
639  const StationRect *r = &st->rect;
640 
641  if (r->IsEmpty()) return; // no tiles belong to this station
642 
643  /* clamp sign coord to be inside the station rect */
644  st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
645  st->UpdateVirtCoord();
646 
647  if (!Station::IsExpected(st)) return;
648  Station *full_station = Station::From(st);
649  for (CargoID c = 0; c < NUM_CARGO; ++c) {
650  LinkGraphID lg = full_station->goods[c].link_graph;
651  if (!LinkGraph::IsValidID(lg)) continue;
652  (*LinkGraph::Get(lg))[full_station->goods[c].node].UpdateLocation(st->xy);
653  }
654 }
655 
665 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
666 {
667  /* Find a deleted station close to us */
668  if (*st == NULL && reuse) *st = GetClosestDeletedStation(area.tile);
669 
670  if (*st != NULL) {
671  if ((*st)->owner != _current_company) {
672  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
673  }
674 
675  CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
676  if (ret.Failed()) return ret;
677  } else {
678  /* allocate and initialize new station */
679  if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
680 
681  if (flags & DC_EXEC) {
682  *st = new Station(area.tile);
683 
684  (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
685  (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
686 
688  SetBit((*st)->town->have_ratings, _current_company);
689  }
690  }
691  }
692  return CommandCost();
693 }
694 
702 {
703  if (!st->IsInUse()) {
704  st->delete_ctr = 0;
706  }
707  /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
708  UpdateStationSignCoord(st);
709 }
710 
712 
722 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
723 {
724  if (check_bridge && IsBridgeAbove(tile)) {
725  return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
726  }
727 
729  if (ret.Failed()) return ret;
730 
731  int z;
732  Slope tileh = GetTileSlope(tile, &z);
733 
734  /* Prohibit building if
735  * 1) The tile is "steep" (i.e. stretches two height levels).
736  * 2) The tile is non-flat and the build_on_slopes switch is disabled.
737  */
738  if ((!allow_steep && IsSteepSlope(tileh)) ||
740  return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
741  }
742 
744  int flat_z = z + GetSlopeMaxZ(tileh);
745  if (tileh != SLOPE_FLAT) {
746  /* Forbid building if the tile faces a slope in a invalid direction. */
747  for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
748  if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
749  return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
750  }
751  }
752  cost.AddCost(_price[PR_BUILD_FOUNDATION]);
753  }
754 
755  /* The level of this tile must be equal to allowed_z. */
756  if (allowed_z < 0) {
757  /* First tile. */
758  allowed_z = flat_z;
759  } else if (allowed_z != flat_z) {
760  return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
761  }
762 
763  return cost;
764 }
765 
773 {
775  int allowed_z = -1;
776 
777  TILE_AREA_LOOP(tile_cur, tile_area) {
778  CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
779  if (ret.Failed()) return ret;
780  cost.AddCost(ret);
781 
782  ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
783  if (ret.Failed()) return ret;
784  cost.AddCost(ret);
785  }
786 
787  return cost;
788 }
789 
804 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, SmallVector<Train *, 4> &affected_vehicles, StationClassID spec_class, byte spec_index, byte plat_len, byte numtracks)
805 {
807  int allowed_z = -1;
808  uint invalid_dirs = 5 << axis;
809 
810  const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
811  bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
812 
813  TILE_AREA_LOOP(tile_cur, tile_area) {
814  CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
815  if (ret.Failed()) return ret;
816  cost.AddCost(ret);
817 
818  if (slope_cb) {
819  /* Do slope check if requested. */
820  ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
821  if (ret.Failed()) return ret;
822  }
823 
824  /* if station is set, then we have special handling to allow building on top of already existing stations.
825  * so station points to INVALID_STATION if we can build on any station.
826  * Or it points to a station if we're only allowed to build on exactly that station. */
827  if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
828  if (!IsRailStation(tile_cur)) {
829  return ClearTile_Station(tile_cur, DC_AUTO); // get error message
830  } else {
831  StationID st = GetStationIndex(tile_cur);
832  if (*station == INVALID_STATION) {
833  *station = st;
834  } else if (*station != st) {
835  return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
836  }
837  }
838  } else {
839  /* Rail type is only valid when building a railway station; if station to
840  * build isn't a rail station it's INVALID_RAILTYPE. */
841  if (rt != INVALID_RAILTYPE &&
842  IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
843  HasPowerOnRail(GetRailType(tile_cur), rt)) {
844  /* Allow overbuilding if the tile:
845  * - has rail, but no signals
846  * - it has exactly one track
847  * - the track is in line with the station
848  * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
849  */
850  TrackBits tracks = GetTrackBits(tile_cur);
851  Track track = RemoveFirstTrack(&tracks);
852  Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
853 
854  if (tracks == TRACK_BIT_NONE && track == expected_track) {
855  /* Check for trains having a reservation for this tile. */
856  if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
857  Train *v = GetTrainForReservation(tile_cur, track);
858  if (v != NULL) {
859  *affected_vehicles.Append() = v;
860  }
861  }
862  CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
863  if (ret.Failed()) return ret;
864  cost.AddCost(ret);
865  /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
866  continue;
867  }
868  }
869  ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
870  if (ret.Failed()) return ret;
871  cost.AddCost(ret);
872  }
873  }
874 
875  return cost;
876 }
877 
890 static CommandCost CheckFlatLandRoadStop(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadTypes rts)
891 {
893  int allowed_z = -1;
894 
895  TILE_AREA_LOOP(cur_tile, tile_area) {
896  CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
897  if (ret.Failed()) return ret;
898  cost.AddCost(ret);
899 
900  /* If station is set, then we have special handling to allow building on top of already existing stations.
901  * Station points to INVALID_STATION if we can build on any station.
902  * Or it points to a station if we're only allowed to build on exactly that station. */
903  if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
904  if (!IsRoadStop(cur_tile)) {
905  return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
906  } else {
907  if (is_truck_stop != IsTruckStop(cur_tile) ||
908  is_drive_through != IsDriveThroughStopTile(cur_tile)) {
909  return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
910  }
911  /* Drive-through station in the wrong direction. */
912  if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
913  return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
914  }
915  StationID st = GetStationIndex(cur_tile);
916  if (*station == INVALID_STATION) {
917  *station = st;
918  } else if (*station != st) {
919  return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
920  }
921  }
922  } else {
923  bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
924  /* Road bits in the wrong direction. */
925  RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
926  if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
927  /* Someone was pedantic and *NEEDED* three fracking different error messages. */
928  switch (CountBits(rb)) {
929  case 1:
930  return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
931 
932  case 2:
933  if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
934  return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
935 
936  default: // 3 or 4
937  return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
938  }
939  }
940 
941  RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
942  uint num_roadbits = 0;
943  if (build_over_road) {
944  /* There is a road, check if we can build road+tram stop over it. */
945  if (HasBit(cur_rts, ROADTYPE_ROAD)) {
946  Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
947  if (road_owner == OWNER_TOWN) {
948  if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
950  CommandCost ret = CheckOwnership(road_owner);
951  if (ret.Failed()) return ret;
952  }
953  num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
954  }
955 
956  /* There is a tram, check if we can build road+tram stop over it. */
957  if (HasBit(cur_rts, ROADTYPE_TRAM)) {
958  Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
960  CommandCost ret = CheckOwnership(tram_owner);
961  if (ret.Failed()) return ret;
962  }
963  num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
964  }
965 
966  /* Take into account existing roadbits. */
967  rts |= cur_rts;
968  } else {
969  ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
970  if (ret.Failed()) return ret;
971  cost.AddCost(ret);
972  }
973 
974  uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
975  cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
976  }
977  }
978 
979  return cost;
980 }
981 
990 {
991  TileArea cur_ta = st->train_station;
992 
993  /* determine new size of train station region.. */
994  int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
995  int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
996  new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
997  new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
998  new_ta.tile = TileXY(x, y);
999 
1000  /* make sure the final size is not too big. */
1002  return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1003  }
1004 
1005  return CommandCost();
1006 }
1007 
1008 static inline byte *CreateSingle(byte *layout, int n)
1009 {
1010  int i = n;
1011  do *layout++ = 0; while (--i);
1012  layout[((n - 1) >> 1) - n] = 2;
1013  return layout;
1014 }
1015 
1016 static inline byte *CreateMulti(byte *layout, int n, byte b)
1017 {
1018  int i = n;
1019  do *layout++ = b; while (--i);
1020  if (n > 4) {
1021  layout[0 - n] = 0;
1022  layout[n - 1 - n] = 0;
1023  }
1024  return layout;
1025 }
1026 
1034 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
1035 {
1036  if (statspec != NULL && statspec->lengths >= plat_len &&
1037  statspec->platforms[plat_len - 1] >= numtracks &&
1038  statspec->layouts[plat_len - 1][numtracks - 1]) {
1039  /* Custom layout defined, follow it. */
1040  memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
1041  plat_len * numtracks);
1042  return;
1043  }
1044 
1045  if (plat_len == 1) {
1046  CreateSingle(layout, numtracks);
1047  } else {
1048  if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1049  numtracks >>= 1;
1050 
1051  while (--numtracks >= 0) {
1052  layout = CreateMulti(layout, plat_len, 4);
1053  layout = CreateMulti(layout, plat_len, 6);
1054  }
1055  }
1056 }
1057 
1069 template <class T, StringID error_message>
1070 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
1071 {
1072  assert(*st == NULL);
1073  bool check_surrounding = true;
1074 
1076  if (existing_station != INVALID_STATION) {
1077  if (adjacent && existing_station != station_to_join) {
1078  /* You can't build an adjacent station over the top of one that
1079  * already exists. */
1080  return_cmd_error(error_message);
1081  } else {
1082  /* Extend the current station, and don't check whether it will
1083  * be near any other stations. */
1084  *st = T::GetIfValid(existing_station);
1085  check_surrounding = (*st == NULL);
1086  }
1087  } else {
1088  /* There's no station here. Don't check the tiles surrounding this
1089  * one if the company wanted to build an adjacent station. */
1090  if (adjacent) check_surrounding = false;
1091  }
1092  }
1093 
1094  if (check_surrounding) {
1095  /* Make sure there are no similar stations around us. */
1096  CommandCost ret = GetStationAround(ta, existing_station, st);
1097  if (ret.Failed()) return ret;
1098  }
1099 
1100  /* Distant join */
1101  if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1102 
1103  return CommandCost();
1104 }
1105 
1115 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1116 {
1117  return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
1118 }
1119 
1129 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
1130 {
1131  return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
1132 }
1133 
1151 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1152 {
1153  /* Unpack parameters */
1154  RailType rt = Extract<RailType, 0, 4>(p1);
1155  Axis axis = Extract<Axis, 4, 1>(p1);
1156  byte numtracks = GB(p1, 8, 8);
1157  byte plat_len = GB(p1, 16, 8);
1158  bool adjacent = HasBit(p1, 24);
1159 
1160  StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
1161  byte spec_index = GB(p2, 8, 8);
1162  StationID station_to_join = GB(p2, 16, 16);
1163 
1164  /* Does the authority allow this? */
1165  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1166  if (ret.Failed()) return ret;
1167 
1168  if (!ValParamRailtype(rt)) return CMD_ERROR;
1169 
1170  /* Check if the given station class is valid */
1171  if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
1172  if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
1173  if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1174 
1175  int w_org, h_org;
1176  if (axis == AXIS_X) {
1177  w_org = plat_len;
1178  h_org = numtracks;
1179  } else {
1180  h_org = plat_len;
1181  w_org = numtracks;
1182  }
1183 
1184  bool reuse = (station_to_join != NEW_STATION);
1185  if (!reuse) station_to_join = INVALID_STATION;
1186  bool distant_join = (station_to_join != INVALID_STATION);
1187 
1188  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1189 
1191 
1192  /* these values are those that will be stored in train_tile and station_platforms */
1193  TileArea new_location(tile_org, w_org, h_org);
1194 
1195  /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1196  StationID est = INVALID_STATION;
1197  SmallVector<Train *, 4> affected_vehicles;
1198  /* Clear the land below the station. */
1199  CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1200  if (cost.Failed()) return cost;
1201  /* Add construction expenses. */
1202  cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
1203  cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
1204 
1205  Station *st = NULL;
1206  ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1207  if (ret.Failed()) return ret;
1208 
1209  ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1210  if (ret.Failed()) return ret;
1211 
1212  if (st != NULL && st->train_station.tile != INVALID_TILE) {
1213  CommandCost ret = CanExpandRailStation(st, new_location, axis);
1214  if (ret.Failed()) return ret;
1215  }
1216 
1217  /* Check if we can allocate a custom stationspec to this station */
1218  const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1219  int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1220  if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1221 
1222  if (statspec != NULL) {
1223  /* Perform NewStation checks */
1224 
1225  /* Check if the station size is permitted */
1226  if (HasBit(statspec->disallowed_platforms, min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, min(plat_len - 1, 7))) {
1227  return CMD_ERROR;
1228  }
1229 
1230  /* Check if the station is buildable */
1231  if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1232  uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
1233  if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1234  }
1235  }
1236 
1237  if (flags & DC_EXEC) {
1238  TileIndexDiff tile_delta;
1239  byte *layout_ptr;
1240  byte numtracks_orig;
1241  Track track;
1242 
1243  st->train_station = new_location;
1244  st->AddFacility(FACIL_TRAIN, new_location.tile);
1245 
1246  st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1247 
1248  if (statspec != NULL) {
1249  /* Include this station spec's animation trigger bitmask
1250  * in the station's cached copy. */
1251  st->cached_anim_triggers |= statspec->animation.triggers;
1252  }
1253 
1254  tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1255  track = AxisToTrack(axis);
1256 
1257  layout_ptr = AllocaM(byte, numtracks * plat_len);
1258  GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
1259 
1260  numtracks_orig = numtracks;
1261 
1262  Company *c = Company::Get(st->owner);
1263  TileIndex tile_track = tile_org;
1264  do {
1265  TileIndex tile = tile_track;
1266  int w = plat_len;
1267  do {
1268  byte layout = *layout_ptr++;
1269  if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1270  /* Check for trains having a reservation for this tile. */
1272  if (v != NULL) {
1274  *affected_vehicles.Append() = v;
1276  for (; v->Next() != NULL; v = v->Next()) { }
1278  }
1279  }
1280 
1281  /* Railtype can change when overbuilding. */
1282  if (IsRailStationTile(tile)) {
1283  if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1284  c->infrastructure.station--;
1285  }
1286 
1287  /* Remove animation if overbuilding */
1288  DeleteAnimatedTile(tile);
1289  byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1290  MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1291  /* Free the spec if we overbuild something */
1292  DeallocateSpecFromStation(st, old_specindex);
1293 
1294  SetCustomStationSpecIndex(tile, specindex);
1295  SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1296  SetAnimationFrame(tile, 0);
1297 
1298  if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1299  c->infrastructure.station++;
1300 
1301  if (statspec != NULL) {
1302  /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1303  uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1304 
1305  /* As the station is not yet completely finished, the station does not yet exist. */
1306  uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
1307  if (callback != CALLBACK_FAILED) {
1308  if (callback < 8) {
1309  SetStationGfx(tile, (callback & ~1) + axis);
1310  } else {
1312  }
1313  }
1314 
1315  /* Trigger station animation -- after building? */
1316  TriggerStationAnimation(st, tile, SAT_BUILT);
1317  }
1318 
1319  tile += tile_delta;
1320  } while (--w);
1321  AddTrackToSignalBuffer(tile_track, track, _current_company);
1322  YapfNotifyTrackLayoutChange(tile_track, track);
1323  tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1324  } while (--numtracks);
1325 
1326  for (uint i = 0; i < affected_vehicles.Length(); ++i) {
1327  /* Restore reservations of trains. */
1328  Train *v = affected_vehicles[i];
1330  TryPathReserve(v, true, true);
1331  for (; v->Next() != NULL; v = v->Next()) { }
1333  }
1334 
1335  /* Check whether we need to expand the reservation of trains already on the station. */
1336  TileArea update_reservation_area;
1337  if (axis == AXIS_X) {
1338  update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1339  } else {
1340  update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1341  }
1342 
1343  TILE_AREA_LOOP(tile, update_reservation_area) {
1344  /* Don't even try to make eye candy parts reserved. */
1345  if (IsStationTileBlocked(tile)) continue;
1346 
1347  DiagDirection dir = AxisToDiagDir(axis);
1348  TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1349  TileIndex platform_begin = tile;
1350  TileIndex platform_end = tile;
1351 
1352  /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1353  for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1354  platform_begin = next_tile;
1355  }
1356  for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1357  platform_end = next_tile;
1358  }
1359 
1360  /* If there is at least on reservation on the platform, we reserve the whole platform. */
1361  bool reservation = false;
1362  for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1363  reservation = HasStationReservation(t);
1364  }
1365 
1366  if (reservation) {
1367  SetRailStationPlatformReservation(platform_begin, dir, true);
1368  }
1369  }
1370 
1371  st->MarkTilesDirty(false);
1372  st->UpdateVirtCoord();
1373  UpdateStationAcceptance(st, false);
1379  }
1380 
1381  return cost;
1382 }
1383 
1384 static void MakeRailStationAreaSmaller(BaseStation *st)
1385 {
1386  TileArea ta = st->train_station;
1387 
1388 restart:
1389 
1390  /* too small? */
1391  if (ta.w != 0 && ta.h != 0) {
1392  /* check the left side, x = constant, y changes */
1393  for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
1394  /* the left side is unused? */
1395  if (++i == ta.h) {
1396  ta.tile += TileDiffXY(1, 0);
1397  ta.w--;
1398  goto restart;
1399  }
1400  }
1401 
1402  /* check the right side, x = constant, y changes */
1403  for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
1404  /* the right side is unused? */
1405  if (++i == ta.h) {
1406  ta.w--;
1407  goto restart;
1408  }
1409  }
1410 
1411  /* check the upper side, y = constant, x changes */
1412  for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
1413  /* the left side is unused? */
1414  if (++i == ta.w) {
1415  ta.tile += TileDiffXY(0, 1);
1416  ta.h--;
1417  goto restart;
1418  }
1419  }
1420 
1421  /* check the lower side, y = constant, x changes */
1422  for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
1423  /* the left side is unused? */
1424  if (++i == ta.w) {
1425  ta.h--;
1426  goto restart;
1427  }
1428  }
1429  } else {
1430  ta.Clear();
1431  }
1432 
1433  st->train_station = ta;
1434 }
1435 
1446 template <class T>
1447 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1448 {
1449  /* Count of the number of tiles removed */
1450  int quantity = 0;
1451  CommandCost total_cost(EXPENSES_CONSTRUCTION);
1452  /* Accumulator for the errors seen during clearing. If no errors happen,
1453  * and the quantity is 0 there is no station. Otherwise it will be one
1454  * of the other error that got accumulated. */
1456 
1457  /* Do the action for every tile into the area */
1458  TILE_AREA_LOOP(tile, ta) {
1459  /* Make sure the specified tile is a rail station */
1460  if (!HasStationTileRail(tile)) continue;
1461 
1462  /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1464  error.AddCost(ret);
1465  if (ret.Failed()) continue;
1466 
1467  /* Check ownership of station */
1468  T *st = T::GetByTile(tile);
1469  if (st == NULL) continue;
1470 
1471  if (_current_company != OWNER_WATER) {
1472  CommandCost ret = CheckOwnership(st->owner);
1473  error.AddCost(ret);
1474  if (ret.Failed()) continue;
1475  }
1476 
1477  /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1478  quantity++;
1479 
1480  if (keep_rail || IsStationTileBlocked(tile)) {
1481  /* Don't refund the 'steel' of the track when we keep the
1482  * rail, or when the tile didn't have any rail at all. */
1483  total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1484  }
1485 
1486  if (flags & DC_EXEC) {
1487  /* read variables before the station tile is removed */
1488  uint specindex = GetCustomStationSpecIndex(tile);
1489  Track track = GetRailStationTrack(tile);
1490  Owner owner = GetTileOwner(tile);
1491  RailType rt = GetRailType(tile);
1492  Train *v = NULL;
1493 
1494  if (HasStationReservation(tile)) {
1495  v = GetTrainForReservation(tile, track);
1496  if (v != NULL) {
1497  /* Free train reservation. */
1500  Vehicle *temp = v;
1501  for (; temp->Next() != NULL; temp = temp->Next()) { }
1503  }
1504  }
1505 
1506  bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1507  if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1508 
1509  DoClearSquare(tile);
1510  DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1511  if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1512  Company::Get(owner)->infrastructure.station--;
1514 
1515  st->rect.AfterRemoveTile(st, tile);
1516  AddTrackToSignalBuffer(tile, track, owner);
1517  YapfNotifyTrackLayoutChange(tile, track);
1518 
1519  DeallocateSpecFromStation(st, specindex);
1520 
1521  affected_stations.Include(st);
1522 
1523  if (v != NULL) {
1524  /* Restore station reservation. */
1526  TryPathReserve(v, true, true);
1527  for (; v->Next() != NULL; v = v->Next()) { }
1529  }
1530  }
1531  }
1532 
1533  if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1534 
1535  for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1536  T *st = *stp;
1537 
1538  /* now we need to make the "spanned" area of the railway station smaller
1539  * if we deleted something at the edges.
1540  * we also need to adjust train_tile. */
1541  MakeRailStationAreaSmaller(st);
1542  UpdateStationSignCoord(st);
1543 
1544  /* if we deleted the whole station, delete the train facility. */
1545  if (st->train_station.tile == INVALID_TILE) {
1546  st->facilities &= ~FACIL_TRAIN;
1548  st->UpdateVirtCoord();
1550  }
1551  }
1552 
1553  total_cost.AddCost(quantity * removal_cost);
1554  return total_cost;
1555 }
1556 
1568 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1569 {
1570  TileIndex end = p1 == 0 ? start : p1;
1571  if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1572 
1573  TileArea ta(start, end);
1574  SmallVector<Station *, 4> affected_stations;
1575 
1576  CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
1577  if (ret.Failed()) return ret;
1578 
1579  /* Do all station specific functions here. */
1580  for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1581  Station *st = *stp;
1582 
1584  st->MarkTilesDirty(false);
1586  }
1587 
1588  /* Now apply the rail cost to the number that we deleted */
1589  return ret;
1590 }
1591 
1603 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1604 {
1605  TileIndex end = p1 == 0 ? start : p1;
1606  if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1607 
1608  TileArea ta(start, end);
1609  SmallVector<Waypoint *, 4> affected_stations;
1610 
1611  return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
1612 }
1613 
1614 
1622 template <class T>
1624 {
1625  /* Current company owns the station? */
1626  if (_current_company != OWNER_WATER) {
1627  CommandCost ret = CheckOwnership(st->owner);
1628  if (ret.Failed()) return ret;
1629  }
1630 
1631  /* determine width and height of platforms */
1632  TileArea ta = st->train_station;
1633 
1634  assert(ta.w != 0 && ta.h != 0);
1635 
1637  /* clear all areas of the station */
1638  TILE_AREA_LOOP(tile, ta) {
1639  /* only remove tiles that are actually train station tiles */
1640  if (!st->TileBelongsToRailStation(tile)) continue;
1641 
1643  if (ret.Failed()) return ret;
1644 
1645  cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
1646  if (flags & DC_EXEC) {
1647  /* read variables before the station tile is removed */
1648  Track track = GetRailStationTrack(tile);
1649  Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
1650  Train *v = NULL;
1651  if (HasStationReservation(tile)) {
1652  v = GetTrainForReservation(tile, track);
1653  if (v != NULL) FreeTrainTrackReservation(v);
1654  }
1655  if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1656  Company::Get(owner)->infrastructure.station--;
1657  DoClearSquare(tile);
1658  DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1659  AddTrackToSignalBuffer(tile, track, owner);
1660  YapfNotifyTrackLayoutChange(tile, track);
1661  if (v != NULL) TryPathReserve(v, true);
1662  }
1663  }
1664 
1665  if (flags & DC_EXEC) {
1666  st->rect.AfterRemoveRect(st, st->train_station);
1667 
1668  st->train_station.Clear();
1669 
1670  st->facilities &= ~FACIL_TRAIN;
1671 
1672  free(st->speclist);
1673  st->num_specs = 0;
1674  st->speclist = NULL;
1675  st->cached_anim_triggers = 0;
1676 
1679  st->UpdateVirtCoord();
1681  }
1682 
1683  return cost;
1684 }
1685 
1693 {
1694  /* if there is flooding, remove platforms tile by tile */
1695  if (_current_company == OWNER_WATER) {
1696  return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
1697  }
1698 
1699  Station *st = Station::GetByTile(tile);
1700  CommandCost cost = RemoveRailStation(st, flags);
1701 
1702  if (flags & DC_EXEC) st->RecomputeIndustriesNear();
1703 
1704  return cost;
1705 }
1706 
1714 {
1715  /* if there is flooding, remove waypoints tile by tile */
1716  if (_current_company == OWNER_WATER) {
1717  return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
1718  }
1719 
1720  return RemoveRailStation(Waypoint::GetByTile(tile), flags);
1721 }
1722 
1723 
1729 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1730 {
1731  RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1732 
1733  if (*primary_stop == NULL) {
1734  /* we have no roadstop of the type yet, so write a "primary stop" */
1735  return primary_stop;
1736  } else {
1737  /* there are stops already, so append to the end of the list */
1738  RoadStop *stop = *primary_stop;
1739  while (stop->next != NULL) stop = stop->next;
1740  return &stop->next;
1741  }
1742 }
1743 
1745 
1755 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1756 {
1757  return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
1758 }
1759 
1776 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1777 {
1778  bool type = HasBit(p2, 0);
1779  bool is_drive_through = HasBit(p2, 1);
1780  RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
1781  StationID station_to_join = GB(p2, 16, 16);
1782  bool reuse = (station_to_join != NEW_STATION);
1783  if (!reuse) station_to_join = INVALID_STATION;
1784  bool distant_join = (station_to_join != INVALID_STATION);
1785 
1786  uint8 width = (uint8)GB(p1, 0, 8);
1787  uint8 lenght = (uint8)GB(p1, 8, 8);
1788 
1789  /* Check if the requested road stop is too big */
1790  if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1791  /* Check for incorrect width / length. */
1792  if (width == 0 || lenght == 0) return CMD_ERROR;
1793  /* Check if the first tile and the last tile are valid */
1794  if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
1795 
1796  TileArea roadstop_area(tile, width, lenght);
1797 
1798  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1799 
1800  if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
1801 
1802  /* Trams only have drive through stops */
1803  if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
1804 
1805  DiagDirection ddir;
1806  Axis axis;
1807  if (is_drive_through) {
1808  /* By definition axis is valid, due to there being 2 axes and reading 1 bit. */
1809  axis = Extract<Axis, 6, 1>(p2);
1810  ddir = AxisToDiagDir(axis);
1811  } else {
1812  /* By definition ddir is valid, due to there being 4 diagonal directions and reading 2 bits. */
1813  ddir = Extract<DiagDirection, 6, 2>(p2);
1814  axis = DiagDirToAxis(ddir);
1815  }
1816 
1817  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
1818  if (ret.Failed()) return ret;
1819 
1820  /* Total road stop cost. */
1821  CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
1822  StationID est = INVALID_STATION;
1823  ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << axis : 1 << ddir, is_drive_through, type, axis, &est, rts);
1824  if (ret.Failed()) return ret;
1825  cost.AddCost(ret);
1826 
1827  Station *st = NULL;
1828  ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
1829  if (ret.Failed()) return ret;
1830 
1831  /* Check if this number of road stops can be allocated. */
1832  if (!RoadStop::CanAllocateItem(roadstop_area.w * roadstop_area.h)) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
1833 
1834  ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
1835  if (ret.Failed()) return ret;
1836 
1837  if (flags & DC_EXEC) {
1838  /* Check every tile in the area. */
1839  TILE_AREA_LOOP(cur_tile, roadstop_area) {
1840  RoadTypes cur_rts = GetRoadTypes(cur_tile);
1841  Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
1842  Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
1843 
1844  if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
1845  RemoveRoadStop(cur_tile, flags);
1846  }
1847 
1848  RoadStop *road_stop = new RoadStop(cur_tile);
1849  /* Insert into linked list of RoadStops. */
1850  RoadStop **currstop = FindRoadStopSpot(type, st);
1851  *currstop = road_stop;
1852 
1853  if (type) {
1854  st->truck_station.Add(cur_tile);
1855  } else {
1856  st->bus_station.Add(cur_tile);
1857  }
1858 
1859  /* Initialize an empty station. */
1860  st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
1861 
1862  st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
1863 
1864  RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
1865  if (is_drive_through) {
1866  /* Update company infrastructure counts. If the current tile is a normal
1867  * road tile, count only the new road bits needed to get a full diagonal road. */
1868  RoadType rt;
1869  FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
1870  Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
1871  if (c != NULL) {
1872  c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
1874  }
1875  }
1876 
1877  MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, axis);
1878  road_stop->MakeDriveThrough();
1879  } else {
1880  /* Non-drive-through stop never overbuild and always count as two road bits. */
1881  Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
1882  MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
1883  }
1884  Company::Get(st->owner)->infrastructure.station++;
1886 
1887  MarkTileDirtyByTile(cur_tile);
1888  }
1889  }
1890 
1891  if (st != NULL) {
1892  st->UpdateVirtCoord();
1893  UpdateStationAcceptance(st, false);
1898  }
1899  return cost;
1900 }
1901 
1902 
1903 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
1904 {
1905  if (v->type == VEH_ROAD) {
1906  /* Okay... we are a road vehicle on a drive through road stop.
1907  * But that road stop has just been removed, so we need to make
1908  * sure we are in a valid state... however, vehicles can also
1909  * turn on road stop tiles, so only clear the 'road stop' state
1910  * bits and only when the state was 'in road stop', otherwise
1911  * we'll end up clearing the turn around bits. */
1912  RoadVehicle *rv = RoadVehicle::From(v);
1914  }
1915 
1916  return NULL;
1917 }
1918 
1919 
1927 {
1928  Station *st = Station::GetByTile(tile);
1929 
1930  if (_current_company != OWNER_WATER) {
1931  CommandCost ret = CheckOwnership(st->owner);
1932  if (ret.Failed()) return ret;
1933  }
1934 
1935  bool is_truck = IsTruckStop(tile);
1936 
1937  RoadStop **primary_stop;
1938  RoadStop *cur_stop;
1939  if (is_truck) { // truck stop
1940  primary_stop = &st->truck_stops;
1941  cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
1942  } else {
1943  primary_stop = &st->bus_stops;
1944  cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
1945  }
1946 
1947  assert(cur_stop != NULL);
1948 
1949  /* don't do the check for drive-through road stops when company bankrupts */
1950  if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
1951  /* remove the 'going through road stop' status from all vehicles on that tile */
1952  if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
1953  } else {
1955  if (ret.Failed()) return ret;
1956  }
1957 
1958  if (flags & DC_EXEC) {
1959  if (*primary_stop == cur_stop) {
1960  /* removed the first stop in the list */
1961  *primary_stop = cur_stop->next;
1962  /* removed the only stop? */
1963  if (*primary_stop == NULL) {
1964  st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
1965  }
1966  } else {
1967  /* tell the predecessor in the list to skip this stop */
1968  RoadStop *pred = *primary_stop;
1969  while (pred->next != cur_stop) pred = pred->next;
1970  pred->next = cur_stop->next;
1971  }
1972 
1973  /* Update company infrastructure counts. */
1974  RoadType rt;
1975  FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
1976  Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
1977  if (c != NULL) {
1978  c->infrastructure.road[rt] -= 2;
1980  }
1981  }
1982  Company::Get(st->owner)->infrastructure.station--;
1983 
1984  if (IsDriveThroughStopTile(tile)) {
1985  /* Clears the tile for us */
1986  cur_stop->ClearDriveThrough();
1987  } else {
1988  DoClearSquare(tile);
1989  }
1990 
1992  delete cur_stop;
1993 
1994  /* Make sure no vehicle is going to the old roadstop */
1995  RoadVehicle *v;
1996  FOR_ALL_ROADVEHICLES(v) {
1997  if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
1998  v->dest_tile == tile) {
2000  }
2001  }
2002 
2003  st->rect.AfterRemoveTile(st, tile);
2004 
2005  st->UpdateVirtCoord();
2008 
2009  /* Update the tile area of the truck/bus stop */
2010  if (is_truck) {
2011  st->truck_station.Clear();
2012  for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
2013  } else {
2014  st->bus_station.Clear();
2015  for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
2016  }
2017  }
2018 
2019  return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
2020 }
2021 
2032 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2033 {
2034  uint8 width = (uint8)GB(p1, 0, 8);
2035  uint8 height = (uint8)GB(p1, 8, 8);
2036 
2037  /* Check for incorrect width / height. */
2038  if (width == 0 || height == 0) return CMD_ERROR;
2039  /* Check if the first tile and the last tile are valid */
2040  if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2041 
2042  TileArea roadstop_area(tile, width, height);
2043 
2044  int quantity = 0;
2046  TILE_AREA_LOOP(cur_tile, roadstop_area) {
2047  /* Make sure the specified tile is a road stop of the correct type */
2048  if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
2049 
2050  /* Save the stop info before it is removed */
2051  bool is_drive_through = IsDriveThroughStopTile(cur_tile);
2052  RoadTypes rts = GetRoadTypes(cur_tile);
2053  RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
2054  ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
2055  DiagDirToRoadBits(GetRoadStopDir(cur_tile));
2056 
2057  Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
2058  Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
2059  CommandCost ret = RemoveRoadStop(cur_tile, flags);
2060  if (ret.Failed()) return ret;
2061  cost.AddCost(ret);
2062 
2063  quantity++;
2064  /* If the stop was a drive-through stop replace the road */
2065  if ((flags & DC_EXEC) && is_drive_through) {
2066  MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2067  road_owner, tram_owner);
2068 
2069  /* Update company infrastructure counts. */
2070  RoadType rt;
2071  FOR_EACH_SET_ROADTYPE(rt, rts) {
2072  Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
2073  if (c != NULL) {
2074  c->infrastructure.road[rt] += CountBits(road_bits);
2076  }
2077  }
2078  }
2079  }
2080 
2081  if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
2082 
2083  return cost;
2084 }
2085 
2093 {
2094  uint mindist = UINT_MAX;
2095 
2096  for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2097  mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
2098  }
2099 
2100  return mindist;
2101 }
2102 
2113 {
2114  /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2115  * So no need to go any further*/
2116  if (as->noise_level < 2) return as->noise_level;
2117 
2118  uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
2119 
2120  /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2121  * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2122  * Basically, it says that the less tolerant a town is, the bigger the distance before
2123  * an actual decrease can be granted */
2124  uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2125 
2126  /* now, we want to have the distance segmented using the distance judged bareable by town
2127  * This will give us the coefficient of reduction the distance provides. */
2128  uint noise_reduction = distance / town_tolerance_distance;
2129 
2130  /* If the noise reduction equals the airport noise itself, don't give it for free.
2131  * Otherwise, simply reduce the airport's level. */
2132  return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2133 }
2134 
2143 {
2144  Town *t, *nearest = NULL;
2145  uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2146  uint mindist = UINT_MAX - add; // prevent overflow
2147  FOR_ALL_TOWNS(t) {
2148  if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
2149  TileIterator *copy = it.Clone();
2150  uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
2151  delete copy;
2152  if (dist < mindist) {
2153  nearest = t;
2154  mindist = dist;
2155  }
2156  }
2157  }
2158 
2159  return nearest;
2160 }
2161 
2162 
2165 {
2166  Town *t;
2167  const Station *st;
2168 
2169  FOR_ALL_TOWNS(t) t->noise_reached = 0;
2170 
2171  FOR_ALL_STATIONS(st) {
2172  if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2173  const AirportSpec *as = st->airport.GetSpec();
2174  AirportTileIterator it(st);
2175  Town *nearest = AirportGetNearestTown(as, it);
2176  nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
2177  }
2178  }
2179 }
2180 
2194 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2195 {
2196  StationID station_to_join = GB(p2, 16, 16);
2197  bool reuse = (station_to_join != NEW_STATION);
2198  if (!reuse) station_to_join = INVALID_STATION;
2199  bool distant_join = (station_to_join != INVALID_STATION);
2200  byte airport_type = GB(p1, 0, 8);
2201  byte layout = GB(p1, 8, 8);
2202 
2203  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2204 
2205  if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2206 
2207  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2208  if (ret.Failed()) return ret;
2209 
2210  /* Check if a valid, buildable airport was chosen for construction */
2211  const AirportSpec *as = AirportSpec::Get(airport_type);
2212  if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
2213 
2214  Direction rotation = as->rotation[layout];
2215  int w = as->size_x;
2216  int h = as->size_y;
2217  if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2218  TileArea airport_area = TileArea(tile, w, h);
2219 
2221  return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2222  }
2223 
2224  CommandCost cost = CheckFlatLand(airport_area, flags);
2225  if (cost.Failed()) return cost;
2226 
2227  /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2228  AirportTileTableIterator iter(as->table[layout], tile);
2229  Town *nearest = AirportGetNearestTown(as, iter);
2230  uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
2231 
2232  /* Check if local auth would allow a new airport */
2233  StringID authority_refuse_message = STR_NULL;
2234  Town *authority_refuse_town = NULL;
2235 
2237  /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2238  if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2239  authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2240  authority_refuse_town = nearest;
2241  }
2242  } else {
2243  Town *t = ClosestTownFromTile(tile, UINT_MAX);
2244  uint num = 0;
2245  const Station *st;
2246  FOR_ALL_STATIONS(st) {
2247  if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2248  }
2249  if (num >= 2) {
2250  authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2251  authority_refuse_town = t;
2252  }
2253  }
2254 
2255  if (authority_refuse_message != STR_NULL) {
2256  SetDParam(0, authority_refuse_town->index);
2257  return_cmd_error(authority_refuse_message);
2258  }
2259 
2260  Station *st = NULL;
2261  ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
2262  if (ret.Failed()) return ret;
2263 
2264  /* Distant join */
2265  if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
2266 
2267  ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2268  if (ret.Failed()) return ret;
2269 
2270  if (st != NULL && st->airport.tile != INVALID_TILE) {
2271  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2272  }
2273 
2274  for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2275  cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2276  }
2277 
2278  if (flags & DC_EXEC) {
2279  /* Always add the noise, so there will be no need to recalculate when option toggles */
2280  nearest->noise_reached += newnoise_level;
2281 
2282  st->AddFacility(FACIL_AIRPORT, tile);
2283  st->airport.type = airport_type;
2284  st->airport.layout = layout;
2285  st->airport.flags = 0;
2286  st->airport.rotation = rotation;
2287 
2288  st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2289 
2290  for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2291  MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2292  SetStationTileRandomBits(iter, GB(Random(), 0, 4));
2293  st->airport.Add(iter);
2294 
2296  }
2297 
2298  /* Only call the animation trigger after all tiles have been built */
2299  for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2300  AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2301  }
2302 
2304 
2305  Company::Get(st->owner)->infrastructure.airport++;
2307 
2308  st->UpdateVirtCoord();
2309  UpdateStationAcceptance(st, false);
2314 
2317  }
2318  }
2319 
2320  return cost;
2321 }
2322 
2330 {
2331  Station *st = Station::GetByTile(tile);
2332 
2333  if (_current_company != OWNER_WATER) {
2334  CommandCost ret = CheckOwnership(st->owner);
2335  if (ret.Failed()) return ret;
2336  }
2337 
2338  tile = st->airport.tile;
2339 
2341 
2342  const Aircraft *a;
2343  FOR_ALL_AIRCRAFT(a) {
2344  if (!a->IsNormalAircraft()) continue;
2345  if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
2346  }
2347 
2348  if (flags & DC_EXEC) {
2349  const AirportSpec *as = st->airport.GetSpec();
2350  /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2351  * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2352  * need of recalculation */
2353  AirportTileIterator it(st);
2354  Town *nearest = AirportGetNearestTown(as, it);
2355  nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
2356  }
2357 
2358  TILE_AREA_LOOP(tile_cur, st->airport) {
2359  if (!st->TileBelongsToAirport(tile_cur)) continue;
2360 
2361  CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2362  if (ret.Failed()) return ret;
2363 
2364  cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2365 
2366  if (flags & DC_EXEC) {
2367  if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
2368  DeleteAnimatedTile(tile_cur);
2369  DoClearSquare(tile_cur);
2370  DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2371  }
2372  }
2373 
2374  if (flags & DC_EXEC) {
2375  /* Clear the persistent storage. */
2376  delete st->airport.psa;
2377 
2378  for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2381  );
2382  }
2383 
2384  st->rect.AfterRemoveRect(st, st->airport);
2385 
2386  st->airport.Clear();
2387  st->facilities &= ~FACIL_AIRPORT;
2388 
2390 
2393  }
2394 
2395  Company::Get(st->owner)->infrastructure.airport--;
2397 
2398  st->UpdateVirtCoord();
2401  DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2402  }
2403 
2404  return cost;
2405 }
2406 
2416 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2417 {
2418  if (!Station::IsValidID(p1)) return CMD_ERROR;
2419  Station *st = Station::Get(p1);
2420 
2421  if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2422 
2423  CommandCost ret = CheckOwnership(st->owner);
2424  if (ret.Failed()) return ret;
2425 
2426  if (flags & DC_EXEC) {
2429  }
2430  return CommandCost();
2431 }
2432 
2439 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2440 {
2441  const Vehicle *v;
2442  FOR_ALL_VEHICLES(v) {
2443  if ((v->owner == company) == include_company) {
2444  const Order *order;
2445  FOR_VEHICLE_ORDERS(v, order) {
2446  if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
2447  return true;
2448  }
2449  }
2450  }
2451  }
2452  return false;
2453 }
2454 
2455 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2456  {-1, 0},
2457  { 0, 0},
2458  { 0, 0},
2459  { 0, -1}
2460 };
2461 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
2462 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
2463 
2473 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2474 {
2475  StationID station_to_join = GB(p2, 16, 16);
2476  bool reuse = (station_to_join != NEW_STATION);
2477  if (!reuse) station_to_join = INVALID_STATION;
2478  bool distant_join = (station_to_join != INVALID_STATION);
2479 
2480  if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2481 
2483  if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2484  direction = ReverseDiagDir(direction);
2485 
2486  /* Docks cannot be placed on rapids */
2487  if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2488 
2489  CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2490  if (ret.Failed()) return ret;
2491 
2492  if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2493 
2494  ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2495  if (ret.Failed()) return ret;
2496 
2497  TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2498 
2499  if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2500  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2501  }
2502 
2503  if (IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2504 
2505  /* Get the water class of the water tile before it is cleared.*/
2506  WaterClass wc = GetWaterClass(tile_cur);
2507 
2508  ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2509  if (ret.Failed()) return ret;
2510 
2511  tile_cur += TileOffsByDiagDir(direction);
2512  if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2513  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2514  }
2515 
2516  TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2517  _dock_w_chk[direction], _dock_h_chk[direction]);
2518 
2519  /* middle */
2520  Station *st = NULL;
2521  ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
2522  if (ret.Failed()) return ret;
2523 
2524  /* Distant join */
2525  if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
2526 
2527  ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2528  if (ret.Failed()) return ret;
2529 
2530  if (st != NULL && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
2531 
2532  if (flags & DC_EXEC) {
2533  st->dock_tile = tile;
2534  st->AddFacility(FACIL_DOCK, tile);
2535 
2536  st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2537 
2538  /* If the water part of the dock is on a canal, update infrastructure counts.
2539  * This is needed as we've unconditionally cleared that tile before. */
2540  if (wc == WATER_CLASS_CANAL) {
2541  Company::Get(st->owner)->infrastructure.water++;
2542  }
2543  Company::Get(st->owner)->infrastructure.station += 2;
2545 
2546  MakeDock(tile, st->owner, st->index, direction, wc);
2547 
2548  st->UpdateVirtCoord();
2549  UpdateStationAcceptance(st, false);
2554  }
2555 
2556  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2557 }
2558 
2566 {
2567  Station *st = Station::GetByTile(tile);
2568  CommandCost ret = CheckOwnership(st->owner);
2569  if (ret.Failed()) return ret;
2570 
2571  TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
2572 
2573  TileIndex tile1 = st->dock_tile;
2574  TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2575 
2576  ret = EnsureNoVehicleOnGround(tile1);
2577  if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2578  if (ret.Failed()) return ret;
2579 
2580  if (flags & DC_EXEC) {
2581  DoClearSquare(tile1);
2582  MarkTileDirtyByTile(tile1);
2583  MakeWaterKeepingClass(tile2, st->owner);
2584 
2585  st->rect.AfterRemoveTile(st, tile1);
2586  st->rect.AfterRemoveTile(st, tile2);
2587 
2588  st->dock_tile = INVALID_TILE;
2589  st->facilities &= ~FACIL_DOCK;
2590 
2591  Company::Get(st->owner)->infrastructure.station -= 2;
2593 
2595  st->UpdateVirtCoord();
2598 
2599  /* All ships that were going to our station, can't go to it anymore.
2600  * Just clear the order, then automatically the next appropriate order
2601  * will be selected and in case of no appropriate order it will just
2602  * wander around the world. */
2603  Ship *s;
2604  FOR_ALL_SHIPS(s) {
2605  if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
2606  s->LeaveStation();
2607  }
2608 
2609  if (s->dest_tile == docking_location) {
2610  s->dest_tile = 0;
2611  s->current_order.Free();
2612  }
2613  }
2614  }
2615 
2616  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
2617 }
2618 
2619 #include "table/station_land.h"
2620 
2621 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
2622 {
2623  return &_station_display_datas[st][gfx];
2624 }
2625 
2635 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
2636 {
2637  bool snow_desert;
2638  switch (*ground) {
2639  case SPR_RAIL_TRACK_X:
2640  snow_desert = false;
2641  *overlay_offset = RTO_X;
2642  break;
2643 
2644  case SPR_RAIL_TRACK_Y:
2645  snow_desert = false;
2646  *overlay_offset = RTO_Y;
2647  break;
2648 
2649  case SPR_RAIL_TRACK_X_SNOW:
2650  snow_desert = true;
2651  *overlay_offset = RTO_X;
2652  break;
2653 
2654  case SPR_RAIL_TRACK_Y_SNOW:
2655  snow_desert = true;
2656  *overlay_offset = RTO_Y;
2657  break;
2658 
2659  default:
2660  return false;
2661  }
2662 
2663  if (ti != NULL) {
2664  /* Decide snow/desert from tile */
2666  case LT_ARCTIC:
2667  snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
2668  break;
2669 
2670  case LT_TROPIC:
2671  snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
2672  break;
2673 
2674  default:
2675  break;
2676  }
2677  }
2678 
2679  *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
2680  return true;
2681 }
2682 
2683 static void DrawTile_Station(TileInfo *ti)
2684 {
2685  const NewGRFSpriteLayout *layout = NULL;
2686  DrawTileSprites tmp_rail_layout;
2687  const DrawTileSprites *t = NULL;
2688  RoadTypes roadtypes;
2689  int32 total_offset;
2690  const RailtypeInfo *rti = NULL;
2691  uint32 relocation = 0;
2692  uint32 ground_relocation = 0;
2693  BaseStation *st = NULL;
2694  const StationSpec *statspec = NULL;
2695  uint tile_layout = 0;
2696 
2697  if (HasStationRail(ti->tile)) {
2698  rti = GetRailTypeInfo(GetRailType(ti->tile));
2699  roadtypes = ROADTYPES_NONE;
2700  total_offset = rti->GetRailtypeSpriteOffset();
2701 
2702  if (IsCustomStationSpecIndex(ti->tile)) {
2703  /* look for customization */
2704  st = BaseStation::GetByTile(ti->tile);
2705  statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
2706 
2707  if (statspec != NULL) {
2708  tile_layout = GetStationGfx(ti->tile);
2709 
2711  uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
2712  if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
2713  }
2714 
2715  /* Ensure the chosen tile layout is valid for this custom station */
2716  if (statspec->renderdata != NULL) {
2717  layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
2718  if (!layout->NeedsPreprocessing()) {
2719  t = layout;
2720  layout = NULL;
2721  }
2722  }
2723  }
2724  }
2725  } else {
2726  roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
2727  total_offset = 0;
2728  }
2729 
2730  StationGfx gfx = GetStationGfx(ti->tile);
2731  if (IsAirport(ti->tile)) {
2732  gfx = GetAirportGfx(ti->tile);
2733  if (gfx >= NEW_AIRPORTTILE_OFFSET) {
2734  const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
2735  if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
2736  return;
2737  }
2738  /* No sprite group (or no valid one) found, meaning no graphics associated.
2739  * Use the substitute one instead */
2740  assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
2741  gfx = ats->grf_prop.subst_id;
2742  }
2743  switch (gfx) {
2744  case APT_RADAR_GRASS_FENCE_SW:
2745  t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
2746  break;
2747  case APT_GRASS_FENCE_NE_FLAG:
2748  t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
2749  break;
2750  case APT_RADAR_FENCE_SW:
2751  t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
2752  break;
2753  case APT_RADAR_FENCE_NE:
2754  t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
2755  break;
2756  case APT_GRASS_FENCE_NE_FLAG_2:
2757  t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
2758  break;
2759  }
2760  }
2761 
2762  Owner owner = GetTileOwner(ti->tile);
2763 
2764  PaletteID palette;
2765  if (Company::IsValidID(owner)) {
2766  palette = COMPANY_SPRITE_COLOUR(owner);
2767  } else {
2768  /* Some stations are not owner by a company, namely oil rigs */
2769  palette = PALETTE_TO_GREY;
2770  }
2771 
2772  if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
2773 
2774  /* don't show foundation for docks */
2775  if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
2776  if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
2777  /* Station has custom foundations.
2778  * Check whether the foundation continues beyond the tile's upper sides. */
2779  uint edge_info = 0;
2780  int z;
2781  Slope slope = GetFoundationPixelSlope(ti->tile, &z);
2782  if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
2783  if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
2784  SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
2785  if (image == 0) goto draw_default_foundation;
2786 
2787  if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
2788  /* Station provides extended foundations. */
2789 
2790  static const uint8 foundation_parts[] = {
2791  0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2792  0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2793  0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2794  7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2795  };
2796 
2797  AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2798  } else {
2799  /* Draw simple foundations, built up from 8 possible foundation sprites. */
2800 
2801  /* Each set bit represents one of the eight composite sprites to be drawn.
2802  * 'Invalid' entries will not drawn but are included for completeness. */
2803  static const uint8 composite_foundation_parts[] = {
2804  /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2805  0x00, 0xD1, 0xE4, 0xE0,
2806  /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2807  0xCA, 0xC9, 0xC4, 0xC0,
2808  /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2809  0xD2, 0x91, 0xE4, 0xA0,
2810  /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2811  0x4A, 0x09, 0x44
2812  };
2813 
2814  uint8 parts = composite_foundation_parts[ti->tileh];
2815 
2816  /* If foundations continue beyond the tile's upper sides then
2817  * mask out the last two pieces. */
2818  if (HasBit(edge_info, 0)) ClrBit(parts, 6);
2819  if (HasBit(edge_info, 1)) ClrBit(parts, 7);
2820 
2821  if (parts == 0) {
2822  /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2823  * correct offset for the childsprites.
2824  * So, draw the (completely empty) sprite of the default foundations. */
2825  goto draw_default_foundation;
2826  }
2827 
2829  for (int i = 0; i < 8; i++) {
2830  if (HasBit(parts, i)) {
2831  AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2832  }
2833  }
2834  EndSpriteCombine();
2835  }
2836 
2837  OffsetGroundSprite(31, 1);
2839  } else {
2840 draw_default_foundation:
2842  }
2843  }
2844 
2845  if (IsBuoy(ti->tile)) {
2846  DrawWaterClassGround(ti);
2847  SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
2848  if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
2849  } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
2850  if (ti->tileh == SLOPE_FLAT) {
2851  DrawWaterClassGround(ti);
2852  } else {
2853  assert(IsDock(ti->tile));
2854  TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
2855  WaterClass wc = GetWaterClass(water_tile);
2856  if (wc == WATER_CLASS_SEA) {
2857  DrawShoreTile(ti->tileh);
2858  } else {
2859  DrawClearLandTile(ti, 3);
2860  }
2861  }
2862  } else {
2863  if (layout != NULL) {
2864  /* Sprite layout which needs preprocessing */
2865  bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
2866  uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
2867  uint8 var10;
2868  FOR_EACH_SET_BIT(var10, var10_values) {
2869  uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
2870  layout->ProcessRegisters(var10, var10_relocation, separate_ground);
2871  }
2872  tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
2873  t = &tmp_rail_layout;
2874  total_offset = 0;
2875  } else if (statspec != NULL) {
2876  /* Simple sprite layout */
2877  ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
2878  if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
2879  ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
2880  }
2881  ground_relocation += rti->fallback_railtype;
2882  }
2883 
2884  SpriteID image = t->ground.sprite;
2885  PaletteID pal = t->ground.pal;
2886  RailTrackOffset overlay_offset;
2887  if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
2888  SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2889  DrawGroundSprite(image, PAL_NONE);
2890  DrawGroundSprite(ground + overlay_offset, PAL_NONE);
2891 
2892  if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
2893  SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2894  DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
2895  }
2896  } else {
2897  image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
2898  if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
2899  DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
2900 
2901  /* PBS debugging, draw reserved tracks darker */
2902  if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
2903  const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2905  }
2906  }
2907  }
2908 
2910 
2911  if (HasBit(roadtypes, ROADTYPE_TRAM)) {
2912  Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
2913  DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
2914  DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
2915  }
2916 
2917  if (IsRailWaypoint(ti->tile)) {
2918  /* Don't offset the waypoint graphics; they're always the same. */
2919  total_offset = 0;
2920  }
2921 
2922  DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
2923 }
2924 
2925 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
2926 {
2927  int32 total_offset = 0;
2928  PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
2929  const DrawTileSprites *t = GetStationTileLayout(st, image);
2930  const RailtypeInfo *rti = NULL;
2931 
2932  if (railtype != INVALID_RAILTYPE) {
2933  rti = GetRailTypeInfo(railtype);
2934  total_offset = rti->GetRailtypeSpriteOffset();
2935  }
2936 
2937  SpriteID img = t->ground.sprite;
2938  RailTrackOffset overlay_offset;
2939  if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
2941  DrawSprite(img, PAL_NONE, x, y);
2942  DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
2943  } else {
2944  DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
2945  }
2946 
2947  if (roadtype == ROADTYPE_TRAM) {
2948  DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
2949  }
2950 
2951  /* Default waypoint has no railtype specific sprites */
2952  DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
2953 }
2954 
2955 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
2956 {
2957  return GetTileMaxPixelZ(tile);
2958 }
2959 
2960 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
2961 {
2962  return FlatteningFoundation(tileh);
2963 }
2964 
2965 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
2966 {
2967  td->owner[0] = GetTileOwner(tile);
2968  if (IsDriveThroughStopTile(tile)) {
2969  Owner road_owner = INVALID_OWNER;
2970  Owner tram_owner = INVALID_OWNER;
2971  RoadTypes rts = GetRoadTypes(tile);
2972  if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
2973  if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
2974 
2975  /* Is there a mix of owners? */
2976  if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
2977  (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
2978  uint i = 1;
2979  if (road_owner != INVALID_OWNER) {
2980  td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
2981  td->owner[i] = road_owner;
2982  i++;
2983  }
2984  if (tram_owner != INVALID_OWNER) {
2985  td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
2986  td->owner[i] = tram_owner;
2987  }
2988  }
2989  }
2991 
2992  if (HasStationTileRail(tile)) {
2993  const StationSpec *spec = GetStationSpec(tile);
2994 
2995  if (spec != NULL) {
2997  td->station_name = spec->name;
2998 
2999  if (spec->grf_prop.grffile != NULL) {
3000  const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3001  td->grf = gc->GetName();
3002  }
3003  }
3004 
3005  const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3006  td->rail_speed = rti->max_speed;
3007  }
3008 
3009  if (IsAirport(tile)) {
3010  const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3012  td->airport_name = as->name;
3013 
3014  const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3015  td->airport_tile_name = ats->name;
3016 
3017  if (as->grf_prop.grffile != NULL) {
3018  const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3019  td->grf = gc->GetName();
3020  } else if (ats->grf_prop.grffile != NULL) {
3021  const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3022  td->grf = gc->GetName();
3023  }
3024  }
3025 
3026  StringID str;
3027  switch (GetStationType(tile)) {
3028  default: NOT_REACHED();
3029  case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3030  case STATION_AIRPORT:
3031  str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3032  break;
3033  case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3034  case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3035  case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
3036  case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3037  case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3038  case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3039  }
3040  td->str = str;
3041 }
3042 
3043 
3044 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3045 {
3046  TrackBits trackbits = TRACK_BIT_NONE;
3047 
3048  switch (mode) {
3049  case TRANSPORT_RAIL:
3050  if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3051  trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3052  }
3053  break;
3054 
3055  case TRANSPORT_WATER:
3056  /* buoy is coded as a station, it is always on open water */
3057  if (IsBuoy(tile)) {
3058  trackbits = TRACK_BIT_ALL;
3059  /* remove tracks that connect NE map edge */
3060  if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3061  /* remove tracks that connect NW map edge */
3062  if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3063  }
3064  break;
3065 
3066  case TRANSPORT_ROAD:
3067  if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
3068  DiagDirection dir = GetRoadStopDir(tile);
3069  Axis axis = DiagDirToAxis(dir);
3070 
3071  if (side != INVALID_DIAGDIR) {
3072  if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
3073  }
3074 
3075  trackbits = AxisToTrackBits(axis);
3076  }
3077  break;
3078 
3079  default:
3080  break;
3081  }
3082 
3084 }
3085 
3086 
3087 static void TileLoop_Station(TileIndex tile)
3088 {
3089  /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3090  * hardcoded.....not good */
3091  switch (GetStationType(tile)) {
3092  case STATION_AIRPORT:
3093  AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3094  break;
3095 
3096  case STATION_DOCK:
3097  if (!IsTileFlat(tile)) break; // only handle water part
3098  /* FALL THROUGH */
3099  case STATION_OILRIG: //(station part)
3100  case STATION_BUOY:
3101  TileLoop_Water(tile);
3102  break;
3103 
3104  default: break;
3105  }
3106 }
3107 
3108 
3109 static void AnimateTile_Station(TileIndex tile)
3110 {
3111  if (HasStationRail(tile)) {
3112  AnimateStationTile(tile);
3113  return;
3114  }
3115 
3116  if (IsAirport(tile)) {
3117  AnimateAirportTile(tile);
3118  }
3119 }
3120 
3121 
3122 static bool ClickTile_Station(TileIndex tile)
3123 {
3124  const BaseStation *bst = BaseStation::GetByTile(tile);
3125 
3126  if (bst->facilities & FACIL_WAYPOINT) {
3128  } else if (IsHangar(tile)) {
3129  const Station *st = Station::From(bst);
3131  } else {
3133  }
3134  return true;
3135 }
3136 
3137 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3138 {
3139  if (v->type == VEH_TRAIN) {
3140  StationID station_id = GetStationIndex(tile);
3141  if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3142  if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3143 
3144  int station_ahead;
3145  int station_length;
3146  int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3147 
3148  /* Stop whenever that amount of station ahead + the distance from the
3149  * begin of the platform to the stop location is longer than the length
3150  * of the platform. Station ahead 'includes' the current tile where the
3151  * vehicle is on, so we need to subtract that. */
3152  if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3153 
3155 
3156  x &= 0xF;
3157  y &= 0xF;
3158 
3159  if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3160  if (y == TILE_SIZE / 2) {
3161  if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3162  stop &= TILE_SIZE - 1;
3163 
3164  if (x == stop) {
3165  return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3166  } else if (x < stop) {
3168  uint16 spd = max(0, (stop - x) * 20 - 15);
3169  if (spd < v->cur_speed) v->cur_speed = spd;
3170  }
3171  }
3172  } else if (v->type == VEH_ROAD) {
3173  RoadVehicle *rv = RoadVehicle::From(v);
3174  if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3175  if (IsRoadStop(tile) && rv->IsFrontEngine()) {
3176  /* Attempt to allocate a parking bay in a road stop */
3178  }
3179  }
3180  }
3181 
3182  return VETSB_CONTINUE;
3183 }
3184 
3190 {
3191  /* Collect cargoes accepted since the last big tick. */
3192  uint cargoes = 0;
3193  for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3194  if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3195  }
3196 
3197  /* Anything to do? */
3198  if (cargoes == 0) return;
3199 
3200  /* Loop over all houses in the catchment. */
3201  Rect r = st->GetCatchmentRect();
3202  TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
3203  TILE_AREA_LOOP(tile, ta) {
3204  if (IsTileType(tile, MP_HOUSE)) {
3205  WatchedCargoCallback(tile, cargoes);
3206  }
3207  }
3208 }
3209 
3217 {
3218  if (!st->IsInUse()) {
3219  if (++st->delete_ctr >= 8) delete st;
3220  return false;
3221  }
3222 
3223  if (Station::IsExpected(st)) {
3225 
3226  for (CargoID i = 0; i < NUM_CARGO; i++) {
3227  ClrBit(Station::From(st)->goods[i].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3228  }
3229  }
3230 
3231 
3232  if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3233 
3234  return true;
3235 }
3236 
3237 static inline void byte_inc_sat(byte *p)
3238 {
3239  byte b = *p + 1;
3240  if (b != 0) *p = b;
3241 }
3242 
3249 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3250 {
3251  /* If truncating also punish the source stations' ratings to
3252  * decrease the flow of incoming cargo. */
3253 
3254  StationCargoAmountMap waiting_per_source;
3255  ge->cargo.Truncate(amount, &waiting_per_source);
3256  for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3257  Station *source_station = Station::GetIfValid(i->first);
3258  if (source_station == NULL) continue;
3259 
3260  GoodsEntry &source_ge = source_station->goods[cs->Index()];
3261  source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
3262  }
3263 }
3264 
3265 static void UpdateStationRating(Station *st)
3266 {
3267  bool waiting_changed = false;
3268 
3269  byte_inc_sat(&st->time_since_load);
3270  byte_inc_sat(&st->time_since_unload);
3271 
3272  const CargoSpec *cs;
3273  FOR_ALL_CARGOSPECS(cs) {
3274  GoodsEntry *ge = &st->goods[cs->Index()];
3275  /* Slowly increase the rating back to his original level in the case we
3276  * didn't deliver cargo yet to this station. This happens when a bribe
3277  * failed while you didn't moved that cargo yet to a station. */
3278  if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3279  ge->rating++;
3280  }
3281 
3282  /* Only change the rating if we are moving this cargo */
3283  if (ge->HasRating()) {
3284  byte_inc_sat(&ge->time_since_pickup);
3285  if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3287  ge->last_speed = 0;
3288  TruncateCargo(cs, ge);
3289  waiting_changed = true;
3290  continue;
3291  }
3292 
3293  bool skip = false;
3294  int rating = 0;
3295  uint waiting = ge->cargo.TotalCount();
3296 
3297  /* num_dests is at least 1 if there is any cargo as
3298  * INVALID_STATION is also a destination.
3299  */
3300  uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3301 
3302  /* Average amount of cargo per next hop, but prefer solitary stations
3303  * with only one or two next hops. They are allowed to have more
3304  * cargo waiting per next hop.
3305  * With manual cargo distribution waiting_avg = waiting / 2 as then
3306  * INVALID_STATION is the only destination.
3307  */
3308  uint waiting_avg = waiting / (num_dests + 1);
3309 
3311  /* Perform custom station rating. If it succeeds the speed, days in transit and
3312  * waiting cargo ratings must not be executed. */
3313 
3314  /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3315  uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3316 
3317  uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
3318  /* Convert to the 'old' vehicle types */
3319  uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3320  uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3321  if (callback != CALLBACK_FAILED) {
3322  skip = true;
3323  rating = GB(callback, 0, 14);
3324 
3325  /* Simulate a 15 bit signed value */
3326  if (HasBit(callback, 14)) rating -= 0x4000;
3327  }
3328  }
3329 
3330  if (!skip) {
3331  int b = ge->last_speed - 85;
3332  if (b >= 0) rating += b >> 2;
3333 
3334  byte waittime = ge->time_since_pickup;
3335  if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3336  (waittime > 21) ||
3337  (rating += 25, waittime > 12) ||
3338  (rating += 25, waittime > 6) ||
3339  (rating += 45, waittime > 3) ||
3340  (rating += 35, true);
3341 
3342  (rating -= 90, ge->max_waiting_cargo > 1500) ||
3343  (rating += 55, ge->max_waiting_cargo > 1000) ||
3344  (rating += 35, ge->max_waiting_cargo > 600) ||
3345  (rating += 10, ge->max_waiting_cargo > 300) ||
3346  (rating += 20, ge->max_waiting_cargo > 100) ||
3347  (rating += 10, true);
3348  }
3349 
3350  if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3351 
3352  byte age = ge->last_age;
3353  (age >= 3) ||
3354  (rating += 10, age >= 2) ||
3355  (rating += 10, age >= 1) ||
3356  (rating += 13, true);
3357 
3358  {
3359  int or_ = ge->rating; // old rating
3360 
3361  /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3362  ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
3363 
3364  /* if rating is <= 64 and more than 100 items waiting on average per destination,
3365  * remove some random amount of goods from the station */
3366  if (rating <= 64 && waiting_avg >= 100) {
3367  int dec = Random() & 0x1F;
3368  if (waiting_avg < 200) dec &= 7;
3369  waiting -= (dec + 1) * num_dests;
3370  waiting_changed = true;
3371  }
3372 
3373  /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3374  if (rating <= 127 && waiting != 0) {
3375  uint32 r = Random();
3376  if (rating <= (int)GB(r, 0, 7)) {
3377  /* Need to have int, otherwise it will just overflow etc. */
3378  waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3379  waiting_changed = true;
3380  }
3381  }
3382 
3383  /* At some point we really must cap the cargo. Previously this
3384  * was a strict 4095, but now we'll have a less strict, but
3385  * increasingly aggressive truncation of the amount of cargo. */
3386  static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3387  static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3388  static const uint MAX_WAITING_CARGO = 1 << 15;
3389 
3390  if (waiting > WAITING_CARGO_THRESHOLD) {
3391  uint difference = waiting - WAITING_CARGO_THRESHOLD;
3392  waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3393 
3394  waiting = min(waiting, MAX_WAITING_CARGO);
3395  waiting_changed = true;
3396  }
3397 
3398  /* We can't truncate cargo that's already reserved for loading.
3399  * Thus StoredCount() here. */
3400  if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3401  /* Feed back the exact own waiting cargo at this station for the
3402  * next rating calculation. */
3403  ge->max_waiting_cargo = 0;
3404 
3405  TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3406  } else {
3407  /* If the average number per next hop is low, be more forgiving. */
3408  ge->max_waiting_cargo = waiting_avg;
3409  }
3410  }
3411  }
3412  }
3413 
3414  StationID index = st->index;
3415  if (waiting_changed) {
3416  SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3417  } else {
3418  SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3419  }
3420 }
3421 
3430 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
3431 {
3432  GoodsEntry &ge = st->goods[c];
3433 
3434  /* Reroute cargo in station. */
3435  ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
3436 
3437  /* Reroute cargo staged to be transfered. */
3438  for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
3439  for (Vehicle *v = *it; v != NULL; v = v->Next()) {
3440  if (v->cargo_type != c) continue;
3441  v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
3442  }
3443  }
3444 }
3445 
3455 {
3456  for (CargoID c = 0; c < NUM_CARGO; ++c) {
3457  GoodsEntry &ge = from->goods[c];
3459  if (lg == NULL) continue;
3460  Node node = (*lg)[ge.node];
3461  for (EdgeIterator it(node.Begin()); it != node.End();) {
3462  Edge edge = it->second;
3463  Station *to = Station::Get((*lg)[it->first].Station());
3464  assert(to->goods[c].node == it->first);
3465  ++it; // Do that before removing the edge. Anything else may crash.
3466  assert(_date >= edge.LastUpdate());
3467  uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
3468  if ((uint)(_date - edge.LastUpdate()) > timeout) {
3469  /* Have all vehicles refresh their next hops before deciding to
3470  * remove the node. */
3471  bool updated = false;
3472  OrderList *l;
3473  FOR_ALL_ORDER_LISTS(l) {
3474  bool found_from = false;
3475  bool found_to = false;
3476  for (Order *order = l->GetFirstOrder(); order != NULL; order = order->next) {
3477  if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
3478  if (order->GetDestination() == from->index) {
3479  found_from = true;
3480  if (found_to) break;
3481  } else if (order->GetDestination() == to->index) {
3482  found_to = true;
3483  if (found_from) break;
3484  }
3485  }
3486  if (!found_to || !found_from) continue;
3487  for (Vehicle *v = l->GetFirstSharedVehicle(); !updated && v != NULL; v = v->NextShared()) {
3488  /* There is potential for optimization here:
3489  * - Usually consists of the same order list are the same. It's probably better to
3490  * first check the first of each list, then the second of each list and so on.
3491  * - We could try to figure out if we've seen a consist with the same cargo on the
3492  * same list already and if the consist can actually carry the cargo we're looking
3493  * for. With conditional and refit orders this is not quite trivial, though. */
3494  LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
3495  if (edge.LastUpdate() == _date) updated = true;
3496  }
3497  if (updated) break;
3498  }
3499  if (!updated) {
3500  /* If it's still considered dead remove it. */
3501  node.RemoveEdge(to->goods[c].node);
3502  ge.flows.DeleteFlows(to->index);
3503  RerouteCargo(from, c, to->index, from->index);
3504  }
3505  } else if (edge.LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastUnrestrictedUpdate()) > timeout) {
3506  edge.Restrict();
3507  ge.flows.RestrictFlows(to->index);
3508  RerouteCargo(from, c, to->index, from->index);
3509  } else if (edge.LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastRestrictedUpdate()) > timeout) {
3510  edge.Release();
3511  }
3512  }
3513  assert(_date >= lg->LastCompression());
3514  if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
3515  lg->Compress();
3516  }
3517  }
3518 }
3519 
3529 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, EdgeUpdateMode mode)
3530 {
3531  GoodsEntry &ge1 = st->goods[cargo];
3532  Station *st2 = Station::Get(next_station_id);
3533  GoodsEntry &ge2 = st2->goods[cargo];
3534  LinkGraph *lg = NULL;
3535  if (ge1.link_graph == INVALID_LINK_GRAPH) {
3536  if (ge2.link_graph == INVALID_LINK_GRAPH) {
3538  lg = new LinkGraph(cargo);
3540  ge2.link_graph = lg->index;
3541  ge2.node = lg->AddNode(st2);
3542  } else {
3543  DEBUG(misc, 0, "Can't allocate link graph");
3544  }
3545  } else {
3546  lg = LinkGraph::Get(ge2.link_graph);
3547  }
3548  if (lg) {
3549  ge1.link_graph = lg->index;
3550  ge1.node = lg->AddNode(st);
3551  }
3552  } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
3553  lg = LinkGraph::Get(ge1.link_graph);
3554  ge2.link_graph = lg->index;
3555  ge2.node = lg->AddNode(st2);
3556  } else {
3557  lg = LinkGraph::Get(ge1.link_graph);
3558  if (ge1.link_graph != ge2.link_graph) {
3559  LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
3560  if (lg->Size() < lg2->Size()) {
3562  lg2->Merge(lg); // Updates GoodsEntries of lg
3563  lg = lg2;
3564  } else {
3566  lg->Merge(lg2); // Updates GoodsEntries of lg2
3567  }
3568  }
3569  }
3570  if (lg != NULL) {
3571  (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, mode);
3572  }
3573 }
3574 
3581 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
3582 {
3583  for (const Vehicle *v = front; v != NULL; v = v->Next()) {
3584  if (v->refit_cap > 0) {
3585  /* The cargo count can indeed be higher than the refit_cap if
3586  * wagons have been auto-replaced and subsequently auto-
3587  * refitted to a higher capacity. The cargo gets redistributed
3588  * among the wagons in that case.
3589  * As usage is not such an important figure anyway we just
3590  * ignore the additional cargo then.*/
3591  IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
3593  }
3594  }
3595 }
3596 
3597 /* called for every station each tick */
3598 static void StationHandleSmallTick(BaseStation *st)
3599 {
3600  if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
3601 
3602  byte b = st->delete_ctr + 1;
3603  if (b >= STATION_RATING_TICKS) b = 0;
3604  st->delete_ctr = b;
3605 
3606  if (b == 0) UpdateStationRating(Station::From(st));
3607 }
3608 
3609 void OnTick_Station()
3610 {
3611  if (_game_mode == GM_EDITOR) return;
3612 
3613  BaseStation *st;
3614  FOR_ALL_BASE_STATIONS(st) {
3615  StationHandleSmallTick(st);
3616 
3617  /* Clean up the link graph about once a week. */
3618  if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
3620  };
3621 
3622  /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3623  * Station index is included so that triggers are not all done
3624  * at the same time. */
3625  if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
3626  /* Stop processing this station if it was deleted */
3627  if (!StationHandleBigTick(st)) continue;
3628  TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
3629  if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
3630  }
3631  }
3632 }
3633 
3636 {
3637  Station *st;
3638 
3639  FOR_ALL_STATIONS(st) {
3640  for (CargoID i = 0; i < NUM_CARGO; i++) {
3641  GoodsEntry *ge = &st->goods[i];
3644  }
3645  }
3646 }
3647 
3648 
3649 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
3650 {
3651  Station *st;
3652 
3653  FOR_ALL_STATIONS(st) {
3654  if (st->owner == owner &&
3655  DistanceManhattan(tile, st->xy) <= radius) {
3656  for (CargoID i = 0; i < NUM_CARGO; i++) {
3657  GoodsEntry *ge = &st->goods[i];
3658 
3659  if (ge->status != 0) {
3660  ge->rating = Clamp(ge->rating + amount, 0, 255);
3661  }
3662  }
3663  }
3664  }
3665 }
3666 
3667 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
3668 {
3669  /* We can't allocate a CargoPacket? Then don't do anything
3670  * at all; i.e. just discard the incoming cargo. */
3671  if (!CargoPacket::CanAllocateItem()) return 0;
3672 
3673  GoodsEntry &ge = st->goods[type];
3674  amount += ge.amount_fract;
3675  ge.amount_fract = GB(amount, 0, 8);
3676 
3677  amount >>= 8;
3678  /* No new "real" cargo item yet. */
3679  if (amount == 0) return 0;
3680 
3681  StationID next = ge.GetVia(st->index);
3682  ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
3683  LinkGraph *lg = NULL;
3684  if (ge.link_graph == INVALID_LINK_GRAPH) {
3686  lg = new LinkGraph(type);
3688  ge.link_graph = lg->index;
3689  ge.node = lg->AddNode(st);
3690  } else {
3691  DEBUG(misc, 0, "Can't allocate link graph");
3692  }
3693  } else {
3694  lg = LinkGraph::Get(ge.link_graph);
3695  }
3696  if (lg != NULL) (*lg)[ge.node].UpdateSupply(amount);
3697 
3698  if (!ge.HasRating()) {
3701  }
3702 
3704  TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
3705  AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
3706 
3708  st->MarkTilesDirty(true);
3709  return amount;
3710 }
3711 
3712 static bool IsUniqueStationName(const char *name)
3713 {
3714  const Station *st;
3715 
3716  FOR_ALL_STATIONS(st) {
3717  if (st->name != NULL && strcmp(st->name, name) == 0) return false;
3718  }
3719 
3720  return true;
3721 }
3722 
3732 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3733 {
3734  Station *st = Station::GetIfValid(p1);
3735  if (st == NULL) return CMD_ERROR;
3736 
3737  CommandCost ret = CheckOwnership(st->owner);
3738  if (ret.Failed()) return ret;
3739 
3740  bool reset = StrEmpty(text);
3741 
3742  if (!reset) {
3744  if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
3745  }
3746 
3747  if (flags & DC_EXEC) {
3748  free(st->name);
3749  st->name = reset ? NULL : stredup(text);
3750 
3751  st->UpdateVirtCoord();
3753  }
3754 
3755  return CommandCost();
3756 }
3757 
3764 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
3765 {
3766  /* area to search = producer plus station catchment radius */
3768 
3769  uint x = TileX(location.tile);
3770  uint y = TileY(location.tile);
3771 
3772  uint min_x = (x > max_rad) ? x - max_rad : 0;
3773  uint max_x = x + location.w + max_rad;
3774  uint min_y = (y > max_rad) ? y - max_rad : 0;
3775  uint max_y = y + location.h + max_rad;
3776 
3777  if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
3778  if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
3779  if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
3780  if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
3781 
3782  for (uint cy = min_y; cy < max_y; cy++) {
3783  for (uint cx = min_x; cx < max_x; cx++) {
3784  TileIndex cur_tile = TileXY(cx, cy);
3785  if (!IsTileType(cur_tile, MP_STATION)) continue;
3786 
3787  Station *st = Station::GetByTile(cur_tile);
3788  /* st can be NULL in case of waypoints */
3789  if (st == NULL) continue;
3790 
3792  int rad = st->GetCatchmentRadius();
3793  int rad_x = cx - x;
3794  int rad_y = cy - y;
3795 
3796  if (rad_x < -rad || rad_x >= rad + location.w) continue;
3797  if (rad_y < -rad || rad_y >= rad + location.h) continue;
3798  }
3799 
3800  /* Insert the station in the set. This will fail if it has
3801  * already been added.
3802  */
3803  stations->Include(st);
3804  }
3805  }
3806 }
3807 
3813 {
3814  if (this->tile != INVALID_TILE) {
3815  FindStationsAroundTiles(*this, &this->stations);
3816  this->tile = INVALID_TILE;
3817  }
3818  return &this->stations;
3819 }
3820 
3821 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
3822 {
3823  /* Return if nothing to do. Also the rounding below fails for 0. */
3824  if (amount == 0) return 0;
3825 
3826  Station *st1 = NULL; // Station with best rating
3827  Station *st2 = NULL; // Second best station
3828  uint best_rating1 = 0; // rating of st1
3829  uint best_rating2 = 0; // rating of st2
3830 
3831  for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
3832  Station *st = *st_iter;
3833 
3834  /* Is the station reserved exclusively for somebody else? */
3835  if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
3836 
3837  if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
3838 
3839  if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
3840 
3841  if (IsCargoInClass(type, CC_PASSENGERS)) {
3842  if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
3843  } else {
3844  if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
3845  }
3846 
3847  /* This station can be used, add it to st1/st2 */
3848  if (st1 == NULL || st->goods[type].rating >= best_rating1) {
3849  st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
3850  } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
3851  st2 = st; best_rating2 = st->goods[type].rating;
3852  }
3853  }
3854 
3855  /* no stations around at all? */
3856  if (st1 == NULL) return 0;
3857 
3858  /* From now we'll calculate with fractal cargo amounts.
3859  * First determine how much cargo we really have. */
3860  amount *= best_rating1 + 1;
3861 
3862  if (st2 == NULL) {
3863  /* only one station around */
3864  return UpdateStationWaiting(st1, type, amount, source_type, source_id);
3865  }
3866 
3867  /* several stations around, the best two (highest rating) are in st1 and st2 */
3868  assert(st1 != NULL);
3869  assert(st2 != NULL);
3870  assert(best_rating1 != 0 || best_rating2 != 0);
3871 
3872  /* Then determine the amount the worst station gets. We do it this way as the
3873  * best should get a bonus, which in this case is the rounding difference from
3874  * this calculation. In reality that will mean the bonus will be pretty low.
3875  * Nevertheless, the best station should always get the most cargo regardless
3876  * of rounding issues. */
3877  uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
3878  assert(worst_cargo <= (amount - worst_cargo));
3879 
3880  /* And then send the cargo to the stations! */
3881  uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
3882  /* These two UpdateStationWaiting's can't be in the statement as then the order
3883  * of execution would be undefined and that could cause desyncs with callbacks. */
3884  return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
3885 }
3886 
3887 void BuildOilRig(TileIndex tile)
3888 {
3889  if (!Station::CanAllocateItem()) {
3890  DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
3891  return;
3892  }
3893 
3894  Station *st = new Station(tile);
3895  st->town = ClosestTownFromTile(tile, UINT_MAX);
3896 
3897  st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
3898 
3899  assert(IsTileType(tile, MP_INDUSTRY));
3900  DeleteAnimatedTile(tile);
3901  MakeOilrig(tile, st->index, GetWaterClass(tile));
3902 
3903  st->owner = OWNER_NONE;
3904  st->airport.type = AT_OILRIG;
3905  st->airport.Add(tile);
3906  st->dock_tile = tile;
3908  st->build_date = _date;
3909 
3910  st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
3911 
3912  st->UpdateVirtCoord();
3913  UpdateStationAcceptance(st, false);
3915 }
3916 
3917 void DeleteOilRig(TileIndex tile)
3918 {
3919  Station *st = Station::GetByTile(tile);
3920 
3921  MakeWaterKeepingClass(tile, OWNER_NONE);
3922 
3923  st->dock_tile = INVALID_TILE;
3924  st->airport.Clear();
3925  st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
3926  st->airport.flags = 0;
3927 
3928  st->rect.AfterRemoveTile(st, tile);
3929 
3930  st->UpdateVirtCoord();
3932  if (!st->IsInUse()) delete st;
3933 }
3934 
3935 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
3936 {
3937  if (IsRoadStopTile(tile)) {
3938  for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
3939  /* Update all roadtypes, no matter if they are present */
3940  if (GetRoadOwner(tile, rt) == old_owner) {
3941  if (HasTileRoadType(tile, rt)) {
3942  /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
3943  Company::Get(old_owner)->infrastructure.road[rt] -= 2;
3944  if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
3945  }
3946  SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
3947  }
3948  }
3949  }
3950 
3951  if (!IsTileOwner(tile, old_owner)) return;
3952 
3953  if (new_owner != INVALID_OWNER) {
3954  /* Update company infrastructure counts. Only do it here
3955  * if the new owner is valid as otherwise the clear
3956  * command will do it for us. No need to dirty windows
3957  * here, we'll redraw the whole screen anyway.*/
3958  Company *old_company = Company::Get(old_owner);
3959  Company *new_company = Company::Get(new_owner);
3960 
3961  /* Update counts for underlying infrastructure. */
3962  switch (GetStationType(tile)) {
3963  case STATION_RAIL:
3964  case STATION_WAYPOINT:
3965  if (!IsStationTileBlocked(tile)) {
3966  old_company->infrastructure.rail[GetRailType(tile)]--;
3967  new_company->infrastructure.rail[GetRailType(tile)]++;
3968  }
3969  break;
3970 
3971  case STATION_BUS:
3972  case STATION_TRUCK:
3973  /* Road stops were already handled above. */
3974  break;
3975 
3976  case STATION_BUOY:
3977  case STATION_DOCK:
3978  if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
3979  old_company->infrastructure.water--;
3980  new_company->infrastructure.water++;
3981  }
3982  break;
3983 
3984  default:
3985  break;
3986  }
3987 
3988  /* Update station tile count. */
3989  if (!IsBuoy(tile) && !IsAirport(tile)) {
3990  old_company->infrastructure.station--;
3991  new_company->infrastructure.station++;
3992  }
3993 
3994  /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
3995  SetTileOwner(tile, new_owner);
3997  } else {
3998  if (IsDriveThroughStopTile(tile)) {
3999  /* Remove the drive-through road stop */
4000  DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
4001  assert(IsTileType(tile, MP_ROAD));
4002  /* Change owner of tile and all roadtypes */
4003  ChangeTileOwner(tile, old_owner, new_owner);
4004  } else {
4006  /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4007  * Update owner of buoy if it was not removed (was in orders).
4008  * Do not update when owned by OWNER_WATER (sea and rivers). */
4009  if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4010  }
4011  }
4012 }
4013 
4023 {
4024  /* Yeah... water can always remove stops, right? */
4025  if (_current_company == OWNER_WATER) return true;
4026 
4027  RoadTypes rts = GetRoadTypes(tile);
4028  if (HasBit(rts, ROADTYPE_TRAM)) {
4029  Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
4030  if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
4031  }
4032  if (HasBit(rts, ROADTYPE_ROAD)) {
4033  Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
4034  if (road_owner != OWNER_TOWN) {
4035  if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
4036  } else {
4037  if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
4038  }
4039  }
4040 
4041  return true;
4042 }
4043 
4051 {
4052  if (flags & DC_AUTO) {
4053  switch (GetStationType(tile)) {
4054  default: break;
4055  case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4056  case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4057  case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4058  case STATION_TRUCK: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4059  case STATION_BUS: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4060  case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4061  case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4062  case STATION_OILRIG:
4063  SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4064  return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4065  }
4066  }
4067 
4068  switch (GetStationType(tile)) {
4069  case STATION_RAIL: return RemoveRailStation(tile, flags);
4070  case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4071  case STATION_AIRPORT: return RemoveAirport(tile, flags);
4072  case STATION_TRUCK:
4073  if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4074  return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4075  }
4076  return RemoveRoadStop(tile, flags);
4077  case STATION_BUS:
4078  if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4079  return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4080  }
4081  return RemoveRoadStop(tile, flags);
4082  case STATION_BUOY: return RemoveBuoy(tile, flags);
4083  case STATION_DOCK: return RemoveDock(tile, flags);
4084  default: break;
4085  }
4086 
4087  return CMD_ERROR;
4088 }
4089 
4090 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4091 {
4093  /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4094  * TTDP does not call it.
4095  */
4096  if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4097  switch (GetStationType(tile)) {
4098  case STATION_WAYPOINT:
4099  case STATION_RAIL: {
4100  DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4101  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4102  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4103  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4104  }
4105 
4106  case STATION_AIRPORT:
4107  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4108 
4109  case STATION_TRUCK:
4110  case STATION_BUS: {
4111  DiagDirection direction = GetRoadStopDir(tile);
4112  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4113  if (IsDriveThroughStopTile(tile)) {
4114  if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4115  }
4116  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4117  }
4118 
4119  default: break;
4120  }
4121  }
4122  }
4123  return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
4124 }
4125 
4131 uint FlowStat::GetShare(StationID st) const
4132 {
4133  uint32 prev = 0;
4134  for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
4135  if (it->second == st) {
4136  return it->first - prev;
4137  } else {
4138  prev = it->first;
4139  }
4140  }
4141  return 0;
4142 }
4143 
4150 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4151 {
4152  if (this->unrestricted == 0) return INVALID_STATION;
4153  assert(!this->shares.empty());
4154  SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4155  assert(it != this->shares.end() && it->first <= this->unrestricted);
4156  if (it->second != excluded && it->second != excluded2) return it->second;
4157 
4158  /* We've hit one of the excluded stations.
4159  * Draw another share, from outside its range. */
4160 
4161  uint end = it->first;
4162  uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4163  uint interval = end - begin;
4164  if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4165  uint new_max = this->unrestricted - interval;
4166  uint rand = RandomRange(new_max);
4167  SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4168  this->shares.upper_bound(rand + interval);
4169  assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4170  if (it2->second != excluded && it2->second != excluded2) return it2->second;
4171 
4172  /* We've hit the second excluded station.
4173  * Same as before, only a bit more complicated. */
4174 
4175  uint end2 = it2->first;
4176  uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4177  uint interval2 = end2 - begin2;
4178  if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4179  new_max -= interval2;
4180  if (begin > begin2) {
4181  Swap(begin, begin2);
4182  Swap(end, end2);
4183  Swap(interval, interval2);
4184  }
4185  rand = RandomRange(new_max);
4186  SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4187  if (rand < begin) {
4188  it3 = this->shares.upper_bound(rand);
4189  } else if (rand < begin2 - interval) {
4190  it3 = this->shares.upper_bound(rand + interval);
4191  } else {
4192  it3 = this->shares.upper_bound(rand + interval + interval2);
4193  }
4194  assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4195  return it3->second;
4196 }
4197 
4204 {
4205  assert(!this->shares.empty());
4206  SharesMap new_shares;
4207  uint i = 0;
4208  for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4209  new_shares[++i] = it->second;
4210  if (it->first == this->unrestricted) this->unrestricted = i;
4211  }
4212  this->shares.swap(new_shares);
4213  assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4214 }
4215 
4222 void FlowStat::ChangeShare(StationID st, int flow)
4223 {
4224  /* We assert only before changing as afterwards the shares can actually
4225  * be empty. In that case the whole flow stat must be deleted then. */
4226  assert(!this->shares.empty());
4227 
4228  uint removed_shares = 0;
4229  uint added_shares = 0;
4230  uint last_share = 0;
4231  SharesMap new_shares;
4232  for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4233  if (it->second == st) {
4234  if (flow < 0) {
4235  uint share = it->first - last_share;
4236  if (flow == INT_MIN || (uint)(-flow) >= share) {
4237  removed_shares += share;
4238  if (it->first <= this->unrestricted) this->unrestricted -= share;
4239  if (flow != INT_MIN) flow += share;
4240  last_share = it->first;
4241  continue; // remove the whole share
4242  }
4243  removed_shares += (uint)(-flow);
4244  } else {
4245  added_shares += (uint)(flow);
4246  }
4247  if (it->first <= this->unrestricted) this->unrestricted += flow;
4248 
4249  /* If we don't continue above the whole flow has been added or
4250  * removed. */
4251  flow = 0;
4252  }
4253  new_shares[it->first + added_shares - removed_shares] = it->second;
4254  last_share = it->first;
4255  }
4256  if (flow > 0) {
4257  new_shares[last_share + (uint)flow] = st;
4258  if (this->unrestricted < last_share) {
4259  this->ReleaseShare(st);
4260  } else {
4261  this->unrestricted += flow;
4262  }
4263  }
4264  this->shares.swap(new_shares);
4265 }
4266 
4272 void FlowStat::RestrictShare(StationID st)
4273 {
4274  assert(!this->shares.empty());
4275  uint flow = 0;
4276  uint last_share = 0;
4277  SharesMap new_shares;
4278  for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4279  if (flow == 0) {
4280  if (it->first > this->unrestricted) return; // Not present or already restricted.
4281  if (it->second == st) {
4282  flow = it->first - last_share;
4283  this->unrestricted -= flow;
4284  } else {
4285  new_shares[it->first] = it->second;
4286  }
4287  } else {
4288  new_shares[it->first - flow] = it->second;
4289  }
4290  last_share = it->first;
4291  }
4292  if (flow == 0) return;
4293  new_shares[last_share + flow] = st;
4294  this->shares.swap(new_shares);
4295  assert(!this->shares.empty());
4296 }
4297 
4303 void FlowStat::ReleaseShare(StationID st)
4304 {
4305  assert(!this->shares.empty());
4306  uint flow = 0;
4307  uint next_share = 0;
4308  bool found = false;
4309  for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4310  if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4311  if (found) {
4312  flow = next_share - it->first;
4313  this->unrestricted += flow;
4314  break;
4315  } else {
4316  if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4317  if (it->second == st) found = true;
4318  }
4319  next_share = it->first;
4320  }
4321  if (flow == 0) return;
4322  SharesMap new_shares;
4323  new_shares[flow] = st;
4324  for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4325  if (it->second != st) {
4326  new_shares[flow + it->first] = it->second;
4327  } else {
4328  flow = 0;
4329  }
4330  }
4331  this->shares.swap(new_shares);
4332  assert(!this->shares.empty());
4333 }
4334 
4340 void FlowStat::ScaleToMonthly(uint runtime)
4341 {
4342  assert(runtime > 0);
4343  SharesMap new_shares;
4344  uint share = 0;
4345  for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
4346  share = max(share + 1, i->first * 30 / runtime);
4347  new_shares[share] = i->second;
4348  if (this->unrestricted == i->first) this->unrestricted = share;
4349  }
4350  this->shares.swap(new_shares);
4351 }
4352 
4359 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
4360 {
4361  FlowStatMap::iterator origin_it = this->find(origin);
4362  if (origin_it == this->end()) {
4363  this->insert(std::make_pair(origin, FlowStat(via, flow)));
4364  } else {
4365  origin_it->second.ChangeShare(via, flow);
4366  assert(!origin_it->second.GetShares()->empty());
4367  }
4368 }
4369 
4378 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
4379 {
4380  FlowStatMap::iterator prev_it = this->find(origin);
4381  if (prev_it == this->end()) {
4382  FlowStat fs(via, flow);
4383  fs.AppendShare(INVALID_STATION, flow);
4384  this->insert(std::make_pair(origin, fs));
4385  } else {
4386  prev_it->second.ChangeShare(via, flow);
4387  prev_it->second.ChangeShare(INVALID_STATION, flow);
4388  assert(!prev_it->second.GetShares()->empty());
4389  }
4390 }
4391 
4397 {
4398  for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
4399  FlowStat &fs = i->second;
4400  uint local = fs.GetShare(INVALID_STATION);
4401  if (local > INT_MAX) { // make sure it fits in an int
4402  fs.ChangeShare(self, -INT_MAX);
4403  fs.ChangeShare(INVALID_STATION, -INT_MAX);
4404  local -= INT_MAX;
4405  }
4406  fs.ChangeShare(self, -(int)local);
4407  fs.ChangeShare(INVALID_STATION, -(int)local);
4408 
4409  /* If the local share is used up there must be a share for some
4410  * remote station. */
4411  assert(!fs.GetShares()->empty());
4412  }
4413 }
4414 
4422 {
4423  StationIDStack ret;
4424  for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
4425  FlowStat &s_flows = f_it->second;
4426  s_flows.ChangeShare(via, INT_MIN);
4427  if (s_flows.GetShares()->empty()) {
4428  ret.Push(f_it->first);
4429  this->erase(f_it++);
4430  } else {
4431  ++f_it;
4432  }
4433  }
4434  return ret;
4435 }
4436 
4441 void FlowStatMap::RestrictFlows(StationID via)
4442 {
4443  for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4444  it->second.RestrictShare(via);
4445  }
4446 }
4447 
4452 void FlowStatMap::ReleaseFlows(StationID via)
4453 {
4454  for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4455  it->second.ReleaseShare(via);
4456  }
4457 }
4458 
4464 {
4465  uint ret = 0;
4466  for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4467  ret += (--(i->second.GetShares()->end()))->first;
4468  }
4469  return ret;
4470 }
4471 
4477 uint FlowStatMap::GetFlowVia(StationID via) const
4478 {
4479  uint ret = 0;
4480  for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4481  ret += i->second.GetShare(via);
4482  }
4483  return ret;
4484 }
4485 
4491 uint FlowStatMap::GetFlowFrom(StationID from) const
4492 {
4493  FlowStatMap::const_iterator i = this->find(from);
4494  if (i == this->end()) return 0;
4495  return (--(i->second.GetShares()->end()))->first;
4496 }
4497 
4504 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
4505 {
4506  FlowStatMap::const_iterator i = this->find(from);
4507  if (i == this->end()) return 0;
4508  return i->second.GetShare(via);
4509 }
4510 
4511 extern const TileTypeProcs _tile_type_station_procs = {
4512  DrawTile_Station, // draw_tile_proc
4513  GetSlopePixelZ_Station, // get_slope_z_proc
4514  ClearTile_Station, // clear_tile_proc
4515  NULL, // add_accepted_cargo_proc
4516  GetTileDesc_Station, // get_tile_desc_proc
4517  GetTileTrackStatus_Station, // get_tile_track_status_proc
4518  ClickTile_Station, // click_tile_proc
4519  AnimateTile_Station, // animate_tile_proc
4520  TileLoop_Station, // tile_loop_proc
4521  ChangeTileOwner_Station, // change_tile_owner_proc
4522  NULL, // add_produced_cargo_proc
4523  VehicleEnter_Station, // vehicle_enter_tile_proc
4524  GetFoundation_Station, // get_foundation_proc
4525  TerraformTile_Station, // terraform_tile_proc
4526 };