station_cmd.cpp

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

Generated on Sun Jan 9 16:02:02 2011 for OpenTTD by  doxygen 1.6.1