station_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: station_cmd.cpp 24425 2012-07-20 19:49:02Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "aircraft.h"
00014 #include "bridge_map.h"
00015 #include "cmd_helper.h"
00016 #include "viewport_func.h"
00017 #include "command_func.h"
00018 #include "town.h"
00019 #include "news_func.h"
00020 #include "train.h"
00021 #include "ship.h"
00022 #include "roadveh.h"
00023 #include "industry.h"
00024 #include "newgrf_cargo.h"
00025 #include "newgrf_debug.h"
00026 #include "newgrf_station.h"
00027 #include "newgrf_canal.h" /* For the buoy */
00028 #include "pathfinder/yapf/yapf_cache.h"
00029 #include "road_internal.h" /* For drawing catenary/checking road removal */
00030 #include "autoslope.h"
00031 #include "water.h"
00032 #include "strings_func.h"
00033 #include "clear_func.h"
00034 #include "date_func.h"
00035 #include "vehicle_func.h"
00036 #include "string_func.h"
00037 #include "animated_tile_func.h"
00038 #include "elrail_func.h"
00039 #include "station_base.h"
00040 #include "roadstop_base.h"
00041 #include "newgrf_railtype.h"
00042 #include "waypoint_base.h"
00043 #include "waypoint_func.h"
00044 #include "pbs.h"
00045 #include "debug.h"
00046 #include "core/random_func.hpp"
00047 #include "company_base.h"
00048 #include "table/airporttile_ids.h"
00049 #include "newgrf_airporttiles.h"
00050 #include "order_backup.h"
00051 #include "newgrf_house.h"
00052 #include "company_gui.h"
00053 #include "widgets/station_widget.h"
00054 
00055 #include "table/strings.h"
00056 
00063 bool IsHangar(TileIndex t)
00064 {
00065   assert(IsTileType(t, MP_STATION));
00066 
00067   /* If the tile isn't an airport there's no chance it's a hangar. */
00068   if (!IsAirport(t)) return false;
00069 
00070   const Station *st = Station::GetByTile(t);
00071   const AirportSpec *as = st->airport.GetSpec();
00072 
00073   for (uint i = 0; i < as->nof_depots; i++) {
00074     if (st->airport.GetHangarTile(i) == t) return true;
00075   }
00076 
00077   return false;
00078 }
00079 
00087 template <class T>
00088 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
00089 {
00090   ta.tile -= TileDiffXY(1, 1);
00091   ta.w    += 2;
00092   ta.h    += 2;
00093 
00094   /* check around to see if there's any stations there */
00095   TILE_AREA_LOOP(tile_cur, ta) {
00096     if (IsTileType(tile_cur, MP_STATION)) {
00097       StationID t = GetStationIndex(tile_cur);
00098       if (!T::IsValidID(t)) continue;
00099 
00100       if (closest_station == INVALID_STATION) {
00101         closest_station = t;
00102       } else if (closest_station != t) {
00103         return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00104       }
00105     }
00106   }
00107   *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
00108   return CommandCost();
00109 }
00110 
00116 typedef bool (*CMSAMatcher)(TileIndex tile);
00117 
00124 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
00125 {
00126   int num = 0;
00127 
00128   for (int dx = -3; dx <= 3; dx++) {
00129     for (int dy = -3; dy <= 3; dy++) {
00130       TileIndex t = TileAddWrap(tile, dx, dy);
00131       if (t != INVALID_TILE && cmp(t)) num++;
00132     }
00133   }
00134 
00135   return num;
00136 }
00137 
00143 static bool CMSAMine(TileIndex tile)
00144 {
00145   /* No industry */
00146   if (!IsTileType(tile, MP_INDUSTRY)) return false;
00147 
00148   const Industry *ind = Industry::GetByTile(tile);
00149 
00150   /* No extractive industry */
00151   if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
00152 
00153   for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00154     /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
00155      * Also the production of passengers and mail is ignored. */
00156     if (ind->produced_cargo[i] != CT_INVALID &&
00157         (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
00158       return true;
00159     }
00160   }
00161 
00162   return false;
00163 }
00164 
00170 static bool CMSAWater(TileIndex tile)
00171 {
00172   return IsTileType(tile, MP_WATER) && IsWater(tile);
00173 }
00174 
00180 static bool CMSATree(TileIndex tile)
00181 {
00182   return IsTileType(tile, MP_TREES);
00183 }
00184 
00185 #define M(x) ((x) - STR_SV_STNAME)
00186 
00187 enum StationNaming {
00188   STATIONNAMING_RAIL,
00189   STATIONNAMING_ROAD,
00190   STATIONNAMING_AIRPORT,
00191   STATIONNAMING_OILRIG,
00192   STATIONNAMING_DOCK,
00193   STATIONNAMING_HELIPORT,
00194 };
00195 
00197 struct StationNameInformation {
00198   uint32 free_names; 
00199   bool *indtypes;    
00200 };
00201 
00210 static bool FindNearIndustryName(TileIndex tile, void *user_data)
00211 {
00212   /* All already found industry types */
00213   StationNameInformation *sni = (StationNameInformation*)user_data;
00214   if (!IsTileType(tile, MP_INDUSTRY)) return false;
00215 
00216   /* If the station name is undefined it means that it doesn't name a station */
00217   IndustryType indtype = GetIndustryType(tile);
00218   if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
00219 
00220   /* In all cases if an industry that provides a name is found two of
00221    * the standard names will be disabled. */
00222   sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
00223   return !sni->indtypes[indtype];
00224 }
00225 
00226 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
00227 {
00228   static const uint32 _gen_station_name_bits[] = {
00229     0,                                       // STATIONNAMING_RAIL
00230     0,                                       // STATIONNAMING_ROAD
00231     1U << M(STR_SV_STNAME_AIRPORT),          // STATIONNAMING_AIRPORT
00232     1U << M(STR_SV_STNAME_OILFIELD),         // STATIONNAMING_OILRIG
00233     1U << M(STR_SV_STNAME_DOCKS),            // STATIONNAMING_DOCK
00234     1U << M(STR_SV_STNAME_HELIPORT),         // STATIONNAMING_HELIPORT
00235   };
00236 
00237   const Town *t = st->town;
00238   uint32 free_names = UINT32_MAX;
00239 
00240   bool indtypes[NUM_INDUSTRYTYPES];
00241   memset(indtypes, 0, sizeof(indtypes));
00242 
00243   const Station *s;
00244   FOR_ALL_STATIONS(s) {
00245     if (s != st && s->town == t) {
00246       if (s->indtype != IT_INVALID) {
00247         indtypes[s->indtype] = true;
00248         continue;
00249       }
00250       uint str = M(s->string_id);
00251       if (str <= 0x20) {
00252         if (str == M(STR_SV_STNAME_FOREST)) {
00253           str = M(STR_SV_STNAME_WOODS);
00254         }
00255         ClrBit(free_names, str);
00256       }
00257     }
00258   }
00259 
00260   TileIndex indtile = tile;
00261   StationNameInformation sni = { free_names, indtypes };
00262   if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
00263     /* An industry has been found nearby */
00264     IndustryType indtype = GetIndustryType(indtile);
00265     const IndustrySpec *indsp = GetIndustrySpec(indtype);
00266     /* STR_NULL means it only disables oil rig/mines */
00267     if (indsp->station_name != STR_NULL) {
00268       st->indtype = indtype;
00269       return STR_SV_STNAME_FALLBACK;
00270     }
00271   }
00272 
00273   /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
00274   free_names = sni.free_names;
00275 
00276   /* check default names */
00277   uint32 tmp = free_names & _gen_station_name_bits[name_class];
00278   if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
00279 
00280   /* check mine? */
00281   if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
00282     if (CountMapSquareAround(tile, CMSAMine) >= 2) {
00283       return STR_SV_STNAME_MINES;
00284     }
00285   }
00286 
00287   /* check close enough to town to get central as name? */
00288   if (DistanceMax(tile, t->xy) < 8) {
00289     if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
00290 
00291     if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
00292   }
00293 
00294   /* Check lakeside */
00295   if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
00296       DistanceFromEdge(tile) < 20 &&
00297       CountMapSquareAround(tile, CMSAWater) >= 5) {
00298     return STR_SV_STNAME_LAKESIDE;
00299   }
00300 
00301   /* Check woods */
00302   if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
00303         CountMapSquareAround(tile, CMSATree) >= 8 ||
00304         CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
00305       ) {
00306     return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
00307   }
00308 
00309   /* check elevation compared to town */
00310   int z = GetTileZ(tile);
00311   int z2 = GetTileZ(t->xy);
00312   if (z < z2) {
00313     if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
00314   } else if (z > z2) {
00315     if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
00316   }
00317 
00318   /* check direction compared to town */
00319   static const int8 _direction_and_table[] = {
00320     ~( (1 << M(STR_SV_STNAME_WEST))  | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00321     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00322     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00323     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
00324   };
00325 
00326   free_names &= _direction_and_table[
00327     (TileX(tile) < TileX(t->xy)) +
00328     (TileY(tile) < TileY(t->xy)) * 2];
00329 
00330   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));
00331   return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
00332 }
00333 #undef M
00334 
00340 static Station *GetClosestDeletedStation(TileIndex tile)
00341 {
00342   uint threshold = 8;
00343   Station *best_station = NULL;
00344   Station *st;
00345 
00346   FOR_ALL_STATIONS(st) {
00347     if (!st->IsInUse() && st->owner == _current_company) {
00348       uint cur_dist = DistanceManhattan(tile, st->xy);
00349 
00350       if (cur_dist < threshold) {
00351         threshold = cur_dist;
00352         best_station = st;
00353       }
00354     }
00355   }
00356 
00357   return best_station;
00358 }
00359 
00360 
00361 void Station::GetTileArea(TileArea *ta, StationType type) const
00362 {
00363   switch (type) {
00364     case STATION_RAIL:
00365       *ta = this->train_station;
00366       return;
00367 
00368     case STATION_AIRPORT:
00369       *ta = this->airport;
00370       return;
00371 
00372     case STATION_TRUCK:
00373       *ta = this->truck_station;
00374       return;
00375 
00376     case STATION_BUS:
00377       *ta = this->bus_station;
00378       return;
00379 
00380     case STATION_DOCK:
00381     case STATION_OILRIG:
00382       ta->tile = this->dock_tile;
00383       break;
00384 
00385     default: NOT_REACHED();
00386   }
00387 
00388   ta->w = 1;
00389   ta->h = 1;
00390 }
00391 
00395 void Station::UpdateVirtCoord()
00396 {
00397   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00398 
00399   pt.y -= 32 * ZOOM_LVL_BASE;
00400   if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
00401 
00402   SetDParam(0, this->index);
00403   SetDParam(1, this->facilities);
00404   this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
00405 
00406   SetWindowDirty(WC_STATION_VIEW, this->index);
00407 }
00408 
00410 void UpdateAllStationVirtCoords()
00411 {
00412   BaseStation *st;
00413 
00414   FOR_ALL_BASE_STATIONS(st) {
00415     st->UpdateVirtCoord();
00416   }
00417 }
00418 
00424 static uint GetAcceptanceMask(const Station *st)
00425 {
00426   uint mask = 0;
00427 
00428   for (CargoID i = 0; i < NUM_CARGO; i++) {
00429     if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) mask |= 1 << i;
00430   }
00431   return mask;
00432 }
00433 
00438 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
00439 {
00440   for (uint i = 0; i < num_items; i++) {
00441     SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
00442   }
00443 
00444   SetDParam(0, st->index);
00445   AddNewsItem(msg, NS_ACCEPTANCE, NR_STATION, st->index);
00446 }
00447 
00455 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
00456 {
00457   CargoArray produced;
00458 
00459   int x = TileX(tile);
00460   int y = TileY(tile);
00461 
00462   /* expand the region by rad tiles on each side
00463    * while making sure that we remain inside the board. */
00464   int x2 = min(x + w + rad, MapSizeX());
00465   int x1 = max(x - rad, 0);
00466 
00467   int y2 = min(y + h + rad, MapSizeY());
00468   int y1 = max(y - rad, 0);
00469 
00470   assert(x1 < x2);
00471   assert(y1 < y2);
00472   assert(w > 0);
00473   assert(h > 0);
00474 
00475   TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
00476 
00477   /* Loop over all tiles to get the produced cargo of
00478    * everything except industries */
00479   TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
00480 
00481   /* Loop over the industries. They produce cargo for
00482    * anything that is within 'rad' from their bounding
00483    * box. As such if you have e.g. a oil well the tile
00484    * area loop might not hit an industry tile while
00485    * the industry would produce cargo for the station.
00486    */
00487   const Industry *i;
00488   FOR_ALL_INDUSTRIES(i) {
00489     if (!ta.Intersects(i->location)) continue;
00490 
00491     for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00492       CargoID cargo = i->produced_cargo[j];
00493       if (cargo != CT_INVALID) produced[cargo]++;
00494     }
00495   }
00496 
00497   return produced;
00498 }
00499 
00508 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
00509 {
00510   CargoArray acceptance;
00511   if (always_accepted != NULL) *always_accepted = 0;
00512 
00513   int x = TileX(tile);
00514   int y = TileY(tile);
00515 
00516   /* expand the region by rad tiles on each side
00517    * while making sure that we remain inside the board. */
00518   int x2 = min(x + w + rad, MapSizeX());
00519   int y2 = min(y + h + rad, MapSizeY());
00520   int x1 = max(x - rad, 0);
00521   int y1 = max(y - rad, 0);
00522 
00523   assert(x1 < x2);
00524   assert(y1 < y2);
00525   assert(w > 0);
00526   assert(h > 0);
00527 
00528   for (int yc = y1; yc != y2; yc++) {
00529     for (int xc = x1; xc != x2; xc++) {
00530       TileIndex tile = TileXY(xc, yc);
00531       AddAcceptedCargo(tile, acceptance, always_accepted);
00532     }
00533   }
00534 
00535   return acceptance;
00536 }
00537 
00543 void UpdateStationAcceptance(Station *st, bool show_msg)
00544 {
00545   /* old accepted goods types */
00546   uint old_acc = GetAcceptanceMask(st);
00547 
00548   /* And retrieve the acceptance. */
00549   CargoArray acceptance;
00550   if (!st->rect.IsEmpty()) {
00551     acceptance = GetAcceptanceAroundTiles(
00552       TileXY(st->rect.left, st->rect.top),
00553       st->rect.right  - st->rect.left + 1,
00554       st->rect.bottom - st->rect.top  + 1,
00555       st->GetCatchmentRadius(),
00556       &st->always_accepted
00557     );
00558   }
00559 
00560   /* Adjust in case our station only accepts fewer kinds of goods */
00561   for (CargoID i = 0; i < NUM_CARGO; i++) {
00562     uint amt = min(acceptance[i], 15);
00563 
00564     /* Make sure the station can accept the goods type. */
00565     bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
00566     if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
00567         (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
00568       amt = 0;
00569     }
00570 
00571     SB(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
00572   }
00573 
00574   /* Only show a message in case the acceptance was actually changed. */
00575   uint new_acc = GetAcceptanceMask(st);
00576   if (old_acc == new_acc) return;
00577 
00578   /* show a message to report that the acceptance was changed? */
00579   if (show_msg && st->owner == _local_company && st->IsInUse()) {
00580     /* List of accept and reject strings for different number of
00581      * cargo types */
00582     static const StringID accept_msg[] = {
00583       STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
00584       STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
00585     };
00586     static const StringID reject_msg[] = {
00587       STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
00588       STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
00589     };
00590 
00591     /* Array of accepted and rejected cargo types */
00592     CargoID accepts[2] = { CT_INVALID, CT_INVALID };
00593     CargoID rejects[2] = { CT_INVALID, CT_INVALID };
00594     uint num_acc = 0;
00595     uint num_rej = 0;
00596 
00597     /* Test each cargo type to see if its acceptange has changed */
00598     for (CargoID i = 0; i < NUM_CARGO; i++) {
00599       if (HasBit(new_acc, i)) {
00600         if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
00601           /* New cargo is accepted */
00602           accepts[num_acc++] = i;
00603         }
00604       } else {
00605         if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
00606           /* Old cargo is no longer accepted */
00607           rejects[num_rej++] = i;
00608         }
00609       }
00610     }
00611 
00612     /* Show news message if there are any changes */
00613     if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
00614     if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
00615   }
00616 
00617   /* redraw the station view since acceptance changed */
00618   SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
00619 }
00620 
00621 static void UpdateStationSignCoord(BaseStation *st)
00622 {
00623   const StationRect *r = &st->rect;
00624 
00625   if (r->IsEmpty()) return; // no tiles belong to this station
00626 
00627   /* clamp sign coord to be inside the station rect */
00628   st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
00629   st->UpdateVirtCoord();
00630 }
00631 
00638 static void DeleteStationIfEmpty(BaseStation *st)
00639 {
00640   if (!st->IsInUse()) {
00641     st->delete_ctr = 0;
00642     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00643   }
00644   /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
00645   UpdateStationSignCoord(st);
00646 }
00647 
00648 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00649 
00659 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
00660 {
00661   if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00662     return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00663   }
00664 
00665   CommandCost ret = EnsureNoVehicleOnGround(tile);
00666   if (ret.Failed()) return ret;
00667 
00668   int z;
00669   Slope tileh = GetTileSlope(tile, &z);
00670 
00671   /* Prohibit building if
00672    *   1) The tile is "steep" (i.e. stretches two height levels).
00673    *   2) The tile is non-flat and the build_on_slopes switch is disabled.
00674    */
00675   if ((!allow_steep && IsSteepSlope(tileh)) ||
00676       ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00677     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00678   }
00679 
00680   CommandCost cost(EXPENSES_CONSTRUCTION);
00681   int flat_z = z + GetSlopeMaxZ(tileh);
00682   if (tileh != SLOPE_FLAT) {
00683     /* Forbid building if the tile faces a slope in a invalid direction. */
00684     for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
00685       if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
00686         return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00687       }
00688     }
00689     cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00690   }
00691 
00692   /* The level of this tile must be equal to allowed_z. */
00693   if (allowed_z < 0) {
00694     /* First tile. */
00695     allowed_z = flat_z;
00696   } else if (allowed_z != flat_z) {
00697     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00698   }
00699 
00700   return cost;
00701 }
00702 
00709 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
00710 {
00711   CommandCost cost(EXPENSES_CONSTRUCTION);
00712   int allowed_z = -1;
00713 
00714   TILE_AREA_LOOP(tile_cur, tile_area) {
00715     CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
00716     if (ret.Failed()) return ret;
00717     cost.AddCost(ret);
00718 
00719     ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00720     if (ret.Failed()) return ret;
00721     cost.AddCost(ret);
00722   }
00723 
00724   return cost;
00725 }
00726 
00741 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)
00742 {
00743   CommandCost cost(EXPENSES_CONSTRUCTION);
00744   int allowed_z = -1;
00745   uint invalid_dirs = 5 << axis;
00746 
00747   const StationSpec *statspec = StationClass::Get(spec_class, spec_index);
00748   bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
00749 
00750   TILE_AREA_LOOP(tile_cur, tile_area) {
00751     CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
00752     if (ret.Failed()) return ret;
00753     cost.AddCost(ret);
00754 
00755     if (slope_cb) {
00756       /* Do slope check if requested. */
00757       ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
00758       if (ret.Failed()) return ret;
00759     }
00760 
00761     /* if station is set, then we have special handling to allow building on top of already existing stations.
00762      * so station points to INVALID_STATION if we can build on any station.
00763      * Or it points to a station if we're only allowed to build on exactly that station. */
00764     if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00765       if (!IsRailStation(tile_cur)) {
00766         return ClearTile_Station(tile_cur, DC_AUTO); // get error message
00767       } else {
00768         StationID st = GetStationIndex(tile_cur);
00769         if (*station == INVALID_STATION) {
00770           *station = st;
00771         } else if (*station != st) {
00772           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00773         }
00774       }
00775     } else {
00776       /* Rail type is only valid when building a railway station; if station to
00777        * build isn't a rail station it's INVALID_RAILTYPE. */
00778       if (rt != INVALID_RAILTYPE &&
00779           IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00780           HasPowerOnRail(GetRailType(tile_cur), rt)) {
00781         /* Allow overbuilding if the tile:
00782          *  - has rail, but no signals
00783          *  - it has exactly one track
00784          *  - the track is in line with the station
00785          *  - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
00786          */
00787         TrackBits tracks = GetTrackBits(tile_cur);
00788         Track track = RemoveFirstTrack(&tracks);
00789         Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00790 
00791         if (tracks == TRACK_BIT_NONE && track == expected_track) {
00792           /* Check for trains having a reservation for this tile. */
00793           if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
00794             Train *v = GetTrainForReservation(tile_cur, track);
00795             if (v != NULL) {
00796               *affected_vehicles.Append() = v;
00797             }
00798           }
00799           CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00800           if (ret.Failed()) return ret;
00801           cost.AddCost(ret);
00802           /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
00803           continue;
00804         }
00805       }
00806       ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00807       if (ret.Failed()) return ret;
00808       cost.AddCost(ret);
00809     }
00810   }
00811 
00812   return cost;
00813 }
00814 
00827 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)
00828 {
00829   CommandCost cost(EXPENSES_CONSTRUCTION);
00830   int allowed_z = -1;
00831 
00832   TILE_AREA_LOOP(cur_tile, tile_area) {
00833     CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
00834     if (ret.Failed()) return ret;
00835     cost.AddCost(ret);
00836 
00837     /* If station is set, then we have special handling to allow building on top of already existing stations.
00838      * Station points to INVALID_STATION if we can build on any station.
00839      * Or it points to a station if we're only allowed to build on exactly that station. */
00840     if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
00841       if (!IsRoadStop(cur_tile)) {
00842         return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
00843       } else {
00844         if (is_truck_stop != IsTruckStop(cur_tile) ||
00845             is_drive_through != IsDriveThroughStopTile(cur_tile)) {
00846           return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
00847         }
00848         /* Drive-through station in the wrong direction. */
00849         if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
00850           return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00851         }
00852         StationID st = GetStationIndex(cur_tile);
00853         if (*station == INVALID_STATION) {
00854           *station = st;
00855         } else if (*station != st) {
00856           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00857         }
00858       }
00859     } else {
00860       bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
00861       /* Road bits in the wrong direction. */
00862       RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
00863       if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
00864         /* Someone was pedantic and *NEEDED* three fracking different error messages. */
00865         switch (CountBits(rb)) {
00866           case 1:
00867             return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00868 
00869           case 2:
00870             if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00871             return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
00872 
00873           default: // 3 or 4
00874             return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
00875         }
00876       }
00877 
00878       RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
00879       uint num_roadbits = 0;
00880       if (build_over_road) {
00881         /* There is a road, check if we can build road+tram stop over it. */
00882         if (HasBit(cur_rts, ROADTYPE_ROAD)) {
00883           Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
00884           if (road_owner == OWNER_TOWN) {
00885             if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
00886           } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
00887             CommandCost ret = CheckOwnership(road_owner);
00888             if (ret.Failed()) return ret;
00889           }
00890           num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
00891         }
00892 
00893         /* There is a tram, check if we can build road+tram stop over it. */
00894         if (HasBit(cur_rts, ROADTYPE_TRAM)) {
00895           Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
00896           if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
00897             CommandCost ret = CheckOwnership(tram_owner);
00898             if (ret.Failed()) return ret;
00899           }
00900           num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
00901         }
00902 
00903         /* Take into account existing roadbits. */
00904         rts |= cur_rts;
00905       } else {
00906         ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00907         if (ret.Failed()) return ret;
00908         cost.AddCost(ret);
00909       }
00910 
00911       uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
00912       cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
00913     }
00914   }
00915 
00916   return cost;
00917 }
00918 
00926 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00927 {
00928   TileArea cur_ta = st->train_station;
00929 
00930   /* determine new size of train station region.. */
00931   int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00932   int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00933   new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00934   new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00935   new_ta.tile = TileXY(x, y);
00936 
00937   /* make sure the final size is not too big. */
00938   if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00939     return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00940   }
00941 
00942   return CommandCost();
00943 }
00944 
00945 static inline byte *CreateSingle(byte *layout, int n)
00946 {
00947   int i = n;
00948   do *layout++ = 0; while (--i);
00949   layout[((n - 1) >> 1) - n] = 2;
00950   return layout;
00951 }
00952 
00953 static inline byte *CreateMulti(byte *layout, int n, byte b)
00954 {
00955   int i = n;
00956   do *layout++ = b; while (--i);
00957   if (n > 4) {
00958     layout[0 - n] = 0;
00959     layout[n - 1 - n] = 0;
00960   }
00961   return layout;
00962 }
00963 
00971 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
00972 {
00973   if (statspec != NULL && statspec->lengths >= plat_len &&
00974       statspec->platforms[plat_len - 1] >= numtracks &&
00975       statspec->layouts[plat_len - 1][numtracks - 1]) {
00976     /* Custom layout defined, follow it. */
00977     memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
00978       plat_len * numtracks);
00979     return;
00980   }
00981 
00982   if (plat_len == 1) {
00983     CreateSingle(layout, numtracks);
00984   } else {
00985     if (numtracks & 1) layout = CreateSingle(layout, plat_len);
00986     numtracks >>= 1;
00987 
00988     while (--numtracks >= 0) {
00989       layout = CreateMulti(layout, plat_len, 4);
00990       layout = CreateMulti(layout, plat_len, 6);
00991     }
00992   }
00993 }
00994 
01006 template <class T, StringID error_message>
01007 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
01008 {
01009   assert(*st == NULL);
01010   bool check_surrounding = true;
01011 
01012   if (_settings_game.station.adjacent_stations) {
01013     if (existing_station != INVALID_STATION) {
01014       if (adjacent && existing_station != station_to_join) {
01015         /* You can't build an adjacent station over the top of one that
01016          * already exists. */
01017         return_cmd_error(error_message);
01018       } else {
01019         /* Extend the current station, and don't check whether it will
01020          * be near any other stations. */
01021         *st = T::GetIfValid(existing_station);
01022         check_surrounding = (*st == NULL);
01023       }
01024     } else {
01025       /* There's no station here. Don't check the tiles surrounding this
01026        * one if the company wanted to build an adjacent station. */
01027       if (adjacent) check_surrounding = false;
01028     }
01029   }
01030 
01031   if (check_surrounding) {
01032     /* Make sure there are no similar stations around us. */
01033     CommandCost ret = GetStationAround(ta, existing_station, st);
01034     if (ret.Failed()) return ret;
01035   }
01036 
01037   /* Distant join */
01038   if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
01039 
01040   return CommandCost();
01041 }
01042 
01052 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01053 {
01054   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
01055 }
01056 
01066 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
01067 {
01068   return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
01069 }
01070 
01088 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01089 {
01090   /* Unpack parameters */
01091   RailType rt    = Extract<RailType, 0, 4>(p1);
01092   Axis axis      = Extract<Axis, 4, 1>(p1);
01093   byte numtracks = GB(p1,  8, 8);
01094   byte plat_len  = GB(p1, 16, 8);
01095   bool adjacent  = HasBit(p1, 24);
01096 
01097   StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
01098   byte spec_index           = GB(p2, 8, 8);
01099   StationID station_to_join = GB(p2, 16, 16);
01100 
01101   /* Does the authority allow this? */
01102   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
01103   if (ret.Failed()) return ret;
01104 
01105   if (!ValParamRailtype(rt)) return CMD_ERROR;
01106 
01107   /* Check if the given station class is valid */
01108   if ((uint)spec_class >= StationClass::GetCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
01109   if (spec_index >= StationClass::GetCount(spec_class)) return CMD_ERROR;
01110   if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
01111 
01112   int w_org, h_org;
01113   if (axis == AXIS_X) {
01114     w_org = plat_len;
01115     h_org = numtracks;
01116   } else {
01117     h_org = plat_len;
01118     w_org = numtracks;
01119   }
01120 
01121   bool reuse = (station_to_join != NEW_STATION);
01122   if (!reuse) station_to_join = INVALID_STATION;
01123   bool distant_join = (station_to_join != INVALID_STATION);
01124 
01125   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01126 
01127   if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01128 
01129   /* these values are those that will be stored in train_tile and station_platforms */
01130   TileArea new_location(tile_org, w_org, h_org);
01131 
01132   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
01133   StationID est = INVALID_STATION;
01134   SmallVector<Train *, 4> affected_vehicles;
01135   /* Clear the land below the station. */
01136   CommandCost cost = CheckFlatLandRailStation(TileArea(tile_org, w_org, h_org), flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
01137   if (cost.Failed()) return cost;
01138   /* Add construction expenses. */
01139   cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01140   cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
01141 
01142   Station *st = NULL;
01143   ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01144   if (ret.Failed()) return ret;
01145 
01146   /* See if there is a deleted station close to us. */
01147   if (st == NULL && reuse) st = GetClosestDeletedStation(tile_org);
01148 
01149   if (st != NULL) {
01150     /* Reuse an existing station. */
01151     if (st->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01152 
01153     if (st->train_station.tile != INVALID_TILE) {
01154       CommandCost ret = CanExpandRailStation(st, new_location, axis);
01155       if (ret.Failed()) return ret;
01156     }
01157 
01158     /* XXX can't we pack this in the "else" part of the if above? */
01159     CommandCost ret = st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST);
01160     if (ret.Failed()) return ret;
01161   } else {
01162     /* allocate and initialize new station */
01163     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01164 
01165     if (flags & DC_EXEC) {
01166       st = new Station(tile_org);
01167 
01168       st->town = ClosestTownFromTile(tile_org, UINT_MAX);
01169       st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);
01170 
01171       if (Company::IsValidID(_current_company)) {
01172         SetBit(st->town->have_ratings, _current_company);
01173       }
01174     }
01175   }
01176 
01177   /* Check if we can allocate a custom stationspec to this station */
01178   const StationSpec *statspec = StationClass::Get(spec_class, spec_index);
01179   int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01180   if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01181 
01182   if (statspec != NULL) {
01183     /* Perform NewStation checks */
01184 
01185     /* Check if the station size is permitted */
01186     if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01187       return CMD_ERROR;
01188     }
01189 
01190     /* Check if the station is buildable */
01191     if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
01192       uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
01193       if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
01194     }
01195   }
01196 
01197   if (flags & DC_EXEC) {
01198     TileIndexDiff tile_delta;
01199     byte *layout_ptr;
01200     byte numtracks_orig;
01201     Track track;
01202 
01203     st->train_station = new_location;
01204     st->AddFacility(FACIL_TRAIN, new_location.tile);
01205 
01206     st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01207 
01208     if (statspec != NULL) {
01209       /* Include this station spec's animation trigger bitmask
01210        * in the station's cached copy. */
01211       st->cached_anim_triggers |= statspec->animation.triggers;
01212     }
01213 
01214     tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01215     track = AxisToTrack(axis);
01216 
01217     layout_ptr = AllocaM(byte, numtracks * plat_len);
01218     GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01219 
01220     numtracks_orig = numtracks;
01221 
01222     Company *c = Company::Get(st->owner);
01223     do {
01224       TileIndex tile = tile_org;
01225       int w = plat_len;
01226       do {
01227         byte layout = *layout_ptr++;
01228         if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01229           /* Check for trains having a reservation for this tile. */
01230           Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01231           if (v != NULL) {
01232             FreeTrainTrackReservation(v);
01233             *affected_vehicles.Append() = v;
01234             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01235             for (; v->Next() != NULL; v = v->Next()) { }
01236             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01237           }
01238         }
01239 
01240         /* Railtype can change when overbuilding. */
01241         if (IsRailStationTile(tile)) {
01242           if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
01243           c->infrastructure.station--;
01244         }
01245 
01246         /* Remove animation if overbuilding */
01247         DeleteAnimatedTile(tile);
01248         byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01249         MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01250         /* Free the spec if we overbuild something */
01251         DeallocateSpecFromStation(st, old_specindex);
01252 
01253         SetCustomStationSpecIndex(tile, specindex);
01254         SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01255         SetAnimationFrame(tile, 0);
01256 
01257         if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
01258         c->infrastructure.station++;
01259 
01260         if (statspec != NULL) {
01261           /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
01262           uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01263 
01264           /* As the station is not yet completely finished, the station does not yet exist. */
01265           uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01266           if (callback != CALLBACK_FAILED) {
01267             if (callback < 8) {
01268               SetStationGfx(tile, (callback & ~1) + axis);
01269             } else {
01270               ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
01271             }
01272           }
01273 
01274           /* Trigger station animation -- after building? */
01275           TriggerStationAnimation(st, tile, SAT_BUILT);
01276         }
01277 
01278         tile += tile_delta;
01279       } while (--w);
01280       AddTrackToSignalBuffer(tile_org, track, _current_company);
01281       YapfNotifyTrackLayoutChange(tile_org, track);
01282       tile_org += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
01283     } while (--numtracks);
01284 
01285     for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01286       /* Restore reservations of trains. */
01287       Train *v = affected_vehicles[i];
01288       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01289       TryPathReserve(v, true, true);
01290       for (; v->Next() != NULL; v = v->Next()) { }
01291       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01292     }
01293 
01294     st->MarkTilesDirty(false);
01295     st->UpdateVirtCoord();
01296     UpdateStationAcceptance(st, false);
01297     st->RecomputeIndustriesNear();
01298     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01299     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01300     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01301     DirtyCompanyInfrastructureWindows(st->owner);
01302   }
01303 
01304   return cost;
01305 }
01306 
01307 static void MakeRailStationAreaSmaller(BaseStation *st)
01308 {
01309   TileArea ta = st->train_station;
01310 
01311 restart:
01312 
01313   /* too small? */
01314   if (ta.w != 0 && ta.h != 0) {
01315     /* check the left side, x = constant, y changes */
01316     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01317       /* the left side is unused? */
01318       if (++i == ta.h) {
01319         ta.tile += TileDiffXY(1, 0);
01320         ta.w--;
01321         goto restart;
01322       }
01323     }
01324 
01325     /* check the right side, x = constant, y changes */
01326     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01327       /* the right side is unused? */
01328       if (++i == ta.h) {
01329         ta.w--;
01330         goto restart;
01331       }
01332     }
01333 
01334     /* check the upper side, y = constant, x changes */
01335     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01336       /* the left side is unused? */
01337       if (++i == ta.w) {
01338         ta.tile += TileDiffXY(0, 1);
01339         ta.h--;
01340         goto restart;
01341       }
01342     }
01343 
01344     /* check the lower side, y = constant, x changes */
01345     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01346       /* the left side is unused? */
01347       if (++i == ta.w) {
01348         ta.h--;
01349         goto restart;
01350       }
01351     }
01352   } else {
01353     ta.Clear();
01354   }
01355 
01356   st->train_station = ta;
01357 }
01358 
01369 template <class T>
01370 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01371 {
01372   /* Count of the number of tiles removed */
01373   int quantity = 0;
01374   CommandCost total_cost(EXPENSES_CONSTRUCTION);
01375 
01376   /* Do the action for every tile into the area */
01377   TILE_AREA_LOOP(tile, ta) {
01378     /* Make sure the specified tile is a rail station */
01379     if (!HasStationTileRail(tile)) continue;
01380 
01381     /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
01382     CommandCost ret = EnsureNoVehicleOnGround(tile);
01383     if (ret.Failed()) continue;
01384 
01385     /* Check ownership of station */
01386     T *st = T::GetByTile(tile);
01387     if (st == NULL) continue;
01388 
01389     if (_current_company != OWNER_WATER) {
01390       CommandCost ret = CheckOwnership(st->owner);
01391       if (ret.Failed()) continue;
01392     }
01393 
01394     /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
01395     quantity++;
01396 
01397     if (keep_rail || IsStationTileBlocked(tile)) {
01398       /* Don't refund the 'steel' of the track when we keep the
01399        *  rail, or when the tile didn't have any rail at all. */
01400       total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01401     }
01402 
01403     if (flags & DC_EXEC) {
01404       /* read variables before the station tile is removed */
01405       uint specindex = GetCustomStationSpecIndex(tile);
01406       Track track = GetRailStationTrack(tile);
01407       Owner owner = GetTileOwner(tile);
01408       RailType rt = GetRailType(tile);
01409       Train *v = NULL;
01410 
01411       if (HasStationReservation(tile)) {
01412         v = GetTrainForReservation(tile, track);
01413         if (v != NULL) {
01414           /* Free train reservation. */
01415           FreeTrainTrackReservation(v);
01416           if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01417           Vehicle *temp = v;
01418           for (; temp->Next() != NULL; temp = temp->Next()) { }
01419           if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01420         }
01421       }
01422 
01423       bool build_rail = keep_rail && !IsStationTileBlocked(tile);
01424       if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
01425 
01426       DoClearSquare(tile);
01427       DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01428       if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01429       Company::Get(owner)->infrastructure.station--;
01430       DirtyCompanyInfrastructureWindows(owner);
01431 
01432       st->rect.AfterRemoveTile(st, tile);
01433       AddTrackToSignalBuffer(tile, track, owner);
01434       YapfNotifyTrackLayoutChange(tile, track);
01435 
01436       DeallocateSpecFromStation(st, specindex);
01437 
01438       affected_stations.Include(st);
01439 
01440       if (v != NULL) {
01441         /* Restore station reservation. */
01442         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01443         TryPathReserve(v, true, true);
01444         for (; v->Next() != NULL; v = v->Next()) { }
01445         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01446       }
01447     }
01448   }
01449 
01450   if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01451 
01452   for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01453     T *st = *stp;
01454 
01455     /* now we need to make the "spanned" area of the railway station smaller
01456      * if we deleted something at the edges.
01457      * we also need to adjust train_tile. */
01458     MakeRailStationAreaSmaller(st);
01459     UpdateStationSignCoord(st);
01460 
01461     /* if we deleted the whole station, delete the train facility. */
01462     if (st->train_station.tile == INVALID_TILE) {
01463       st->facilities &= ~FACIL_TRAIN;
01464       SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01465       st->UpdateVirtCoord();
01466       DeleteStationIfEmpty(st);
01467     }
01468   }
01469 
01470   total_cost.AddCost(quantity * removal_cost);
01471   return total_cost;
01472 }
01473 
01485 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01486 {
01487   TileIndex end = p1 == 0 ? start : p1;
01488   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01489 
01490   TileArea ta(start, end);
01491   SmallVector<Station *, 4> affected_stations;
01492 
01493   CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01494   if (ret.Failed()) return ret;
01495 
01496   /* Do all station specific functions here. */
01497   for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01498     Station *st = *stp;
01499 
01500     if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01501     st->MarkTilesDirty(false);
01502     st->RecomputeIndustriesNear();
01503   }
01504 
01505   /* Now apply the rail cost to the number that we deleted */
01506   return ret;
01507 }
01508 
01520 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01521 {
01522   TileIndex end = p1 == 0 ? start : p1;
01523   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01524 
01525   TileArea ta(start, end);
01526   SmallVector<Waypoint *, 4> affected_stations;
01527 
01528   return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01529 }
01530 
01531 
01539 template <class T>
01540 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01541 {
01542   /* Current company owns the station? */
01543   if (_current_company != OWNER_WATER) {
01544     CommandCost ret = CheckOwnership(st->owner);
01545     if (ret.Failed()) return ret;
01546   }
01547 
01548   /* determine width and height of platforms */
01549   TileArea ta = st->train_station;
01550 
01551   assert(ta.w != 0 && ta.h != 0);
01552 
01553   CommandCost cost(EXPENSES_CONSTRUCTION);
01554   /* clear all areas of the station */
01555   TILE_AREA_LOOP(tile, ta) {
01556     /* only remove tiles that are actually train station tiles */
01557     if (!st->TileBelongsToRailStation(tile)) continue;
01558 
01559     CommandCost ret = EnsureNoVehicleOnGround(tile);
01560     if (ret.Failed()) return ret;
01561 
01562     cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01563     if (flags & DC_EXEC) {
01564       /* read variables before the station tile is removed */
01565       Track track = GetRailStationTrack(tile);
01566       Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
01567       Train *v = NULL;
01568       if (HasStationReservation(tile)) {
01569         v = GetTrainForReservation(tile, track);
01570         if (v != NULL) FreeTrainTrackReservation(v);
01571       }
01572       if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
01573       Company::Get(owner)->infrastructure.station--;
01574       DoClearSquare(tile);
01575       DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01576       AddTrackToSignalBuffer(tile, track, owner);
01577       YapfNotifyTrackLayoutChange(tile, track);
01578       if (v != NULL) TryPathReserve(v, true);
01579     }
01580   }
01581 
01582   if (flags & DC_EXEC) {
01583     st->rect.AfterRemoveRect(st, st->train_station);
01584 
01585     st->train_station.Clear();
01586 
01587     st->facilities &= ~FACIL_TRAIN;
01588 
01589     free(st->speclist);
01590     st->num_specs = 0;
01591     st->speclist  = NULL;
01592     st->cached_anim_triggers = 0;
01593 
01594     DirtyCompanyInfrastructureWindows(st->owner);
01595     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01596     st->UpdateVirtCoord();
01597     DeleteStationIfEmpty(st);
01598   }
01599 
01600   return cost;
01601 }
01602 
01609 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01610 {
01611   /* if there is flooding, remove platforms tile by tile */
01612   if (_current_company == OWNER_WATER) {
01613     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01614   }
01615 
01616   Station *st = Station::GetByTile(tile);
01617   CommandCost cost = RemoveRailStation(st, flags);
01618 
01619   if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01620 
01621   return cost;
01622 }
01623 
01630 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01631 {
01632   /* if there is flooding, remove waypoints tile by tile */
01633   if (_current_company == OWNER_WATER) {
01634     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01635   }
01636 
01637   return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01638 }
01639 
01640 
01646 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01647 {
01648   RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01649 
01650   if (*primary_stop == NULL) {
01651     /* we have no roadstop of the type yet, so write a "primary stop" */
01652     return primary_stop;
01653   } else {
01654     /* there are stops already, so append to the end of the list */
01655     RoadStop *stop = *primary_stop;
01656     while (stop->next != NULL) stop = stop->next;
01657     return &stop->next;
01658   }
01659 }
01660 
01661 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
01662 
01672 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01673 {
01674   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
01675 }
01676 
01692 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01693 {
01694   bool type = HasBit(p2, 0);
01695   bool is_drive_through = HasBit(p2, 1);
01696   RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
01697   StationID station_to_join = GB(p2, 16, 16);
01698   bool reuse = (station_to_join != NEW_STATION);
01699   if (!reuse) station_to_join = INVALID_STATION;
01700   bool distant_join = (station_to_join != INVALID_STATION);
01701 
01702   uint8 width = (uint8)GB(p1, 0, 8);
01703   uint8 lenght = (uint8)GB(p1, 8, 8);
01704 
01705   /* Check if the requested road stop is too big */
01706   if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
01707   /* Check for incorrect width / lenght. */
01708   if (width == 0 || lenght == 0) return CMD_ERROR;
01709   /* Check if the first tile and the last tile are valid */
01710   if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
01711 
01712   TileArea roadstop_area(tile, width, lenght);
01713 
01714   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01715 
01716   if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01717 
01718   /* Trams only have drive through stops */
01719   if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01720 
01721   DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
01722 
01723   /* Safeguard the parameters. */
01724   if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
01725   /* If it is a drive-through stop, check for valid axis. */
01726   if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
01727 
01728   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
01729   if (ret.Failed()) return ret;
01730 
01731   /* Total road stop cost. */
01732   CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01733   StationID est = INVALID_STATION;
01734   ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
01735   if (ret.Failed()) return ret;
01736   cost.AddCost(ret);
01737 
01738   Station *st = NULL;
01739   ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
01740   if (ret.Failed()) return ret;
01741 
01742   /* Find a deleted station close to us */
01743   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
01744 
01745   /* Check if this number of road stops can be allocated. */
01746   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);
01747 
01748   if (st != NULL) {
01749     if (st->owner != _current_company) {
01750       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01751     }
01752 
01753     CommandCost ret = st->rect.BeforeAddRect(roadstop_area.tile, roadstop_area.w, roadstop_area.h, StationRect::ADD_TEST);
01754     if (ret.Failed()) return ret;
01755   } else {
01756     /* allocate and initialize new station */
01757     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01758 
01759     if (flags & DC_EXEC) {
01760       st = new Station(tile);
01761 
01762       st->town = ClosestTownFromTile(tile, UINT_MAX);
01763       st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
01764 
01765       if (Company::IsValidID(_current_company)) {
01766         SetBit(st->town->have_ratings, _current_company);
01767       }
01768     }
01769   }
01770 
01771   if (flags & DC_EXEC) {
01772     /* Check every tile in the area. */
01773     TILE_AREA_LOOP(cur_tile, roadstop_area) {
01774       RoadTypes cur_rts = GetRoadTypes(cur_tile);
01775       Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
01776       Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
01777 
01778       if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
01779         RemoveRoadStop(cur_tile, flags);
01780       }
01781 
01782       RoadStop *road_stop = new RoadStop(cur_tile);
01783       /* Insert into linked list of RoadStops. */
01784       RoadStop **currstop = FindRoadStopSpot(type, st);
01785       *currstop = road_stop;
01786 
01787       if (type) {
01788         st->truck_station.Add(cur_tile);
01789       } else {
01790         st->bus_station.Add(cur_tile);
01791       }
01792 
01793       /* Initialize an empty station. */
01794       st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
01795 
01796       st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
01797 
01798       RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01799       if (is_drive_through) {
01800         /* Update company infrastructure counts. If the current tile is a normal
01801          * road tile, count only the new road bits needed to get a full diagonal road. */
01802         RoadType rt;
01803         FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
01804           Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
01805           if (c != NULL) {
01806             c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
01807             DirtyCompanyInfrastructureWindows(c->index);
01808           }
01809         }
01810 
01811         MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
01812         road_stop->MakeDriveThrough();
01813       } else {
01814         /* Non-drive-through stop never overbuild and always count as two road bits. */
01815         Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
01816         MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
01817       }
01818       Company::Get(st->owner)->infrastructure.station++;
01819       DirtyCompanyInfrastructureWindows(st->owner);
01820 
01821       MarkTileDirtyByTile(cur_tile);
01822     }
01823   }
01824 
01825   if (st != NULL) {
01826     st->UpdateVirtCoord();
01827     UpdateStationAcceptance(st, false);
01828     st->RecomputeIndustriesNear();
01829     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01830     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01831     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01832   }
01833   return cost;
01834 }
01835 
01836 
01837 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01838 {
01839   if (v->type == VEH_ROAD) {
01840     /* Okay... we are a road vehicle on a drive through road stop.
01841      * But that road stop has just been removed, so we need to make
01842      * sure we are in a valid state... however, vehicles can also
01843      * turn on road stop tiles, so only clear the 'road stop' state
01844      * bits and only when the state was 'in road stop', otherwise
01845      * we'll end up clearing the turn around bits. */
01846     RoadVehicle *rv = RoadVehicle::From(v);
01847     if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01848   }
01849 
01850   return NULL;
01851 }
01852 
01853 
01860 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01861 {
01862   Station *st = Station::GetByTile(tile);
01863 
01864   if (_current_company != OWNER_WATER) {
01865     CommandCost ret = CheckOwnership(st->owner);
01866     if (ret.Failed()) return ret;
01867   }
01868 
01869   bool is_truck = IsTruckStop(tile);
01870 
01871   RoadStop **primary_stop;
01872   RoadStop *cur_stop;
01873   if (is_truck) { // truck stop
01874     primary_stop = &st->truck_stops;
01875     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01876   } else {
01877     primary_stop = &st->bus_stops;
01878     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01879   }
01880 
01881   assert(cur_stop != NULL);
01882 
01883   /* don't do the check for drive-through road stops when company bankrupts */
01884   if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01885     /* remove the 'going through road stop' status from all vehicles on that tile */
01886     if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01887   } else {
01888     CommandCost ret = EnsureNoVehicleOnGround(tile);
01889     if (ret.Failed()) return ret;
01890   }
01891 
01892   if (flags & DC_EXEC) {
01893     if (*primary_stop == cur_stop) {
01894       /* removed the first stop in the list */
01895       *primary_stop = cur_stop->next;
01896       /* removed the only stop? */
01897       if (*primary_stop == NULL) {
01898         st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01899       }
01900     } else {
01901       /* tell the predecessor in the list to skip this stop */
01902       RoadStop *pred = *primary_stop;
01903       while (pred->next != cur_stop) pred = pred->next;
01904       pred->next = cur_stop->next;
01905     }
01906 
01907     /* Update company infrastructure counts. */
01908     RoadType rt;
01909     FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
01910       Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
01911       if (c != NULL) {
01912         c->infrastructure.road[rt] -= 2;
01913         DirtyCompanyInfrastructureWindows(c->index);
01914       }
01915     }
01916     Company::Get(st->owner)->infrastructure.station--;
01917 
01918     if (IsDriveThroughStopTile(tile)) {
01919       /* Clears the tile for us */
01920       cur_stop->ClearDriveThrough();
01921     } else {
01922       DoClearSquare(tile);
01923     }
01924 
01925     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01926     delete cur_stop;
01927 
01928     /* Make sure no vehicle is going to the old roadstop */
01929     RoadVehicle *v;
01930     FOR_ALL_ROADVEHICLES(v) {
01931       if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01932           v->dest_tile == tile) {
01933         v->dest_tile = v->GetOrderStationLocation(st->index);
01934       }
01935     }
01936 
01937     st->rect.AfterRemoveTile(st, tile);
01938 
01939     st->UpdateVirtCoord();
01940     st->RecomputeIndustriesNear();
01941     DeleteStationIfEmpty(st);
01942 
01943     /* Update the tile area of the truck/bus stop */
01944     if (is_truck) {
01945       st->truck_station.Clear();
01946       for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01947     } else {
01948       st->bus_station.Clear();
01949       for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
01950     }
01951   }
01952 
01953   return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
01954 }
01955 
01966 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01967 {
01968   uint8 width = (uint8)GB(p1, 0, 8);
01969   uint8 height = (uint8)GB(p1, 8, 8);
01970 
01971   /* Check for incorrect width / height. */
01972   if (width == 0 || height == 0) return CMD_ERROR;
01973   /* Check if the first tile and the last tile are valid */
01974   if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
01975 
01976   TileArea roadstop_area(tile, width, height);
01977 
01978   int quantity = 0;
01979   CommandCost cost(EXPENSES_CONSTRUCTION);
01980   TILE_AREA_LOOP(cur_tile, roadstop_area) {
01981     /* Make sure the specified tile is a road stop of the correct type */
01982     if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
01983 
01984     /* Save the stop info before it is removed */
01985     bool is_drive_through = IsDriveThroughStopTile(cur_tile);
01986     RoadTypes rts = GetRoadTypes(cur_tile);
01987     RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
01988         ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
01989         DiagDirToRoadBits(GetRoadStopDir(cur_tile));
01990 
01991     Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
01992     Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
01993     CommandCost ret = RemoveRoadStop(cur_tile, flags);
01994     if (ret.Failed()) return ret;
01995     cost.AddCost(ret);
01996 
01997     quantity++;
01998     /* If the stop was a drive-through stop replace the road */
01999     if ((flags & DC_EXEC) && is_drive_through) {
02000       MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
02001           road_owner, tram_owner);
02002 
02003       /* Update company infrastructure counts. */
02004       RoadType rt;
02005       FOR_EACH_SET_ROADTYPE(rt, rts) {
02006         Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
02007         if (c != NULL) {
02008           c->infrastructure.road[rt] += CountBits(road_bits);
02009           DirtyCompanyInfrastructureWindows(c->index);
02010         }
02011       }
02012     }
02013   }
02014 
02015   if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
02016 
02017   return cost;
02018 }
02019 
02026 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
02027 {
02028   uint mindist = UINT_MAX;
02029 
02030   for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
02031     mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
02032   }
02033 
02034   return mindist;
02035 }
02036 
02046 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
02047 {
02048   /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
02049    * So no need to go any further*/
02050   if (as->noise_level < 2) return as->noise_level;
02051 
02052   uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
02053 
02054   /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
02055    * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
02056    * Basically, it says that the less tolerant a town is, the bigger the distance before
02057    * an actual decrease can be granted */
02058   uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
02059 
02060   /* now, we want to have the distance segmented using the distance judged bareable by town
02061    * This will give us the coefficient of reduction the distance provides. */
02062   uint noise_reduction = distance / town_tolerance_distance;
02063 
02064   /* If the noise reduction equals the airport noise itself, don't give it for free.
02065    * Otherwise, simply reduce the airport's level. */
02066   return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
02067 }
02068 
02076 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
02077 {
02078   Town *t, *nearest = NULL;
02079   uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
02080   uint mindist = UINT_MAX - add; // prevent overflow
02081   FOR_ALL_TOWNS(t) {
02082     if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
02083       TileIterator *copy = it.Clone();
02084       uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
02085       delete copy;
02086       if (dist < mindist) {
02087         nearest = t;
02088         mindist = dist;
02089       }
02090     }
02091   }
02092 
02093   return nearest;
02094 }
02095 
02096 
02098 void UpdateAirportsNoise()
02099 {
02100   Town *t;
02101   const Station *st;
02102 
02103   FOR_ALL_TOWNS(t) t->noise_reached = 0;
02104 
02105   FOR_ALL_STATIONS(st) {
02106     if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
02107       const AirportSpec *as = st->airport.GetSpec();
02108       AirportTileIterator it(st);
02109       Town *nearest = AirportGetNearestTown(as, it);
02110       nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
02111     }
02112   }
02113 }
02114 
02128 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02129 {
02130   StationID station_to_join = GB(p2, 16, 16);
02131   bool reuse = (station_to_join != NEW_STATION);
02132   if (!reuse) station_to_join = INVALID_STATION;
02133   bool distant_join = (station_to_join != INVALID_STATION);
02134   byte airport_type = GB(p1, 0, 8);
02135   byte layout = GB(p1, 8, 8);
02136 
02137   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02138 
02139   if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
02140 
02141   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02142   if (ret.Failed()) return ret;
02143 
02144   /* Check if a valid, buildable airport was chosen for construction */
02145   const AirportSpec *as = AirportSpec::Get(airport_type);
02146   if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
02147 
02148   Direction rotation = as->rotation[layout];
02149   Town *t = ClosestTownFromTile(tile, UINT_MAX);
02150   int w = as->size_x;
02151   int h = as->size_y;
02152   if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
02153 
02154   if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
02155     return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
02156   }
02157 
02158   CommandCost cost = CheckFlatLand(TileArea(tile, w, h), flags);
02159   if (cost.Failed()) return cost;
02160 
02161   /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
02162   AirportTileTableIterator iter(as->table[layout], tile);
02163   Town *nearest = AirportGetNearestTown(as, iter);
02164   uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
02165 
02166   /* Check if local auth would allow a new airport */
02167   StringID authority_refuse_message = STR_NULL;
02168   Town *authority_refuse_town = NULL;
02169 
02170   if (_settings_game.economy.station_noise_level) {
02171     /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
02172     if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
02173       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
02174       authority_refuse_town = nearest;
02175     }
02176   } else {
02177     uint num = 0;
02178     const Station *st;
02179     FOR_ALL_STATIONS(st) {
02180       if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
02181     }
02182     if (num >= 2) {
02183       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
02184       authority_refuse_town = t;
02185     }
02186   }
02187 
02188   if (authority_refuse_message != STR_NULL) {
02189     SetDParam(0, authority_refuse_town->index);
02190     return_cmd_error(authority_refuse_message);
02191   }
02192 
02193   Station *st = NULL;
02194   ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
02195   if (ret.Failed()) return ret;
02196 
02197   /* Distant join */
02198   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02199 
02200   /* Find a deleted station close to us */
02201   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02202 
02203   if (st != NULL) {
02204     if (st->owner != _current_company) {
02205       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02206     }
02207 
02208     CommandCost ret = st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST);
02209     if (ret.Failed()) return ret;
02210 
02211     if (st->airport.tile != INVALID_TILE) {
02212       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
02213     }
02214   } else {
02215     /* allocate and initialize new station */
02216     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02217 
02218     if (flags & DC_EXEC) {
02219       st = new Station(tile);
02220 
02221       st->town = t;
02222       st->string_id = GenerateStationName(st, tile, !(GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
02223 
02224       if (Company::IsValidID(_current_company)) {
02225         SetBit(st->town->have_ratings, _current_company);
02226       }
02227     }
02228   }
02229 
02230   for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02231     cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
02232   }
02233 
02234   if (flags & DC_EXEC) {
02235     /* Always add the noise, so there will be no need to recalculate when option toggles */
02236     nearest->noise_reached += newnoise_level;
02237 
02238     st->AddFacility(FACIL_AIRPORT, tile);
02239     st->airport.type = airport_type;
02240     st->airport.layout = layout;
02241     st->airport.flags = 0;
02242     st->airport.rotation = rotation;
02243 
02244     st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02245 
02246     for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02247       MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
02248       SetStationTileRandomBits(iter, GB(Random(), 0, 4));
02249       st->airport.Add(iter);
02250 
02251       if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
02252     }
02253 
02254     /* Only call the animation trigger after all tiles have been built */
02255     for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02256       AirportTileAnimationTrigger(st, iter, AAT_BUILT);
02257     }
02258 
02259     UpdateAirplanesOnNewStation(st);
02260 
02261     Company::Get(st->owner)->infrastructure.airport++;
02262     DirtyCompanyInfrastructureWindows(st->owner);
02263 
02264     st->UpdateVirtCoord();
02265     UpdateStationAcceptance(st, false);
02266     st->RecomputeIndustriesNear();
02267     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02268     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02269     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_PLANES);
02270 
02271     if (_settings_game.economy.station_noise_level) {
02272       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02273     }
02274   }
02275 
02276   return cost;
02277 }
02278 
02285 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02286 {
02287   Station *st = Station::GetByTile(tile);
02288 
02289   if (_current_company != OWNER_WATER) {
02290     CommandCost ret = CheckOwnership(st->owner);
02291     if (ret.Failed()) return ret;
02292   }
02293 
02294   tile = st->airport.tile;
02295 
02296   CommandCost cost(EXPENSES_CONSTRUCTION);
02297 
02298   const Aircraft *a;
02299   FOR_ALL_AIRCRAFT(a) {
02300     if (!a->IsNormalAircraft()) continue;
02301     if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02302   }
02303 
02304   if (flags & DC_EXEC) {
02305     const AirportSpec *as = st->airport.GetSpec();
02306     /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
02307      * And as for construction, always remove it, even if the setting is not set, in order to avoid the
02308      * need of recalculation */
02309     AirportTileIterator it(st);
02310     Town *nearest = AirportGetNearestTown(as, it);
02311     nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
02312   }
02313 
02314   TILE_AREA_LOOP(tile_cur, st->airport) {
02315     if (!st->TileBelongsToAirport(tile_cur)) continue;
02316 
02317     CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
02318     if (ret.Failed()) return ret;
02319 
02320     cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02321 
02322     if (flags & DC_EXEC) {
02323       if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
02324       DeleteAnimatedTile(tile_cur);
02325       DoClearSquare(tile_cur);
02326       DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
02327     }
02328   }
02329 
02330   if (flags & DC_EXEC) {
02331     /* Clear the persistent storage. */
02332     delete st->airport.psa;
02333 
02334     for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
02335       DeleteWindowById(
02336         WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
02337       );
02338     }
02339 
02340     st->rect.AfterRemoveRect(st, st->airport);
02341 
02342     st->airport.Clear();
02343     st->facilities &= ~FACIL_AIRPORT;
02344 
02345     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_PLANES);
02346 
02347     if (_settings_game.economy.station_noise_level) {
02348       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02349     }
02350 
02351     Company::Get(st->owner)->infrastructure.airport--;
02352     DirtyCompanyInfrastructureWindows(st->owner);
02353 
02354     st->UpdateVirtCoord();
02355     st->RecomputeIndustriesNear();
02356     DeleteStationIfEmpty(st);
02357     DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
02358   }
02359 
02360   return cost;
02361 }
02362 
02369 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
02370 {
02371   const Vehicle *v;
02372   FOR_ALL_VEHICLES(v) {
02373     if ((v->owner == company) == include_company) {
02374       const Order *order;
02375       FOR_VEHICLE_ORDERS(v, order) {
02376         if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02377           return true;
02378         }
02379       }
02380     }
02381   }
02382   return false;
02383 }
02384 
02385 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02386   {-1,  0},
02387   { 0,  0},
02388   { 0,  0},
02389   { 0, -1}
02390 };
02391 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02392 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02393 
02403 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02404 {
02405   StationID station_to_join = GB(p2, 16, 16);
02406   bool reuse = (station_to_join != NEW_STATION);
02407   if (!reuse) station_to_join = INVALID_STATION;
02408   bool distant_join = (station_to_join != INVALID_STATION);
02409 
02410   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02411 
02412   DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
02413   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02414   direction = ReverseDiagDir(direction);
02415 
02416   /* Docks cannot be placed on rapids */
02417   if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02418 
02419   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02420   if (ret.Failed()) return ret;
02421 
02422   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02423 
02424   ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02425   if (ret.Failed()) return ret;
02426 
02427   TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02428 
02429   if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur) != SLOPE_FLAT) {
02430     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02431   }
02432 
02433   if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02434 
02435   /* Get the water class of the water tile before it is cleared.*/
02436   WaterClass wc = GetWaterClass(tile_cur);
02437 
02438   ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02439   if (ret.Failed()) return ret;
02440 
02441   tile_cur += TileOffsByDiagDir(direction);
02442   if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur) != SLOPE_FLAT) {
02443     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02444   }
02445 
02446   /* middle */
02447   Station *st = NULL;
02448   ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
02449       TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02450           _dock_w_chk[direction], _dock_h_chk[direction]), &st);
02451   if (ret.Failed()) return ret;
02452 
02453   /* Distant join */
02454   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02455 
02456   /* Find a deleted station close to us */
02457   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02458 
02459   if (st != NULL) {
02460     if (st->owner != _current_company) {
02461       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02462     }
02463 
02464     CommandCost ret = st->rect.BeforeAddRect(
02465         tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02466         _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST);
02467     if (ret.Failed()) return ret;
02468 
02469     if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02470   } else {
02471     /* allocate and initialize new station */
02472     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02473 
02474     if (flags & DC_EXEC) {
02475       st = new Station(tile);
02476 
02477       st->town = ClosestTownFromTile(tile, UINT_MAX);
02478       st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
02479 
02480       if (Company::IsValidID(_current_company)) {
02481         SetBit(st->town->have_ratings, _current_company);
02482       }
02483     }
02484   }
02485 
02486   if (flags & DC_EXEC) {
02487     st->dock_tile = tile;
02488     st->AddFacility(FACIL_DOCK, tile);
02489 
02490     st->rect.BeforeAddRect(
02491         tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02492         _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
02493 
02494     /* If the water part of the dock is on a canal, update infrastructure counts.
02495      * This is needed as we've unconditionally cleared that tile before. */
02496     if (wc == WATER_CLASS_CANAL) {
02497       Company::Get(st->owner)->infrastructure.water++;
02498     }
02499     Company::Get(st->owner)->infrastructure.station += 2;
02500     DirtyCompanyInfrastructureWindows(st->owner);
02501 
02502     MakeDock(tile, st->owner, st->index, direction, wc);
02503 
02504     st->UpdateVirtCoord();
02505     UpdateStationAcceptance(st, false);
02506     st->RecomputeIndustriesNear();
02507     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02508     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02509     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02510   }
02511 
02512   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02513 }
02514 
02521 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02522 {
02523   Station *st = Station::GetByTile(tile);
02524   CommandCost ret = CheckOwnership(st->owner);
02525   if (ret.Failed()) return ret;
02526 
02527   TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
02528 
02529   TileIndex tile1 = st->dock_tile;
02530   TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02531 
02532   ret = EnsureNoVehicleOnGround(tile1);
02533   if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
02534   if (ret.Failed()) return ret;
02535 
02536   if (flags & DC_EXEC) {
02537     DoClearSquare(tile1);
02538     MarkTileDirtyByTile(tile1);
02539     MakeWaterKeepingClass(tile2, st->owner);
02540 
02541     st->rect.AfterRemoveTile(st, tile1);
02542     st->rect.AfterRemoveTile(st, tile2);
02543 
02544     st->dock_tile = INVALID_TILE;
02545     st->facilities &= ~FACIL_DOCK;
02546 
02547     Company::Get(st->owner)->infrastructure.station -= 2;
02548     DirtyCompanyInfrastructureWindows(st->owner);
02549 
02550     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02551     st->UpdateVirtCoord();
02552     st->RecomputeIndustriesNear();
02553     DeleteStationIfEmpty(st);
02554 
02555     /* All ships that were going to our station, can't go to it anymore.
02556      * Just clear the order, then automatically the next appropriate order
02557      * will be selected and in case of no appropriate order it will just
02558      * wander around the world. */
02559     Ship *s;
02560     FOR_ALL_SHIPS(s) {
02561       if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
02562         s->LeaveStation();
02563       }
02564 
02565       if (s->dest_tile == docking_location) {
02566         s->dest_tile = 0;
02567         s->current_order.Free();
02568       }
02569     }
02570   }
02571 
02572   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02573 }
02574 
02575 #include "table/station_land.h"
02576 
02577 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02578 {
02579   return &_station_display_datas[st][gfx];
02580 }
02581 
02582 static void DrawTile_Station(TileInfo *ti)
02583 {
02584   const NewGRFSpriteLayout *layout = NULL;
02585   DrawTileSprites tmp_rail_layout;
02586   const DrawTileSprites *t = NULL;
02587   RoadTypes roadtypes;
02588   int32 total_offset;
02589   const RailtypeInfo *rti = NULL;
02590   uint32 relocation = 0;
02591   uint32 ground_relocation = 0;
02592   BaseStation *st = NULL;
02593   const StationSpec *statspec = NULL;
02594   uint tile_layout = 0;
02595 
02596   if (HasStationRail(ti->tile)) {
02597     rti = GetRailTypeInfo(GetRailType(ti->tile));
02598     roadtypes = ROADTYPES_NONE;
02599     total_offset = rti->GetRailtypeSpriteOffset();
02600 
02601     if (IsCustomStationSpecIndex(ti->tile)) {
02602       /* look for customization */
02603       st = BaseStation::GetByTile(ti->tile);
02604       statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02605 
02606       if (statspec != NULL) {
02607         tile_layout = GetStationGfx(ti->tile);
02608 
02609         if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02610           uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02611           if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
02612         }
02613 
02614         /* Ensure the chosen tile layout is valid for this custom station */
02615         if (statspec->renderdata != NULL) {
02616           layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
02617           if (!layout->NeedsPreprocessing()) {
02618             t = layout;
02619             layout = NULL;
02620           }
02621         }
02622       }
02623     }
02624   } else {
02625     roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02626     total_offset = 0;
02627   }
02628 
02629   StationGfx gfx = GetStationGfx(ti->tile);
02630   if (IsAirport(ti->tile)) {
02631     gfx = GetAirportGfx(ti->tile);
02632     if (gfx >= NEW_AIRPORTTILE_OFFSET) {
02633       const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
02634       if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
02635         return;
02636       }
02637       /* No sprite group (or no valid one) found, meaning no graphics associated.
02638        * Use the substitute one instead */
02639       assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
02640       gfx = ats->grf_prop.subst_id;
02641     }
02642     switch (gfx) {
02643       case APT_RADAR_GRASS_FENCE_SW:
02644         t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
02645         break;
02646       case APT_GRASS_FENCE_NE_FLAG:
02647         t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
02648         break;
02649       case APT_RADAR_FENCE_SW:
02650         t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
02651         break;
02652       case APT_RADAR_FENCE_NE:
02653         t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
02654         break;
02655       case APT_GRASS_FENCE_NE_FLAG_2:
02656         t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
02657         break;
02658     }
02659   }
02660 
02661   Owner owner = GetTileOwner(ti->tile);
02662 
02663   PaletteID palette;
02664   if (Company::IsValidID(owner)) {
02665     palette = COMPANY_SPRITE_COLOUR(owner);
02666   } else {
02667     /* Some stations are not owner by a company, namely oil rigs */
02668     palette = PALETTE_TO_GREY;
02669   }
02670 
02671   if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
02672 
02673   /* don't show foundation for docks */
02674   if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02675     if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02676       /* Station has custom foundations.
02677        * Check whether the foundation continues beyond the tile's upper sides. */
02678       uint edge_info = 0;
02679       int z;
02680       Slope slope = GetFoundationPixelSlope(ti->tile, &z);
02681       if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
02682       if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
02683       SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
02684 
02685       if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02686         /* Station provides extended foundations. */
02687 
02688         static const uint8 foundation_parts[] = {
02689           0, 0, 0, 0, // Invalid,  Invalid,   Invalid,   SLOPE_SW
02690           0, 1, 2, 3, // Invalid,  SLOPE_EW,  SLOPE_SE,  SLOPE_WSE
02691           0, 4, 5, 6, // Invalid,  SLOPE_NW,  SLOPE_NS,  SLOPE_NWS
02692           7, 8, 9     // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
02693         };
02694 
02695         AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02696       } else {
02697         /* Draw simple foundations, built up from 8 possible foundation sprites. */
02698 
02699         /* Each set bit represents one of the eight composite sprites to be drawn.
02700          * 'Invalid' entries will not drawn but are included for completeness. */
02701         static const uint8 composite_foundation_parts[] = {
02702           /* Invalid  (00000000), Invalid   (11010001), Invalid   (11100100), SLOPE_SW  (11100000) */
02703              0x00,                0xD1,                 0xE4,                 0xE0,
02704           /* Invalid  (11001010), SLOPE_EW  (11001001), SLOPE_SE  (11000100), SLOPE_WSE (11000000) */
02705              0xCA,                0xC9,                 0xC4,                 0xC0,
02706           /* Invalid  (11010010), SLOPE_NW  (10010001), SLOPE_NS  (11100100), SLOPE_NWS (10100000) */
02707              0xD2,                0x91,                 0xE4,                 0xA0,
02708           /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
02709              0x4A,                0x09,                 0x44
02710         };
02711 
02712         uint8 parts = composite_foundation_parts[ti->tileh];
02713 
02714         /* If foundations continue beyond the tile's upper sides then
02715          * mask out the last two pieces. */
02716         if (HasBit(edge_info, 0)) ClrBit(parts, 6);
02717         if (HasBit(edge_info, 1)) ClrBit(parts, 7);
02718 
02719         if (parts == 0) {
02720           /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
02721            * correct offset for the childsprites.
02722            * So, draw the (completely empty) sprite of the default foundations. */
02723           goto draw_default_foundation;
02724         }
02725 
02726         StartSpriteCombine();
02727         for (int i = 0; i < 8; i++) {
02728           if (HasBit(parts, i)) {
02729             AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02730           }
02731         }
02732         EndSpriteCombine();
02733       }
02734 
02735       OffsetGroundSprite(31, 1);
02736       ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02737     } else {
02738 draw_default_foundation:
02739       DrawFoundation(ti, FOUNDATION_LEVELED);
02740     }
02741   }
02742 
02743   if (IsBuoy(ti->tile)) {
02744     DrawWaterClassGround(ti);
02745     SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
02746     if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
02747   } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
02748     if (ti->tileh == SLOPE_FLAT) {
02749       DrawWaterClassGround(ti);
02750     } else {
02751       assert(IsDock(ti->tile));
02752       TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02753       WaterClass wc = GetWaterClass(water_tile);
02754       if (wc == WATER_CLASS_SEA) {
02755         DrawShoreTile(ti->tileh);
02756       } else {
02757         DrawClearLandTile(ti, 3);
02758       }
02759     }
02760   } else {
02761     if (layout != NULL) {
02762       /* Sprite layout which needs preprocessing */
02763       bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
02764       uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
02765       uint8 var10;
02766       FOR_EACH_SET_BIT(var10, var10_values) {
02767         uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
02768         layout->ProcessRegisters(var10, var10_relocation, separate_ground);
02769       }
02770       tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
02771       t = &tmp_rail_layout;
02772       total_offset = 0;
02773     } else if (statspec != NULL) {
02774       /* Simple sprite layout */
02775       ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
02776       if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
02777         ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
02778       }
02779       ground_relocation += rti->fallback_railtype;
02780     }
02781 
02782     SpriteID image = t->ground.sprite;
02783     PaletteID pal  = t->ground.pal;
02784     if (rti != NULL && rti->UsesOverlay() && (image == SPR_RAIL_TRACK_X || image == SPR_RAIL_TRACK_Y)) {
02785       SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
02786       DrawGroundSprite(SPR_FLAT_GRASS_TILE, PAL_NONE);
02787       DrawGroundSprite(ground + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE);
02788 
02789       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
02790         SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
02791         DrawGroundSprite(overlay + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PALETTE_CRASH);
02792       }
02793     } else {
02794       image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
02795       if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
02796       DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02797 
02798       /* PBS debugging, draw reserved tracks darker */
02799       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02800         const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02801         DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02802       }
02803     }
02804   }
02805 
02806   if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
02807 
02808   if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02809     Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02810     DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02811     DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02812   }
02813 
02814   if (IsRailWaypoint(ti->tile)) {
02815     /* Don't offset the waypoint graphics; they're always the same. */
02816     total_offset = 0;
02817   }
02818 
02819   DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02820 }
02821 
02822 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02823 {
02824   int32 total_offset = 0;
02825   PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02826   const DrawTileSprites *t = GetStationTileLayout(st, image);
02827   const RailtypeInfo *rti = NULL;
02828 
02829   if (railtype != INVALID_RAILTYPE) {
02830     rti = GetRailTypeInfo(railtype);
02831     total_offset = rti->GetRailtypeSpriteOffset();
02832   }
02833 
02834   SpriteID img = t->ground.sprite;
02835   if ((img == SPR_RAIL_TRACK_X || img == SPR_RAIL_TRACK_Y) && rti->UsesOverlay()) {
02836     SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
02837     DrawSprite(SPR_FLAT_GRASS_TILE, PAL_NONE, x, y);
02838     DrawSprite(ground + (img == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE, x, y);
02839   } else {
02840     DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02841   }
02842 
02843   if (roadtype == ROADTYPE_TRAM) {
02844     DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02845   }
02846 
02847   /* Default waypoint has no railtype specific sprites */
02848   DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02849 }
02850 
02851 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
02852 {
02853   return GetTileMaxPixelZ(tile);
02854 }
02855 
02856 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02857 {
02858   return FlatteningFoundation(tileh);
02859 }
02860 
02861 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02862 {
02863   td->owner[0] = GetTileOwner(tile);
02864   if (IsDriveThroughStopTile(tile)) {
02865     Owner road_owner = INVALID_OWNER;
02866     Owner tram_owner = INVALID_OWNER;
02867     RoadTypes rts = GetRoadTypes(tile);
02868     if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02869     if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02870 
02871     /* Is there a mix of owners? */
02872     if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02873         (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02874       uint i = 1;
02875       if (road_owner != INVALID_OWNER) {
02876         td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02877         td->owner[i] = road_owner;
02878         i++;
02879       }
02880       if (tram_owner != INVALID_OWNER) {
02881         td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02882         td->owner[i] = tram_owner;
02883       }
02884     }
02885   }
02886   td->build_date = BaseStation::GetByTile(tile)->build_date;
02887 
02888   if (HasStationTileRail(tile)) {
02889     const StationSpec *spec = GetStationSpec(tile);
02890 
02891     if (spec != NULL) {
02892       td->station_class = StationClass::GetName(spec->cls_id);
02893       td->station_name  = spec->name;
02894 
02895       if (spec->grf_prop.grffile != NULL) {
02896         const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
02897         td->grf = gc->GetName();
02898       }
02899     }
02900 
02901     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
02902     td->rail_speed = rti->max_speed;
02903   }
02904 
02905   if (IsAirport(tile)) {
02906     const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
02907     td->airport_class = AirportClass::GetName(as->cls_id);
02908     td->airport_name = as->name;
02909 
02910     const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
02911     td->airport_tile_name = ats->name;
02912 
02913     if (as->grf_prop.grffile != NULL) {
02914       const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
02915       td->grf = gc->GetName();
02916     } else if (ats->grf_prop.grffile != NULL) {
02917       const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
02918       td->grf = gc->GetName();
02919     }
02920   }
02921 
02922   StringID str;
02923   switch (GetStationType(tile)) {
02924     default: NOT_REACHED();
02925     case STATION_RAIL:     str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
02926     case STATION_AIRPORT:
02927       str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
02928       break;
02929     case STATION_TRUCK:    str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
02930     case STATION_BUS:      str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
02931     case STATION_OILRIG:   str = STR_INDUSTRY_NAME_OIL_RIG; break;
02932     case STATION_DOCK:     str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
02933     case STATION_BUOY:     str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
02934     case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
02935   }
02936   td->str = str;
02937 }
02938 
02939 
02940 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
02941 {
02942   TrackBits trackbits = TRACK_BIT_NONE;
02943 
02944   switch (mode) {
02945     case TRANSPORT_RAIL:
02946       if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
02947         trackbits = TrackToTrackBits(GetRailStationTrack(tile));
02948       }
02949       break;
02950 
02951     case TRANSPORT_WATER:
02952       /* buoy is coded as a station, it is always on open water */
02953       if (IsBuoy(tile)) {
02954         trackbits = TRACK_BIT_ALL;
02955         /* remove tracks that connect NE map edge */
02956         if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
02957         /* remove tracks that connect NW map edge */
02958         if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
02959       }
02960       break;
02961 
02962     case TRANSPORT_ROAD:
02963       if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
02964         DiagDirection dir = GetRoadStopDir(tile);
02965         Axis axis = DiagDirToAxis(dir);
02966 
02967         if (side != INVALID_DIAGDIR) {
02968           if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
02969         }
02970 
02971         trackbits = AxisToTrackBits(axis);
02972       }
02973       break;
02974 
02975     default:
02976       break;
02977   }
02978 
02979   return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
02980 }
02981 
02982 
02983 static void TileLoop_Station(TileIndex tile)
02984 {
02985   /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
02986    * hardcoded.....not good */
02987   switch (GetStationType(tile)) {
02988     case STATION_AIRPORT:
02989       AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
02990       break;
02991 
02992     case STATION_DOCK:
02993       if (GetTileSlope(tile) != SLOPE_FLAT) break; // only handle water part
02994       /* FALL THROUGH */
02995     case STATION_OILRIG: //(station part)
02996     case STATION_BUOY:
02997       TileLoop_Water(tile);
02998       break;
02999 
03000     default: break;
03001   }
03002 }
03003 
03004 
03005 static void AnimateTile_Station(TileIndex tile)
03006 {
03007   if (HasStationRail(tile)) {
03008     AnimateStationTile(tile);
03009     return;
03010   }
03011 
03012   if (IsAirport(tile)) {
03013     AnimateAirportTile(tile);
03014   }
03015 }
03016 
03017 
03018 static bool ClickTile_Station(TileIndex tile)
03019 {
03020   const BaseStation *bst = BaseStation::GetByTile(tile);
03021 
03022   if (bst->facilities & FACIL_WAYPOINT) {
03023     ShowWaypointWindow(Waypoint::From(bst));
03024   } else if (IsHangar(tile)) {
03025     const Station *st = Station::From(bst);
03026     ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
03027   } else {
03028     ShowStationViewWindow(bst->index);
03029   }
03030   return true;
03031 }
03032 
03033 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
03034 {
03035   if (v->type == VEH_TRAIN) {
03036     StationID station_id = GetStationIndex(tile);
03037     if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
03038     if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
03039 
03040     int station_ahead;
03041     int station_length;
03042     int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
03043 
03044     /* Stop whenever that amount of station ahead + the distance from the
03045      * begin of the platform to the stop location is longer than the length
03046      * of the platform. Station ahead 'includes' the current tile where the
03047      * vehicle is on, so we need to substract that. */
03048     if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
03049 
03050     DiagDirection dir = DirToDiagDir(v->direction);
03051 
03052     x &= 0xF;
03053     y &= 0xF;
03054 
03055     if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
03056     if (y == TILE_SIZE / 2) {
03057       if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
03058       stop &= TILE_SIZE - 1;
03059 
03060       if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
03061       if (x < stop) {
03062         uint16 spd;
03063 
03064         v->vehstatus |= VS_TRAIN_SLOWING;
03065         spd = max(0, (stop - x) * 20 - 15);
03066         if (spd < v->cur_speed) v->cur_speed = spd;
03067       }
03068     }
03069   } else if (v->type == VEH_ROAD) {
03070     RoadVehicle *rv = RoadVehicle::From(v);
03071     if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
03072       if (IsRoadStop(tile) && rv->IsFrontEngine()) {
03073         /* Attempt to allocate a parking bay in a road stop */
03074         return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
03075       }
03076     }
03077   }
03078 
03079   return VETSB_CONTINUE;
03080 }
03081 
03086 void TriggerWatchedCargoCallbacks(Station *st)
03087 {
03088   /* Collect cargoes accepted since the last big tick. */
03089   uint cargoes = 0;
03090   for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
03091     if (HasBit(st->goods[cid].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
03092   }
03093 
03094   /* Anything to do? */
03095   if (cargoes == 0) return;
03096 
03097   /* Loop over all houses in the catchment. */
03098   Rect r = st->GetCatchmentRect();
03099   TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
03100   TILE_AREA_LOOP(tile, ta) {
03101     if (IsTileType(tile, MP_HOUSE)) {
03102       WatchedCargoCallback(tile, cargoes);
03103     }
03104   }
03105 }
03106 
03113 static bool StationHandleBigTick(BaseStation *st)
03114 {
03115   if (!st->IsInUse()) {
03116     if (++st->delete_ctr >= 8) delete st;
03117     return false;
03118   }
03119 
03120   if (Station::IsExpected(st)) {
03121     TriggerWatchedCargoCallbacks(Station::From(st));
03122 
03123     for (CargoID i = 0; i < NUM_CARGO; i++) {
03124       ClrBit(Station::From(st)->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
03125     }
03126   }
03127 
03128 
03129   if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
03130 
03131   return true;
03132 }
03133 
03134 static inline void byte_inc_sat(byte *p)
03135 {
03136   byte b = *p + 1;
03137   if (b != 0) *p = b;
03138 }
03139 
03140 static void UpdateStationRating(Station *st)
03141 {
03142   bool waiting_changed = false;
03143 
03144   byte_inc_sat(&st->time_since_load);
03145   byte_inc_sat(&st->time_since_unload);
03146 
03147   const CargoSpec *cs;
03148   FOR_ALL_CARGOSPECS(cs) {
03149     GoodsEntry *ge = &st->goods[cs->Index()];
03150     /* Slowly increase the rating back to his original level in the case we
03151      *  didn't deliver cargo yet to this station. This happens when a bribe
03152      *  failed while you didn't moved that cargo yet to a station. */
03153     if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP) && ge->rating < INITIAL_STATION_RATING) {
03154       ge->rating++;
03155     }
03156 
03157     /* Only change the rating if we are moving this cargo */
03158     if (HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) {
03159       byte_inc_sat(&ge->days_since_pickup);
03160 
03161       bool skip = false;
03162       int rating = 0;
03163       uint waiting = ge->cargo.Count();
03164 
03165       if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
03166         /* Perform custom station rating. If it succeeds the speed, days in transit and
03167          * waiting cargo ratings must not be executed. */
03168 
03169         /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
03170         uint last_speed = ge->last_speed;
03171         if (last_speed == 0) last_speed = 0xFF;
03172 
03173         uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(waiting, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
03174         /* Convert to the 'old' vehicle types */
03175         uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
03176         uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
03177         if (callback != CALLBACK_FAILED) {
03178           skip = true;
03179           rating = GB(callback, 0, 14);
03180 
03181           /* Simulate a 15 bit signed value */
03182           if (HasBit(callback, 14)) rating -= 0x4000;
03183         }
03184       }
03185 
03186       if (!skip) {
03187         int b = ge->last_speed - 85;
03188         if (b >= 0) rating += b >> 2;
03189 
03190         byte days = ge->days_since_pickup;
03191         if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
03192         (days > 21) ||
03193         (rating += 25, days > 12) ||
03194         (rating += 25, days > 6) ||
03195         (rating += 45, days > 3) ||
03196         (rating += 35, true);
03197 
03198         (rating -= 90, waiting > 1500) ||
03199         (rating += 55, waiting > 1000) ||
03200         (rating += 35, waiting > 600) ||
03201         (rating += 10, waiting > 300) ||
03202         (rating += 20, waiting > 100) ||
03203         (rating += 10, true);
03204       }
03205 
03206       if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
03207 
03208       byte age = ge->last_age;
03209       (age >= 3) ||
03210       (rating += 10, age >= 2) ||
03211       (rating += 10, age >= 1) ||
03212       (rating += 13, true);
03213 
03214       {
03215         int or_ = ge->rating; // old rating
03216 
03217         /* only modify rating in steps of -2, -1, 0, 1 or 2 */
03218         ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
03219 
03220         /* if rating is <= 64 and more than 200 items waiting,
03221          * remove some random amount of goods from the station */
03222         if (rating <= 64 && waiting >= 200) {
03223           int dec = Random() & 0x1F;
03224           if (waiting < 400) dec &= 7;
03225           waiting -= dec + 1;
03226           waiting_changed = true;
03227         }
03228 
03229         /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
03230         if (rating <= 127 && waiting != 0) {
03231           uint32 r = Random();
03232           if (rating <= (int)GB(r, 0, 7)) {
03233             /* Need to have int, otherwise it will just overflow etc. */
03234             waiting = max((int)waiting - (int)GB(r, 8, 2) - 1, 0);
03235             waiting_changed = true;
03236           }
03237         }
03238 
03239         /* At some point we really must cap the cargo. Previously this
03240          * was a strict 4095, but now we'll have a less strict, but
03241          * increasingly agressive truncation of the amount of cargo. */
03242         static const uint WAITING_CARGO_THRESHOLD  = 1 << 12;
03243         static const uint WAITING_CARGO_CUT_FACTOR = 1 <<  6;
03244         static const uint MAX_WAITING_CARGO        = 1 << 15;
03245 
03246         if (waiting > WAITING_CARGO_THRESHOLD) {
03247           uint difference = waiting - WAITING_CARGO_THRESHOLD;
03248           waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
03249 
03250           waiting = min(waiting, MAX_WAITING_CARGO);
03251           waiting_changed = true;
03252         }
03253 
03254         if (waiting_changed) ge->cargo.Truncate(waiting);
03255       }
03256     }
03257   }
03258 
03259   StationID index = st->index;
03260   if (waiting_changed) {
03261     SetWindowDirty(WC_STATION_VIEW, index); // update whole window
03262   } else {
03263     SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
03264   }
03265 }
03266 
03267 /* called for every station each tick */
03268 static void StationHandleSmallTick(BaseStation *st)
03269 {
03270   if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
03271 
03272   byte b = st->delete_ctr + 1;
03273   if (b >= STATION_RATING_TICKS) b = 0;
03274   st->delete_ctr = b;
03275 
03276   if (b == 0) UpdateStationRating(Station::From(st));
03277 }
03278 
03279 void OnTick_Station()
03280 {
03281   if (_game_mode == GM_EDITOR) return;
03282 
03283   BaseStation *st;
03284   FOR_ALL_BASE_STATIONS(st) {
03285     StationHandleSmallTick(st);
03286 
03287     /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
03288      * Station index is included so that triggers are not all done
03289      * at the same time. */
03290     if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
03291       /* Stop processing this station if it was deleted */
03292       if (!StationHandleBigTick(st)) continue;
03293       TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
03294       if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
03295     }
03296   }
03297 }
03298 
03300 void StationMonthlyLoop()
03301 {
03302   Station *st;
03303 
03304   FOR_ALL_STATIONS(st) {
03305     for (CargoID i = 0; i < NUM_CARGO; i++) {
03306       GoodsEntry *ge = &st->goods[i];
03307       SB(ge->acceptance_pickup, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH, 1));
03308       ClrBit(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
03309     }
03310   }
03311 }
03312 
03313 
03314 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
03315 {
03316   Station *st;
03317 
03318   FOR_ALL_STATIONS(st) {
03319     if (st->owner == owner &&
03320         DistanceManhattan(tile, st->xy) <= radius) {
03321       for (CargoID i = 0; i < NUM_CARGO; i++) {
03322         GoodsEntry *ge = &st->goods[i];
03323 
03324         if (ge->acceptance_pickup != 0) {
03325           ge->rating = Clamp(ge->rating + amount, 0, 255);
03326         }
03327       }
03328     }
03329   }
03330 }
03331 
03332 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
03333 {
03334   /* We can't allocate a CargoPacket? Then don't do anything
03335    * at all; i.e. just discard the incoming cargo. */
03336   if (!CargoPacket::CanAllocateItem()) return 0;
03337 
03338   GoodsEntry &ge = st->goods[type];
03339   amount += ge.amount_fract;
03340   ge.amount_fract = GB(amount, 0, 8);
03341 
03342   amount >>= 8;
03343   /* No new "real" cargo item yet. */
03344   if (amount == 0) return 0;
03345 
03346   ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id));
03347 
03348   if (!HasBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP)) {
03349     InvalidateWindowData(WC_STATION_LIST, st->index);
03350     SetBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP);
03351   }
03352 
03353   TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
03354   AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
03355 
03356   SetWindowDirty(WC_STATION_VIEW, st->index);
03357   st->MarkTilesDirty(true);
03358   return amount;
03359 }
03360 
03361 static bool IsUniqueStationName(const char *name)
03362 {
03363   const Station *st;
03364 
03365   FOR_ALL_STATIONS(st) {
03366     if (st->name != NULL && strcmp(st->name, name) == 0) return false;
03367   }
03368 
03369   return true;
03370 }
03371 
03381 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
03382 {
03383   Station *st = Station::GetIfValid(p1);
03384   if (st == NULL) return CMD_ERROR;
03385 
03386   CommandCost ret = CheckOwnership(st->owner);
03387   if (ret.Failed()) return ret;
03388 
03389   bool reset = StrEmpty(text);
03390 
03391   if (!reset) {
03392     if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
03393     if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
03394   }
03395 
03396   if (flags & DC_EXEC) {
03397     free(st->name);
03398     st->name = reset ? NULL : strdup(text);
03399 
03400     st->UpdateVirtCoord();
03401     InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
03402   }
03403 
03404   return CommandCost();
03405 }
03406 
03413 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
03414 {
03415   /* area to search = producer plus station catchment radius */
03416   uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
03417 
03418   uint x = TileX(location.tile);
03419   uint y = TileY(location.tile);
03420 
03421   uint min_x = (x > max_rad) ? x - max_rad : 0;
03422   uint max_x = x + location.w + max_rad;
03423   uint min_y = (y > max_rad) ? y - max_rad : 0;
03424   uint max_y = y + location.h + max_rad;
03425 
03426   if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
03427   if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
03428   if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
03429   if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
03430 
03431   for (uint cy = min_y; cy < max_y; cy++) {
03432     for (uint cx = min_x; cx < max_x; cx++) {
03433       TileIndex cur_tile = TileXY(cx, cy);
03434       if (!IsTileType(cur_tile, MP_STATION)) continue;
03435 
03436       Station *st = Station::GetByTile(cur_tile);
03437       /* st can be NULL in case of waypoints */
03438       if (st == NULL) continue;
03439 
03440       if (_settings_game.station.modified_catchment) {
03441         int rad = st->GetCatchmentRadius();
03442         int rad_x = cx - x;
03443         int rad_y = cy - y;
03444 
03445         if (rad_x < -rad || rad_x >= rad + location.w) continue;
03446         if (rad_y < -rad || rad_y >= rad + location.h) continue;
03447       }
03448 
03449       /* Insert the station in the set. This will fail if it has
03450        * already been added.
03451        */
03452       stations->Include(st);
03453     }
03454   }
03455 }
03456 
03461 const StationList *StationFinder::GetStations()
03462 {
03463   if (this->tile != INVALID_TILE) {
03464     FindStationsAroundTiles(*this, &this->stations);
03465     this->tile = INVALID_TILE;
03466   }
03467   return &this->stations;
03468 }
03469 
03470 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03471 {
03472   /* Return if nothing to do. Also the rounding below fails for 0. */
03473   if (amount == 0) return 0;
03474 
03475   Station *st1 = NULL;   // Station with best rating
03476   Station *st2 = NULL;   // Second best station
03477   uint best_rating1 = 0; // rating of st1
03478   uint best_rating2 = 0; // rating of st2
03479 
03480   for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03481     Station *st = *st_iter;
03482 
03483     /* Is the station reserved exclusively for somebody else? */
03484     if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03485 
03486     if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
03487 
03488     if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue; // Selectively servicing stations, and not this one
03489 
03490     if (IsCargoInClass(type, CC_PASSENGERS)) {
03491       if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
03492     } else {
03493       if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
03494     }
03495 
03496     /* This station can be used, add it to st1/st2 */
03497     if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03498       st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03499     } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03500       st2 = st; best_rating2 = st->goods[type].rating;
03501     }
03502   }
03503 
03504   /* no stations around at all? */
03505   if (st1 == NULL) return 0;
03506 
03507   /* From now we'll calculate with fractal cargo amounts.
03508    * First determine how much cargo we really have. */
03509   amount *= best_rating1 + 1;
03510 
03511   if (st2 == NULL) {
03512     /* only one station around */
03513     return UpdateStationWaiting(st1, type, amount, source_type, source_id);
03514   }
03515 
03516   /* several stations around, the best two (highest rating) are in st1 and st2 */
03517   assert(st1 != NULL);
03518   assert(st2 != NULL);
03519   assert(best_rating1 != 0 || best_rating2 != 0);
03520 
03521   /* Then determine the amount the worst station gets. We do it this way as the
03522    * best should get a bonus, which in this case is the rounding difference from
03523    * this calculation. In reality that will mean the bonus will be pretty low.
03524    * Nevertheless, the best station should always get the most cargo regardless
03525    * of rounding issues. */
03526   uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
03527   assert(worst_cargo <= (amount - worst_cargo));
03528 
03529   /* And then send the cargo to the stations! */
03530   uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
03531   /* These two UpdateStationWaiting's can't be in the statement as then the order
03532    * of execution would be undefined and that could cause desyncs with callbacks. */
03533   return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
03534 }
03535 
03536 void BuildOilRig(TileIndex tile)
03537 {
03538   if (!Station::CanAllocateItem()) {
03539     DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03540     return;
03541   }
03542 
03543   Station *st = new Station(tile);
03544   st->town = ClosestTownFromTile(tile, UINT_MAX);
03545 
03546   st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03547 
03548   assert(IsTileType(tile, MP_INDUSTRY));
03549   DeleteAnimatedTile(tile);
03550   MakeOilrig(tile, st->index, GetWaterClass(tile));
03551 
03552   st->owner = OWNER_NONE;
03553   st->airport.type = AT_OILRIG;
03554   st->airport.Add(tile);
03555   st->dock_tile = tile;
03556   st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03557   st->build_date = _date;
03558 
03559   st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03560 
03561   for (CargoID j = 0; j < NUM_CARGO; j++) {
03562     st->goods[j].acceptance_pickup = 0;
03563     st->goods[j].days_since_pickup = 255;
03564     st->goods[j].rating = INITIAL_STATION_RATING;
03565     st->goods[j].last_speed = 0;
03566     st->goods[j].last_age = 255;
03567   }
03568 
03569   st->UpdateVirtCoord();
03570   UpdateStationAcceptance(st, false);
03571   st->RecomputeIndustriesNear();
03572 }
03573 
03574 void DeleteOilRig(TileIndex tile)
03575 {
03576   Station *st = Station::GetByTile(tile);
03577 
03578   MakeWaterKeepingClass(tile, OWNER_NONE);
03579 
03580   st->dock_tile = INVALID_TILE;
03581   st->airport.Clear();
03582   st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03583   st->airport.flags = 0;
03584 
03585   st->rect.AfterRemoveTile(st, tile);
03586 
03587   st->UpdateVirtCoord();
03588   st->RecomputeIndustriesNear();
03589   if (!st->IsInUse()) delete st;
03590 }
03591 
03592 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03593 {
03594   if (IsRoadStopTile(tile)) {
03595     for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03596       /* Update all roadtypes, no matter if they are present */
03597       if (GetRoadOwner(tile, rt) == old_owner) {
03598         if (HasTileRoadType(tile, rt)) {
03599           /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
03600           Company::Get(old_owner)->infrastructure.road[rt] -= 2;
03601           if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
03602         }
03603         SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03604       }
03605     }
03606   }
03607 
03608   if (!IsTileOwner(tile, old_owner)) return;
03609 
03610   if (new_owner != INVALID_OWNER) {
03611     /* Update company infrastructure counts. Only do it here
03612      * if the new owner is valid as otherwise the clear
03613      * command will do it for us. No need to dirty windows
03614      * here, we'll redraw the whole screen anyway.*/
03615     Company *old_company = Company::Get(old_owner);
03616     Company *new_company = Company::Get(new_owner);
03617 
03618     /* Update counts for underlying infrastructure. */
03619     switch (GetStationType(tile)) {
03620       case STATION_RAIL:
03621       case STATION_WAYPOINT:
03622         if (!IsStationTileBlocked(tile)) {
03623           old_company->infrastructure.rail[GetRailType(tile)]--;
03624           new_company->infrastructure.rail[GetRailType(tile)]++;
03625         }
03626         break;
03627 
03628       case STATION_BUS:
03629       case STATION_TRUCK:
03630         /* Road stops were already handled above. */
03631         break;
03632 
03633       case STATION_BUOY:
03634       case STATION_DOCK:
03635         if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
03636           old_company->infrastructure.water--;
03637           new_company->infrastructure.water++;
03638         }
03639         break;
03640 
03641       default:
03642         break;
03643     }
03644 
03645     /* Update station tile count. */
03646     if (!IsBuoy(tile) && !IsAirport(tile)) {
03647       old_company->infrastructure.station--;
03648       new_company->infrastructure.station++;
03649     }
03650 
03651     /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
03652     SetTileOwner(tile, new_owner);
03653     InvalidateWindowClassesData(WC_STATION_LIST, 0);
03654   } else {
03655     if (IsDriveThroughStopTile(tile)) {
03656       /* Remove the drive-through road stop */
03657       DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03658       assert(IsTileType(tile, MP_ROAD));
03659       /* Change owner of tile and all roadtypes */
03660       ChangeTileOwner(tile, old_owner, new_owner);
03661     } else {
03662       DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03663       /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
03664        * Update owner of buoy if it was not removed (was in orders).
03665        * Do not update when owned by OWNER_WATER (sea and rivers). */
03666       if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03667     }
03668   }
03669 }
03670 
03679 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03680 {
03681   /* Yeah... water can always remove stops, right? */
03682   if (_current_company == OWNER_WATER) return true;
03683 
03684   RoadTypes rts = GetRoadTypes(tile);
03685   if (HasBit(rts, ROADTYPE_TRAM)) {
03686     Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03687     if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
03688   }
03689   if (HasBit(rts, ROADTYPE_ROAD)) {
03690     Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03691     if (road_owner != OWNER_TOWN) {
03692       if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
03693     } else {
03694       if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
03695     }
03696   }
03697 
03698   return true;
03699 }
03700 
03707 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
03708 {
03709   if (flags & DC_AUTO) {
03710     switch (GetStationType(tile)) {
03711       default: break;
03712       case STATION_RAIL:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
03713       case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
03714       case STATION_AIRPORT:  return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
03715       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);
03716       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);
03717       case STATION_BUOY:     return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
03718       case STATION_DOCK:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
03719       case STATION_OILRIG:
03720         SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
03721         return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
03722     }
03723   }
03724 
03725   switch (GetStationType(tile)) {
03726     case STATION_RAIL:     return RemoveRailStation(tile, flags);
03727     case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
03728     case STATION_AIRPORT:  return RemoveAirport(tile, flags);
03729     case STATION_TRUCK:
03730       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03731         return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03732       }
03733       return RemoveRoadStop(tile, flags);
03734     case STATION_BUS:
03735       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03736         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03737       }
03738       return RemoveRoadStop(tile, flags);
03739     case STATION_BUOY:     return RemoveBuoy(tile, flags);
03740     case STATION_DOCK:     return RemoveDock(tile, flags);
03741     default: break;
03742   }
03743 
03744   return CMD_ERROR;
03745 }
03746 
03747 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
03748 {
03749   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
03750     /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
03751      *       TTDP does not call it.
03752      */
03753     if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
03754       switch (GetStationType(tile)) {
03755         case STATION_WAYPOINT:
03756         case STATION_RAIL: {
03757           DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
03758           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03759           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03760           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03761         }
03762 
03763         case STATION_AIRPORT:
03764           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03765 
03766         case STATION_TRUCK:
03767         case STATION_BUS: {
03768           DiagDirection direction = GetRoadStopDir(tile);
03769           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03770           if (IsDriveThroughStopTile(tile)) {
03771             if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03772           }
03773           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03774         }
03775 
03776         default: break;
03777       }
03778     }
03779   }
03780   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03781 }
03782 
03783 
03784 extern const TileTypeProcs _tile_type_station_procs = {
03785   DrawTile_Station,           // draw_tile_proc
03786   GetSlopePixelZ_Station,     // get_slope_z_proc
03787   ClearTile_Station,          // clear_tile_proc
03788   NULL,                       // add_accepted_cargo_proc
03789   GetTileDesc_Station,        // get_tile_desc_proc
03790   GetTileTrackStatus_Station, // get_tile_track_status_proc
03791   ClickTile_Station,          // click_tile_proc
03792   AnimateTile_Station,        // animate_tile_proc
03793   TileLoop_Station,           // tile_loop_proc
03794   ChangeTileOwner_Station,    // change_tile_owner_proc
03795   NULL,                       // add_produced_cargo_proc
03796   VehicleEnter_Station,       // vehicle_enter_tile_proc
03797   GetFoundation_Station,      // get_foundation_proc
03798   TerraformTile_Station,      // terraform_tile_proc
03799 };