station_cmd.cpp

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