station_cmd.cpp

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