station_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: station_cmd.cpp 18866 2010-01-18 22:57:21Z 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 "landscape.h"
00017 #include "viewport_func.h"
00018 #include "command_func.h"
00019 #include "town.h"
00020 #include "news_func.h"
00021 #include "train.h"
00022 #include "roadveh.h"
00023 #include "industry.h"
00024 #include "newgrf_cargo.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 "variables.h"
00029 #include "autoslope.h"
00030 #include "water.h"
00031 #include "station_gui.h"
00032 #include "strings_func.h"
00033 #include "functions.h"
00034 #include "window_func.h"
00035 #include "date_func.h"
00036 #include "vehicle_func.h"
00037 #include "string_func.h"
00038 #include "animated_tile_func.h"
00039 #include "elrail_func.h"
00040 #include "station_base.h"
00041 #include "roadstop_base.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 "newgrf.h"
00049 
00050 #include "table/strings.h"
00051 
00058 bool IsHangar(TileIndex t)
00059 {
00060   assert(IsTileType(t, MP_STATION));
00061 
00062   /* If the tile isn't an airport there's no chance it's a hangar. */
00063   if (!IsAirport(t)) return false;
00064 
00065   const Station *st = Station::GetByTile(t);
00066   const AirportSpec *as = st->GetAirportSpec();
00067 
00068   for (uint i = 0; i < as->nof_depots; i++) {
00069     if (st->GetHangarTile(i) == t) return true;
00070   }
00071 
00072   return false;
00073 }
00074 
00082 template <class T>
00083 bool GetStationAround(TileArea ta, StationID closest_station, T **st)
00084 {
00085   /* check around to see if there's any stations there */
00086   TILE_LOOP(tile_cur, ta.w + 2, ta.h + 2, ta.tile - TileDiffXY(1, 1)) {
00087     if (IsTileType(tile_cur, MP_STATION)) {
00088       StationID t = GetStationIndex(tile_cur);
00089 
00090       if (closest_station == INVALID_STATION) {
00091         if (T::IsValidID(t)) closest_station = t;
00092       } else if (closest_station != t) {
00093         _error_message = STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING;
00094         return false;
00095       }
00096     }
00097   }
00098   *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
00099   return true;
00100 }
00101 
00107 typedef bool (*CMSAMatcher)(TileIndex tile);
00108 
00115 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
00116 {
00117   int num = 0;
00118 
00119   for (int dx = -3; dx <= 3; dx++) {
00120     for (int dy = -3; dy <= 3; dy++) {
00121       TileIndex t = TileAddWrap(tile, dx, dy);
00122       if (t != INVALID_TILE && cmp(t)) num++;
00123     }
00124   }
00125 
00126   return num;
00127 }
00128 
00134 static bool CMSAMine(TileIndex tile)
00135 {
00136   /* No industry */
00137   if (!IsTileType(tile, MP_INDUSTRY)) return false;
00138 
00139   const Industry *ind = Industry::GetByTile(tile);
00140 
00141   /* No extractive industry */
00142   if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
00143 
00144   for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00145     /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
00146      * Also the production of passengers and mail is ignored. */
00147     if (ind->produced_cargo[i] != CT_INVALID &&
00148         (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
00149       return true;
00150     }
00151   }
00152 
00153   return false;
00154 }
00155 
00161 static bool CMSAWater(TileIndex tile)
00162 {
00163   return IsTileType(tile, MP_WATER) && IsWater(tile);
00164 }
00165 
00171 static bool CMSATree(TileIndex tile)
00172 {
00173   return IsTileType(tile, MP_TREES);
00174 }
00175 
00181 static bool CMSAForest(TileIndex tile)
00182 {
00183   /* No industry */
00184   if (!IsTileType(tile, MP_INDUSTRY)) return false;
00185 
00186   const Industry *ind = Industry::GetByTile(tile);
00187 
00188   /* No extractive industry */
00189   if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
00190 
00191   for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00192     /* The industry produces wood. */
00193     if (ind->produced_cargo[i] != CT_INVALID && CargoSpec::Get(ind->produced_cargo[i])->label == 'WOOD') return true;
00194   }
00195 
00196   return false;
00197 }
00198 
00199 #define M(x) ((x) - STR_SV_STNAME)
00200 
00201 enum StationNaming {
00202   STATIONNAMING_RAIL,
00203   STATIONNAMING_ROAD,
00204   STATIONNAMING_AIRPORT,
00205   STATIONNAMING_OILRIG,
00206   STATIONNAMING_DOCK,
00207   STATIONNAMING_HELIPORT,
00208 };
00209 
00211 struct StationNameInformation {
00212   uint32 free_names; 
00213   bool *indtypes;    
00214 };
00215 
00224 static bool FindNearIndustryName(TileIndex tile, void *user_data)
00225 {
00226   /* All already found industry types */
00227   StationNameInformation *sni = (StationNameInformation*)user_data;
00228   if (!IsTileType(tile, MP_INDUSTRY)) return false;
00229 
00230   /* If the station name is undefined it means that it doesn't name a station */
00231   IndustryType indtype = GetIndustryType(tile);
00232   if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
00233 
00234   /* In all cases if an industry that provides a name is found two of
00235    * the standard names will be disabled. */
00236   sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
00237   return !sni->indtypes[indtype];
00238 }
00239 
00240 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
00241 {
00242   static const uint32 _gen_station_name_bits[] = {
00243     0,                                       // STATIONNAMING_RAIL
00244     0,                                       // STATIONNAMING_ROAD
00245     1U << M(STR_SV_STNAME_AIRPORT),          // STATIONNAMING_AIRPORT
00246     1U << M(STR_SV_STNAME_OILFIELD),         // STATIONNAMING_OILRIG
00247     1U << M(STR_SV_STNAME_DOCKS),            // STATIONNAMING_DOCK
00248     1U << M(STR_SV_STNAME_HELIPORT),         // STATIONNAMING_HELIPORT
00249   };
00250 
00251   const Town *t = st->town;
00252   uint32 free_names = UINT32_MAX;
00253 
00254   bool indtypes[NUM_INDUSTRYTYPES];
00255   memset(indtypes, 0, sizeof(indtypes));
00256 
00257   const Station *s;
00258   FOR_ALL_STATIONS(s) {
00259     if (s != st && s->town == t) {
00260       if (s->indtype != IT_INVALID) {
00261         indtypes[s->indtype] = true;
00262         continue;
00263       }
00264       uint str = M(s->string_id);
00265       if (str <= 0x20) {
00266         if (str == M(STR_SV_STNAME_FOREST)) {
00267           str = M(STR_SV_STNAME_WOODS);
00268         }
00269         ClrBit(free_names, str);
00270       }
00271     }
00272   }
00273 
00274   TileIndex indtile = tile;
00275   StationNameInformation sni = { free_names, indtypes };
00276   if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
00277     /* An industry has been found nearby */
00278     IndustryType indtype = GetIndustryType(indtile);
00279     const IndustrySpec *indsp = GetIndustrySpec(indtype);
00280     /* STR_NULL means it only disables oil rig/mines */
00281     if (indsp->station_name != STR_NULL) {
00282       st->indtype = indtype;
00283       return STR_SV_STNAME_FALLBACK;
00284     }
00285   }
00286 
00287   /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
00288   free_names = sni.free_names;
00289 
00290   /* check default names */
00291   uint32 tmp = free_names & _gen_station_name_bits[name_class];
00292   if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
00293 
00294   /* check mine? */
00295   if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
00296     if (CountMapSquareAround(tile, CMSAMine) >= 2) {
00297       return STR_SV_STNAME_MINES;
00298     }
00299   }
00300 
00301   /* check close enough to town to get central as name? */
00302   if (DistanceMax(tile, t->xy) < 8) {
00303     if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
00304 
00305     if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
00306   }
00307 
00308   /* Check lakeside */
00309   if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
00310       DistanceFromEdge(tile) < 20 &&
00311       CountMapSquareAround(tile, CMSAWater) >= 5) {
00312     return STR_SV_STNAME_LAKESIDE;
00313   }
00314 
00315   /* Check woods */
00316   if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
00317         CountMapSquareAround(tile, CMSATree) >= 8 ||
00318         CountMapSquareAround(tile, CMSAForest) >= 2)
00319       ) {
00320     return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
00321   }
00322 
00323   /* check elevation compared to town */
00324   uint z = GetTileZ(tile);
00325   uint z2 = GetTileZ(t->xy);
00326   if (z < z2) {
00327     if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
00328   } else if (z > z2) {
00329     if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
00330   }
00331 
00332   /* check direction compared to town */
00333   static const int8 _direction_and_table[] = {
00334     ~( (1 << M(STR_SV_STNAME_WEST))  | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00335     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00336     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00337     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
00338   };
00339 
00340   free_names &= _direction_and_table[
00341     (TileX(tile) < TileX(t->xy)) +
00342     (TileY(tile) < TileY(t->xy)) * 2];
00343 
00344   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));
00345   return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
00346 }
00347 #undef M
00348 
00354 static Station *GetClosestDeletedStation(TileIndex tile)
00355 {
00356   uint threshold = 8;
00357   Station *best_station = NULL;
00358   Station *st;
00359 
00360   FOR_ALL_STATIONS(st) {
00361     if (!st->IsInUse() && st->owner == _current_company) {
00362       uint cur_dist = DistanceManhattan(tile, st->xy);
00363 
00364       if (cur_dist < threshold) {
00365         threshold = cur_dist;
00366         best_station = st;
00367       }
00368     }
00369   }
00370 
00371   return best_station;
00372 }
00373 
00374 
00375 void Station::GetTileArea(TileArea *ta, StationType type) const
00376 {
00377   switch (type) {
00378     case STATION_RAIL:
00379       *ta = this->train_station;
00380       return;
00381 
00382     case STATION_AIRPORT:
00383       ta->tile = this->airport_tile;
00384       ta->w    = this->GetAirportSpec()->size_x;
00385       ta->h    = this->GetAirportSpec()->size_y;
00386       return;
00387 
00388     case STATION_TRUCK:
00389       *ta = this->truck_station;
00390       return;
00391 
00392     case STATION_BUS:
00393       *ta = this->bus_station;
00394       return;
00395 
00396     case STATION_DOCK:
00397     case STATION_OILRIG:
00398       ta->tile = this->dock_tile;
00399       break;
00400 
00401     default: NOT_REACHED();
00402   }
00403 
00404   ta->w = 1;
00405   ta->h = 1;
00406 }
00407 
00411 void Station::UpdateVirtCoord()
00412 {
00413   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00414 
00415   pt.y -= 32;
00416   if ((this->facilities & FACIL_AIRPORT) && this->airport_type == AT_OILRIG) pt.y -= 16;
00417 
00418   SetDParam(0, this->index);
00419   SetDParam(1, this->facilities);
00420   this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
00421 
00422   SetWindowDirty(WC_STATION_VIEW, this->index);
00423 }
00424 
00426 void UpdateAllStationVirtCoords()
00427 {
00428   BaseStation *st;
00429 
00430   FOR_ALL_BASE_STATIONS(st) {
00431     st->UpdateVirtCoord();
00432   }
00433 }
00434 
00439 static uint GetAcceptanceMask(const Station *st)
00440 {
00441   uint mask = 0;
00442 
00443   for (CargoID i = 0; i < NUM_CARGO; i++) {
00444     if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) mask |= 1 << i;
00445   }
00446   return mask;
00447 }
00448 
00452 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
00453 {
00454   for (uint i = 0; i < num_items; i++) {
00455     SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
00456   }
00457 
00458   SetDParam(0, st->index);
00459   AddNewsItem(msg, NS_ACCEPTANCE, NR_STATION, st->index);
00460 }
00461 
00469 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
00470 {
00471   CargoArray produced;
00472 
00473   int x = TileX(tile);
00474   int y = TileY(tile);
00475 
00476   /* expand the region by rad tiles on each side
00477    * while making sure that we remain inside the board. */
00478   int x2 = min(x + w + rad, MapSizeX());
00479   int x1 = max(x - rad, 0);
00480 
00481   int y2 = min(y + h + rad, MapSizeY());
00482   int y1 = max(y - rad, 0);
00483 
00484   assert(x1 < x2);
00485   assert(y1 < y2);
00486   assert(w > 0);
00487   assert(h > 0);
00488 
00489   TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
00490 
00491   /* Loop over all tiles to get the produced cargo of
00492    * everything except industries */
00493   TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
00494 
00495   /* Loop over the industries. They produce cargo for
00496    * anything that is within 'rad' from their bounding
00497    * box. As such if you have e.g. a oil well the tile
00498    * area loop might not hit an industry tile while
00499    * the industry would produce cargo for the station.
00500    */
00501   const Industry *i;
00502   FOR_ALL_INDUSTRIES(i) {
00503     if (!ta.Intersects(i->location)) continue;
00504 
00505     for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00506       CargoID cargo = i->produced_cargo[j];
00507       if (cargo != CT_INVALID) produced[cargo]++;
00508     }
00509   }
00510 
00511   return produced;
00512 }
00513 
00522 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
00523 {
00524   CargoArray acceptance;
00525   if (always_accepted != NULL) *always_accepted = 0;
00526 
00527   int x = TileX(tile);
00528   int y = TileY(tile);
00529 
00530   /* expand the region by rad tiles on each side
00531    * while making sure that we remain inside the board. */
00532   int x2 = min(x + w + rad, MapSizeX());
00533   int y2 = min(y + h + rad, MapSizeY());
00534   int x1 = max(x - rad, 0);
00535   int y1 = max(y - rad, 0);
00536 
00537   assert(x1 < x2);
00538   assert(y1 < y2);
00539   assert(w > 0);
00540   assert(h > 0);
00541 
00542   for (int yc = y1; yc != y2; yc++) {
00543     for (int xc = x1; xc != x2; xc++) {
00544       TileIndex tile = TileXY(xc, yc);
00545       AddAcceptedCargo(tile, acceptance, always_accepted);
00546     }
00547   }
00548 
00549   return acceptance;
00550 }
00551 
00556 void UpdateStationAcceptance(Station *st, bool show_msg)
00557 {
00558   /* old accepted goods types */
00559   uint old_acc = GetAcceptanceMask(st);
00560 
00561   /* And retrieve the acceptance. */
00562   CargoArray acceptance;
00563   if (!st->rect.IsEmpty()) {
00564     acceptance = GetAcceptanceAroundTiles(
00565       TileXY(st->rect.left, st->rect.top),
00566       st->rect.right  - st->rect.left + 1,
00567       st->rect.bottom - st->rect.top  + 1,
00568       st->GetCatchmentRadius(),
00569       &st->always_accepted
00570     );
00571   }
00572 
00573   /* Adjust in case our station only accepts fewer kinds of goods */
00574   for (CargoID i = 0; i < NUM_CARGO; i++) {
00575     uint amt = min(acceptance[i], 15);
00576 
00577     /* Make sure the station can accept the goods type. */
00578     bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
00579     if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
00580         (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
00581       amt = 0;
00582     }
00583 
00584     SB(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE, 1, amt >= 8);
00585   }
00586 
00587   /* Only show a message in case the acceptance was actually changed. */
00588   uint new_acc = GetAcceptanceMask(st);
00589   if (old_acc == new_acc) return;
00590 
00591   /* show a message to report that the acceptance was changed? */
00592   if (show_msg && st->owner == _local_company && st->IsInUse()) {
00593     /* List of accept and reject strings for different number of
00594      * cargo types */
00595     static const StringID accept_msg[] = {
00596       STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
00597       STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
00598     };
00599     static const StringID reject_msg[] = {
00600       STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
00601       STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
00602     };
00603 
00604     /* Array of accepted and rejected cargo types */
00605     CargoID accepts[2] = { CT_INVALID, CT_INVALID };
00606     CargoID rejects[2] = { CT_INVALID, CT_INVALID };
00607     uint num_acc = 0;
00608     uint num_rej = 0;
00609 
00610     /* Test each cargo type to see if its acceptange has changed */
00611     for (CargoID i = 0; i < NUM_CARGO; i++) {
00612       if (HasBit(new_acc, i)) {
00613         if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
00614           /* New cargo is accepted */
00615           accepts[num_acc++] = i;
00616         }
00617       } else {
00618         if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
00619           /* Old cargo is no longer accepted */
00620           rejects[num_rej++] = i;
00621         }
00622       }
00623     }
00624 
00625     /* Show news message if there are any changes */
00626     if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
00627     if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
00628   }
00629 
00630   /* redraw the station view since acceptance changed */
00631   SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ACCEPTLIST);
00632 }
00633 
00634 static void UpdateStationSignCoord(BaseStation *st)
00635 {
00636   const StationRect *r = &st->rect;
00637 
00638   if (r->IsEmpty()) return; // no tiles belong to this station
00639 
00640   /* clamp sign coord to be inside the station rect */
00641   st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
00642   st->UpdateVirtCoord();
00643 }
00644 
00650 static void DeleteStationIfEmpty(BaseStation *st)
00651 {
00652   if (!st->IsInUse()) {
00653     st->delete_ctr = 0;
00654     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00655   }
00656   /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
00657   UpdateStationSignCoord(st);
00658 }
00659 
00660 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00661 
00673 CommandCost CheckFlatLandBelow(TileIndex tile, uint w, uint h, DoCommandFlag flags, uint invalid_dirs, StationID *station, bool check_clear = true, RailType rt = INVALID_RAILTYPE)
00674 {
00675   CommandCost cost(EXPENSES_CONSTRUCTION);
00676   int allowed_z = -1;
00677 
00678   TILE_LOOP(tile_cur, w, h, tile) {
00679     if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) {
00680       return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00681     }
00682 
00683     if (!EnsureNoVehicleOnGround(tile_cur)) return CMD_ERROR;
00684 
00685     uint z;
00686     Slope tileh = GetTileSlope(tile_cur, &z);
00687 
00688     /* Prohibit building if
00689      *   1) The tile is "steep" (i.e. stretches two height levels)
00690      *   2) The tile is non-flat and the build_on_slopes switch is disabled
00691      */
00692     if (IsSteepSlope(tileh) ||
00693         ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00694       return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00695     }
00696 
00697     int flat_z = z;
00698     if (tileh != SLOPE_FLAT) {
00699       /* need to check so the entrance to the station is not pointing at a slope.
00700        * This must be valid for all station tiles, as the user can remove single station tiles. */
00701       if ((HasBit(invalid_dirs, DIAGDIR_NE) && !(tileh & SLOPE_NE)) ||
00702           (HasBit(invalid_dirs, DIAGDIR_SE) && !(tileh & SLOPE_SE)) ||
00703           (HasBit(invalid_dirs, DIAGDIR_SW) && !(tileh & SLOPE_SW)) ||
00704           (HasBit(invalid_dirs, DIAGDIR_NW) && !(tileh & SLOPE_NW))) {
00705         return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00706       }
00707       cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00708       flat_z += TILE_HEIGHT;
00709     }
00710 
00711     /* get corresponding flat level and make sure that all parts of the station have the same level. */
00712     if (allowed_z == -1) {
00713       /* first tile */
00714       allowed_z = flat_z;
00715     } else if (allowed_z != flat_z) {
00716       return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00717     }
00718 
00719     /* if station is set, then we have special handling to allow building on top of already existing stations.
00720      * so station points to INVALID_STATION if we can build on any station.
00721      * Or it points to a station if we're only allowed to build on exactly that station. */
00722     if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00723       if (!IsRailStation(tile_cur)) {
00724         return ClearTile_Station(tile_cur, DC_AUTO); // get error message
00725       } else {
00726         StationID st = GetStationIndex(tile_cur);
00727         if (*station == INVALID_STATION) {
00728           *station = st;
00729         } else if (*station != st) {
00730           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00731         }
00732       }
00733     } else if (check_clear) {
00734       /* Rail type is only valid when building a railway station; in station to
00735        * build isn't a rail station it's INVALID_RAILTYPE. */
00736       if (rt != INVALID_RAILTYPE &&
00737           IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00738           HasPowerOnRail(GetRailType(tile_cur), rt)) {
00739         /* Allow overbuilding if the tile:
00740          *  - has rail, but no signals
00741          *  - it has exactly one track
00742          *  - the track is in line with the station
00743          *  - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
00744          */
00745         TrackBits tracks = GetTrackBits(tile_cur);
00746         Track track = RemoveFirstTrack(&tracks);
00747         Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00748 
00749         if (tracks == TRACK_BIT_NONE && track == expected_track) {
00750           CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00751           if (ret.Failed()) return ret;
00752           cost.AddCost(ret);
00753           /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
00754           continue;
00755         }
00756       }
00757       CommandCost ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00758       if (ret.Failed()) return ret;
00759       cost.AddCost(ret);
00760     }
00761   }
00762 
00763   return cost;
00764 }
00765 
00773 bool CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00774 {
00775   TileArea cur_ta = st->train_station;
00776 
00777   if (_settings_game.station.nonuniform_stations) {
00778     /* determine new size of train station region.. */
00779     int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00780     int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00781     new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00782     new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00783     new_ta.tile = TileXY(x, y);
00784   } else {
00785     /* do not allow modifying non-uniform stations,
00786      * the uniform-stations code wouldn't handle it well */
00787     TILE_LOOP(t, cur_ta.w, cur_ta.h, cur_ta.tile) {
00788       if (!st->TileBelongsToRailStation(t)) { // there may be adjoined station
00789         _error_message = STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED;
00790         return false;
00791       }
00792     }
00793 
00794     /* check so the orientation is the same */
00795     if (GetRailStationAxis(cur_ta.tile) != axis) {
00796       _error_message = STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED;
00797       return false;
00798     }
00799 
00800     /* check if the new station adjoins the old station in either direction */
00801     if (cur_ta.w == new_ta.w && cur_ta.tile == new_ta.tile + TileDiffXY(0, new_ta.h)) {
00802       /* above */
00803       new_ta.h += cur_ta.h;
00804     } else if (cur_ta.w == new_ta.w && cur_ta.tile == new_ta.tile - TileDiffXY(0, cur_ta.h)) {
00805       /* below */
00806       new_ta.tile = cur_ta.tile;
00807       new_ta.h += new_ta.h;
00808     } else if (cur_ta.h == new_ta.h && cur_ta.tile == new_ta.tile + TileDiffXY(new_ta.w, 0)) {
00809       /* to the left */
00810       new_ta.w += cur_ta.w;
00811     } else if (cur_ta.h == new_ta.h && cur_ta.tile == new_ta.tile - TileDiffXY(cur_ta.w, 0)) {
00812       /* to the right */
00813       new_ta.tile = cur_ta.tile;
00814       new_ta.w += cur_ta.w;
00815     } else {
00816       _error_message = STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED;
00817       return false;
00818     }
00819   }
00820   /* make sure the final size is not too big. */
00821   if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00822     _error_message = STR_ERROR_STATION_TOO_SPREAD_OUT;
00823     return false;
00824   }
00825 
00826   return true;
00827 }
00828 
00829 static inline byte *CreateSingle(byte *layout, int n)
00830 {
00831   int i = n;
00832   do *layout++ = 0; while (--i);
00833   layout[((n - 1) >> 1) - n] = 2;
00834   return layout;
00835 }
00836 
00837 static inline byte *CreateMulti(byte *layout, int n, byte b)
00838 {
00839   int i = n;
00840   do *layout++ = b; while (--i);
00841   if (n > 4) {
00842     layout[0 - n] = 0;
00843     layout[n - 1 - n] = 0;
00844   }
00845   return layout;
00846 }
00847 
00848 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
00849 {
00850   if (statspec != NULL && statspec->lengths >= plat_len &&
00851       statspec->platforms[plat_len - 1] >= numtracks &&
00852       statspec->layouts[plat_len - 1][numtracks - 1]) {
00853     /* Custom layout defined, follow it. */
00854     memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
00855       plat_len * numtracks);
00856     return;
00857   }
00858 
00859   if (plat_len == 1) {
00860     CreateSingle(layout, numtracks);
00861   } else {
00862     if (numtracks & 1) layout = CreateSingle(layout, plat_len);
00863     numtracks >>= 1;
00864 
00865     while (--numtracks >= 0) {
00866       layout = CreateMulti(layout, plat_len, 4);
00867       layout = CreateMulti(layout, plat_len, 6);
00868     }
00869   }
00870 }
00871 
00883 template <class T, StringID error_message>
00884 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
00885 {
00886   assert(*st == NULL);
00887   bool check_surrounding = true;
00888 
00889   if (_settings_game.station.adjacent_stations) {
00890     if (existing_station != INVALID_STATION) {
00891       if (adjacent && existing_station != station_to_join) {
00892         /* You can't build an adjacent station over the top of one that
00893          * already exists. */
00894         return_cmd_error(error_message);
00895       } else {
00896         /* Extend the current station, and don't check whether it will
00897          * be near any other stations. */
00898         *st = T::GetIfValid(existing_station);
00899         check_surrounding = (*st == NULL);
00900       }
00901     } else {
00902       /* There's no station here. Don't check the tiles surrounding this
00903        * one if the company wanted to build an adjacent station. */
00904       if (adjacent) check_surrounding = false;
00905     }
00906   }
00907 
00908   if (check_surrounding) {
00909     /* Make sure there are no similar stations around us. */
00910     if (!GetStationAround(ta, existing_station, st)) return CMD_ERROR;
00911   }
00912 
00913   /* Distant join */
00914   if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
00915 
00916   return CommandCost();;
00917 }
00918 
00928 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
00929 {
00930   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
00931 }
00932 
00942 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
00943 {
00944   return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
00945 }
00946 
00964 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00965 {
00966   /* Unpack parameters */
00967   RailType rt    = (RailType)GB(p1, 0, 4);
00968   Axis axis      = Extract<Axis, 4>(p1);
00969   byte numtracks = GB(p1,  8, 8);
00970   byte plat_len  = GB(p1, 16, 8);
00971   bool adjacent  = HasBit(p1, 24);
00972 
00973   StationClassID spec_class = (StationClassID)GB(p2, 0, 8);
00974   byte spec_index           = GB(p2, 8, 8);
00975   StationID station_to_join = GB(p2, 16, 16);
00976 
00977   /* Does the authority allow this? */
00978   if (!CheckIfAuthorityAllowsNewStation(tile_org, flags)) return CMD_ERROR;
00979   if (!ValParamRailtype(rt)) return CMD_ERROR;
00980 
00981   /* Check if the given station class is valid */
00982   if ((uint)spec_class >= GetNumStationClasses()) return CMD_ERROR;
00983   if (spec_index >= GetNumCustomStations(spec_class)) return CMD_ERROR;
00984   if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
00985 
00986   int w_org, h_org;
00987   if (axis == AXIS_X) {
00988     w_org = plat_len;
00989     h_org = numtracks;
00990   } else {
00991     h_org = plat_len;
00992     w_org = numtracks;
00993   }
00994 
00995   bool reuse = (station_to_join != NEW_STATION);
00996   if (!reuse) station_to_join = INVALID_STATION;
00997   bool distant_join = (station_to_join != INVALID_STATION);
00998 
00999   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01000 
01001   if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01002 
01003   /* these values are those that will be stored in train_tile and station_platforms */
01004   TileArea new_location(tile_org, w_org, h_org);
01005 
01006   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
01007   StationID est = INVALID_STATION;
01008   /* If DC_EXEC is in flag, do not want to pass it to CheckFlatLandBelow, because of a nice bug
01009    * for detail info, see:
01010    * https://sourceforge.net/tracker/index.php?func=detail&aid=1029064&group_id=103924&atid=636365 */
01011   CommandCost ret = CheckFlatLandBelow(tile_org, w_org, h_org, flags & ~DC_EXEC, 5 << axis, _settings_game.station.nonuniform_stations ? &est : NULL, true, rt);
01012   if (ret.Failed()) return ret;
01013   CommandCost cost(EXPENSES_CONSTRUCTION, ret.GetCost() + (numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01014 
01015   Station *st = NULL;
01016   ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01017   if (ret.Failed()) return ret;
01018 
01019   /* See if there is a deleted station close to us. */
01020   if (st == NULL && reuse) st = GetClosestDeletedStation(tile_org);
01021 
01022   if (st != NULL) {
01023     /* Reuse an existing station. */
01024     if (st->owner != _current_company)
01025       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01026 
01027     if (st->train_station.tile != INVALID_TILE) {
01028       /* check if we want to expanding an already existing station? */
01029       if (!_settings_game.station.join_stations)
01030         return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_RAILROAD);
01031       if (!CanExpandRailStation(st, new_location, axis))
01032         return CMD_ERROR;
01033     }
01034 
01035     /* XXX can't we pack this in the "else" part of the if above? */
01036     if (!st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST)) return CMD_ERROR;
01037   } else {
01038     /* allocate and initialize new station */
01039     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01040 
01041     if (flags & DC_EXEC) {
01042       st = new Station(tile_org);
01043 
01044       st->town = ClosestTownFromTile(tile_org, UINT_MAX);
01045       st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);
01046 
01047       if (Company::IsValidID(_current_company)) {
01048         SetBit(st->town->have_ratings, _current_company);
01049       }
01050     }
01051   }
01052 
01053   /* Check if we can allocate a custom stationspec to this station */
01054   const StationSpec *statspec = GetCustomStationSpec(spec_class, spec_index);
01055   int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01056   if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01057 
01058   if (statspec != NULL) {
01059     /* Perform NewStation checks */
01060 
01061     /* Check if the station size is permitted */
01062     if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01063       return CMD_ERROR;
01064     }
01065 
01066     /* Check if the station is buildable */
01067     if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL) && GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) {
01068       return CMD_ERROR;
01069     }
01070   }
01071 
01072   if (flags & DC_EXEC) {
01073     TileIndexDiff tile_delta;
01074     byte *layout_ptr;
01075     byte numtracks_orig;
01076     Track track;
01077 
01078     /* Now really clear the land below the station
01079      * It should never return CMD_ERROR.. but you never know ;)
01080      * (a bit strange function name for it, but it really does clear the land, when DC_EXEC is in flags) */
01081     ret = CheckFlatLandBelow(tile_org, w_org, h_org, flags, 5 << axis, _settings_game.station.nonuniform_stations ? &est : NULL, true, rt);
01082     if (ret.Failed()) return ret;
01083 
01084     st->train_station = new_location;
01085     st->AddFacility(FACIL_TRAIN, new_location.tile);
01086 
01087     st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01088 
01089     if (statspec != NULL) {
01090       /* Include this station spec's animation trigger bitmask
01091        * in the station's cached copy. */
01092       st->cached_anim_triggers |= statspec->anim_triggers;
01093     }
01094 
01095     tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01096     track = AxisToTrack(axis);
01097 
01098     layout_ptr = AllocaM(byte, numtracks * plat_len);
01099     GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01100 
01101     numtracks_orig = numtracks;
01102 
01103     SmallVector<Train*, 4> affected_vehicles;
01104     do {
01105       TileIndex tile = tile_org;
01106       int w = plat_len;
01107       do {
01108         byte layout = *layout_ptr++;
01109         if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01110           /* Check for trains having a reservation for this tile. */
01111           Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01112           if (v != NULL) {
01113             FreeTrainTrackReservation(v);
01114             *affected_vehicles.Append() = v;
01115             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01116             for (; v->Next() != NULL; v = v->Next()) { }
01117             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01118           }
01119         }
01120 
01121         /* Remove animation if overbuilding */
01122         DeleteAnimatedTile(tile);
01123         byte old_specindex = IsTileType(tile, MP_STATION) ? GetCustomStationSpecIndex(tile) : 0;
01124         MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01125         /* Free the spec if we overbuild something */
01126         DeallocateSpecFromStation(st, old_specindex);
01127 
01128         SetCustomStationSpecIndex(tile, specindex);
01129         SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01130         SetStationAnimationFrame(tile, 0);
01131 
01132         if (statspec != NULL) {
01133           /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
01134           uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01135 
01136           /* As the station is not yet completely finished, the station does not yet exist. */
01137           uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01138           if (callback != CALLBACK_FAILED && callback < 8) SetStationGfx(tile, (callback & ~1) + axis);
01139 
01140           /* Trigger station animation -- after building? */
01141           StationAnimationTrigger(st, tile, STAT_ANIM_BUILT);
01142         }
01143 
01144         tile += tile_delta;
01145       } while (--w);
01146       AddTrackToSignalBuffer(tile_org, track, _current_company);
01147       YapfNotifyTrackLayoutChange(tile_org, track);
01148       tile_org += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
01149     } while (--numtracks);
01150 
01151     for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01152       /* Restore reservations of trains. */
01153       Train *v = affected_vehicles[i];
01154       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01155       TryPathReserve(v, true, true);
01156       for (; v->Next() != NULL; v = v->Next()) { }
01157       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01158     }
01159 
01160     st->MarkTilesDirty(false);
01161     st->UpdateVirtCoord();
01162     UpdateStationAcceptance(st, false);
01163     st->RecomputeIndustriesNear();
01164     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01165     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01166     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01167   }
01168 
01169   return cost;
01170 }
01171 
01172 static void MakeRailStationAreaSmaller(BaseStation *st)
01173 {
01174   TileArea ta = st->train_station;
01175 
01176 restart:
01177 
01178   /* too small? */
01179   if (ta.w != 0 && ta.h != 0) {
01180     /* check the left side, x = constant, y changes */
01181     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01182       /* the left side is unused? */
01183       if (++i == ta.h) {
01184         ta.tile += TileDiffXY(1, 0);
01185         ta.w--;
01186         goto restart;
01187       }
01188     }
01189 
01190     /* check the right side, x = constant, y changes */
01191     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01192       /* the right side is unused? */
01193       if (++i == ta.h) {
01194         ta.w--;
01195         goto restart;
01196       }
01197     }
01198 
01199     /* check the upper side, y = constant, x changes */
01200     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01201       /* the left side is unused? */
01202       if (++i == ta.w) {
01203         ta.tile += TileDiffXY(0, 1);
01204         ta.h--;
01205         goto restart;
01206       }
01207     }
01208 
01209     /* check the lower side, y = constant, x changes */
01210     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01211       /* the left side is unused? */
01212       if (++i == ta.w) {
01213         ta.h--;
01214         goto restart;
01215       }
01216     }
01217   } else {
01218     ta.Clear();
01219   }
01220 
01221   st->train_station = ta;
01222 }
01223 
01234 template <class T>
01235 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01236 {
01237   /* Count of the number of tiles removed */
01238   int quantity = 0;
01239   CommandCost total_cost(EXPENSES_CONSTRUCTION);
01240 
01241   /* Do the action for every tile into the area */
01242   TILE_AREA_LOOP(tile, ta) {
01243     /* Make sure the specified tile is a rail station */
01244     if (!HasStationTileRail(tile)) continue;
01245 
01246     /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
01247     if (!EnsureNoVehicleOnGround(tile)) continue;
01248 
01249     /* Check ownership of station */
01250     T *st = T::GetByTile(tile);
01251     if (st == NULL) continue;
01252     if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) continue;
01253 
01254     /* Do not allow removing from stations if non-uniform stations are not enabled
01255      * The check must be here to give correct error message
01256      */
01257     if (!_settings_game.station.nonuniform_stations) return_cmd_error(STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED);
01258 
01259     /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
01260     quantity++;
01261 
01262     if (flags & DC_EXEC) {
01263       /* read variables before the station tile is removed */
01264       uint specindex = GetCustomStationSpecIndex(tile);
01265       Track track = GetRailStationTrack(tile);
01266       Owner owner = GetTileOwner(tile);
01267       RailType rt = GetRailType(tile);
01268       Train *v = NULL;
01269 
01270       if (HasStationReservation(tile)) {
01271         v = GetTrainForReservation(tile, track);
01272         if (v != NULL) {
01273           /* Free train reservation. */
01274           FreeTrainTrackReservation(v);
01275           if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01276           Vehicle *temp = v;
01277           for (; temp->Next() != NULL; temp = temp->Next()) { }
01278           if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01279         }
01280       }
01281 
01282       DoClearSquare(tile);
01283       if (keep_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01284 
01285       st->rect.AfterRemoveTile(st, tile);
01286       AddTrackToSignalBuffer(tile, track, owner);
01287       YapfNotifyTrackLayoutChange(tile, track);
01288 
01289       DeallocateSpecFromStation(st, specindex);
01290 
01291       affected_stations.Include(st);
01292 
01293       if (v != NULL) {
01294         /* Restore station reservation. */
01295         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01296         TryPathReserve(v, true, true);
01297         for (; v->Next() != NULL; v = v->Next()) { }
01298         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01299       }
01300     }
01301     if (keep_rail) {
01302       /* Don't refund the 'steel' of the track! */
01303       total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01304     }
01305   }
01306 
01307   if (quantity == 0) return CMD_ERROR;
01308 
01309   for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01310     T *st = *stp;
01311 
01312     /* now we need to make the "spanned" area of the railway station smaller
01313      * if we deleted something at the edges.
01314      * we also need to adjust train_tile. */
01315     MakeRailStationAreaSmaller(st);
01316     UpdateStationSignCoord(st);
01317 
01318     /* if we deleted the whole station, delete the train facility. */
01319     if (st->train_station.tile == INVALID_TILE) {
01320       st->facilities &= ~FACIL_TRAIN;
01321       SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01322       st->UpdateVirtCoord();
01323       DeleteStationIfEmpty(st);
01324     }
01325   }
01326 
01327   total_cost.AddCost(quantity * removal_cost);
01328   return total_cost;
01329 }
01330 
01341 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01342 {
01343   TileIndex end = p1 == 0 ? start : p1;
01344   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01345 
01346   TileArea ta(start, end);
01347   SmallVector<Station *, 4> affected_stations;
01348 
01349   CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01350   if (ret.Failed()) return ret;
01351 
01352   /* Do all station specific functions here. */
01353   for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01354     Station *st = *stp;
01355 
01356     if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01357     st->MarkTilesDirty(false);
01358     st->RecomputeIndustriesNear();
01359   }
01360 
01361   /* Now apply the rail cost to the number that we deleted */
01362   return ret;
01363 }
01364 
01375 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01376 {
01377   TileIndex end = p1 == 0 ? start : p1;
01378   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01379 
01380   TileArea ta(start, end);
01381   SmallVector<Waypoint *, 4> affected_stations;
01382 
01383   return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01384 }
01385 
01386 
01394 template <class T>
01395 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01396 {
01397   /* Current company owns the station? */
01398   if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) return CMD_ERROR;
01399 
01400   /* determine width and height of platforms */
01401   TileArea ta = st->train_station;
01402 
01403   assert(ta.w != 0 && ta.h != 0);
01404 
01405   CommandCost cost(EXPENSES_CONSTRUCTION);
01406   /* clear all areas of the station */
01407   TILE_AREA_LOOP(tile, ta) {
01408     /* for nonuniform stations, only remove tiles that are actually train station tiles */
01409     if (!st->TileBelongsToRailStation(tile)) continue;
01410 
01411     if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
01412 
01413     cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01414     if (flags & DC_EXEC) {
01415       /* read variables before the station tile is removed */
01416       Track track = GetRailStationTrack(tile);
01417       Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
01418       Train *v = NULL;
01419       if (HasStationReservation(tile)) {
01420         v = GetTrainForReservation(tile, track);
01421         if (v != NULL) FreeTrainTrackReservation(v);
01422       }
01423       DoClearSquare(tile);
01424       AddTrackToSignalBuffer(tile, track, owner);
01425       YapfNotifyTrackLayoutChange(tile, track);
01426       if (v != NULL) TryPathReserve(v, true);
01427     }
01428   }
01429 
01430   if (flags & DC_EXEC) {
01431     st->rect.AfterRemoveRect(st, st->train_station.tile, st->train_station.w, st->train_station.h);
01432 
01433     st->train_station.Clear();
01434 
01435     st->facilities &= ~FACIL_TRAIN;
01436 
01437     free(st->speclist);
01438     st->num_specs = 0;
01439     st->speclist  = NULL;
01440     st->cached_anim_triggers = 0;
01441 
01442     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01443     st->UpdateVirtCoord();
01444     DeleteStationIfEmpty(st);
01445   }
01446 
01447   return cost;
01448 }
01449 
01456 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01457 {
01458   /* if there is flooding and non-uniform stations are enabled, remove platforms tile by tile */
01459   if (_current_company == OWNER_WATER && _settings_game.station.nonuniform_stations) {
01460     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01461   }
01462 
01463   Station *st = Station::GetByTile(tile);
01464   CommandCost cost = RemoveRailStation(st, flags);
01465 
01466   if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01467 
01468   return cost;
01469 }
01470 
01477 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01478 {
01479   /* if there is flooding and non-uniform stations are enabled, remove waypoints tile by tile */
01480   if (_current_company == OWNER_WATER && _settings_game.station.nonuniform_stations) {
01481     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01482   }
01483 
01484   return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01485 }
01486 
01487 
01493 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01494 {
01495   RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01496 
01497   if (*primary_stop == NULL) {
01498     /* we have no roadstop of the type yet, so write a "primary stop" */
01499     return primary_stop;
01500   } else {
01501     /* there are stops already, so append to the end of the list */
01502     RoadStop *stop = *primary_stop;
01503     while (stop->next != NULL) stop = stop->next;
01504     return &stop->next;
01505   }
01506 }
01507 
01520 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01521 {
01522   bool type = HasBit(p2, 0);
01523   bool is_drive_through = HasBit(p2, 1);
01524   bool build_over_road  = is_drive_through && IsNormalRoadTile(tile);
01525   RoadTypes rts = (RoadTypes)GB(p2, 2, 2);
01526   StationID station_to_join = GB(p2, 16, 16);
01527   bool reuse = (station_to_join != NEW_STATION);
01528   if (!reuse) station_to_join = INVALID_STATION;
01529   bool distant_join = (station_to_join != INVALID_STATION);
01530   Owner tram_owner = _current_company;
01531   Owner road_owner = _current_company;
01532 
01533   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01534 
01535   if (!AreValidRoadTypes(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01536 
01537   /* Trams only have drive through stops */
01538   if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01539 
01540   /* Saveguard the parameters */
01541   if (!IsValidDiagDirection((DiagDirection)p1)) return CMD_ERROR;
01542   /* If it is a drive-through stop check for valid axis */
01543   if (is_drive_through && !IsValidAxis((Axis)p1)) return CMD_ERROR;
01544   /* Road bits in the wrong direction */
01545   if (build_over_road && (GetAllRoadBits(tile) & ((Axis)p1 == AXIS_X ? ROAD_Y : ROAD_X)) != 0) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
01546 
01547   if (!CheckIfAuthorityAllowsNewStation(tile, flags)) return CMD_ERROR;
01548 
01549   RoadTypes cur_rts = IsNormalRoadTile(tile) ? GetRoadTypes(tile) : ROADTYPES_NONE;
01550   uint num_roadbits = 0;
01551   /* Not allowed to build over this road */
01552   if (build_over_road) {
01553     /* there is a road, check if we can build road+tram stop over it */
01554     if (HasBit(cur_rts, ROADTYPE_ROAD)) {
01555       road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01556       if (road_owner == OWNER_TOWN) {
01557         if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
01558       } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE && !CheckOwnership(road_owner)) {
01559         return CMD_ERROR;
01560       }
01561       num_roadbits += CountBits(GetRoadBits(tile, ROADTYPE_ROAD));
01562     }
01563 
01564     /* there is a tram, check if we can build road+tram stop over it */
01565     if (HasBit(cur_rts, ROADTYPE_TRAM)) {
01566       tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01567       if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE && !CheckOwnership(tram_owner)) {
01568         return CMD_ERROR;
01569       }
01570       num_roadbits += CountBits(GetRoadBits(tile, ROADTYPE_TRAM));
01571     }
01572 
01573     /* Don't allow building the roadstop when vehicles are already driving on it */
01574     if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
01575 
01576     /* Do not remove roadtypes! */
01577     rts |= cur_rts;
01578   }
01579 
01580   CommandCost cost = CheckFlatLandBelow(tile, 1, 1, flags, is_drive_through ? 5 << p1 : 1 << p1, NULL, !build_over_road);
01581   if (cost.Failed()) return cost;
01582   uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
01583   cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
01584 
01585   Station *st = NULL;
01586   CommandCost ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 5), TileArea(tile, 1, 1), &st);
01587   if (ret.Failed()) return ret;
01588 
01589   /* Find a deleted station close to us */
01590   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
01591 
01592   /* give us a road stop in the list, and check if something went wrong */
01593   if (!RoadStop::CanAllocateItem()) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
01594 
01595   if (st != NULL) {
01596     if (st->owner != _current_company) {
01597       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01598     }
01599 
01600     if (!st->rect.BeforeAddTile(tile, StationRect::ADD_TEST)) return CMD_ERROR;
01601   } else {
01602     /* allocate and initialize new station */
01603     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01604 
01605     if (flags & DC_EXEC) {
01606       st = new Station(tile);
01607 
01608       st->town = ClosestTownFromTile(tile, UINT_MAX);
01609       st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
01610 
01611       if (Company::IsValidID(_current_company)) {
01612         SetBit(st->town->have_ratings, _current_company);
01613       }
01614     }
01615   }
01616 
01617   cost.AddCost(_price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01618 
01619   if (flags & DC_EXEC) {
01620     RoadStop *road_stop = new RoadStop(tile);
01621     /* Insert into linked list of RoadStops */
01622     RoadStop **currstop = FindRoadStopSpot(type, st);
01623     *currstop = road_stop;
01624 
01625     if (type) {
01626       st->truck_station.Add(tile);
01627     } else {
01628       st->bus_station.Add(tile);
01629     }
01630 
01631     /* initialize an empty station */
01632     st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, tile);
01633 
01634     st->rect.BeforeAddTile(tile, StationRect::ADD_TRY);
01635 
01636     RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01637     if (is_drive_through) {
01638       MakeDriveThroughRoadStop(tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts, (Axis)p1);
01639       road_stop->MakeDriveThrough();
01640     } else {
01641       MakeRoadStop(tile, st->owner, st->index, rs_type, rts, (DiagDirection)p1);
01642     }
01643 
01644     st->UpdateVirtCoord();
01645     UpdateStationAcceptance(st, false);
01646     st->RecomputeIndustriesNear();
01647     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01648     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01649     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
01650   }
01651   return cost;
01652 }
01653 
01654 
01655 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01656 {
01657   if (v->type == VEH_ROAD) {
01658     /* Okay... we are a road vehicle on a drive through road stop.
01659      * But that road stop has just been removed, so we need to make
01660      * sure we are in a valid state... however, vehicles can also
01661      * turn on road stop tiles, so only clear the 'road stop' state
01662      * bits and only when the state was 'in road stop', otherwise
01663      * we'll end up clearing the turn around bits. */
01664     RoadVehicle *rv = RoadVehicle::From(v);
01665     if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01666   }
01667 
01668   return NULL;
01669 }
01670 
01671 
01678 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01679 {
01680   Station *st = Station::GetByTile(tile);
01681 
01682   if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
01683     return CMD_ERROR;
01684   }
01685 
01686   bool is_truck = IsTruckStop(tile);
01687 
01688   RoadStop **primary_stop;
01689   RoadStop *cur_stop;
01690   if (is_truck) { // truck stop
01691     primary_stop = &st->truck_stops;
01692     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01693   } else {
01694     primary_stop = &st->bus_stops;
01695     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01696   }
01697 
01698   assert(cur_stop != NULL);
01699 
01700   /* don't do the check for drive-through road stops when company bankrupts */
01701   if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01702     /* remove the 'going through road stop' status from all vehicles on that tile */
01703     if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01704   } else {
01705     if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
01706   }
01707 
01708   if (flags & DC_EXEC) {
01709     if (*primary_stop == cur_stop) {
01710       /* removed the first stop in the list */
01711       *primary_stop = cur_stop->next;
01712       /* removed the only stop? */
01713       if (*primary_stop == NULL) {
01714         st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01715       }
01716     } else {
01717       /* tell the predecessor in the list to skip this stop */
01718       RoadStop *pred = *primary_stop;
01719       while (pred->next != cur_stop) pred = pred->next;
01720       pred->next = cur_stop->next;
01721     }
01722 
01723     if (IsDriveThroughStopTile(tile)) {
01724       /* Clears the tile for us */
01725       cur_stop->ClearDriveThrough();
01726     } else {
01727       DoClearSquare(tile);
01728     }
01729 
01730     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
01731     delete cur_stop;
01732 
01733     /* Make sure no vehicle is going to the old roadstop */
01734     RoadVehicle *v;
01735     FOR_ALL_ROADVEHICLES(v) {
01736       if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01737           v->dest_tile == tile) {
01738         v->dest_tile = v->GetOrderStationLocation(st->index);
01739       }
01740     }
01741 
01742     st->rect.AfterRemoveTile(st, tile);
01743 
01744     st->UpdateVirtCoord();
01745     st->RecomputeIndustriesNear();
01746     DeleteStationIfEmpty(st);
01747 
01748     /* Update the tile area of the truck/bus stop */
01749     if (is_truck) {
01750       st->truck_station.Clear();
01751       for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01752     } else {
01753       st->bus_station.Clear();
01754       for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
01755     }
01756   }
01757 
01758   return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
01759 }
01760 
01769 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01770 {
01771   /* Make sure the specified tile is a road stop of the correct type */
01772   if (!IsTileType(tile, MP_STATION) || !IsRoadStop(tile) || (uint32)GetRoadStopType(tile) != GB(p2, 0, 1)) return CMD_ERROR;
01773 
01774   /* Save the stop info before it is removed */
01775   bool is_drive_through = IsDriveThroughStopTile(tile);
01776   RoadTypes rts = GetRoadTypes(tile);
01777   RoadBits road_bits = IsDriveThroughStopTile(tile) ?
01778       ((GetRoadStopDir(tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
01779       DiagDirToRoadBits(GetRoadStopDir(tile));
01780 
01781   Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01782   Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01783   CommandCost ret = RemoveRoadStop(tile, flags);
01784 
01785   /* If the stop was a drive-through stop replace the road */
01786   if ((flags & DC_EXEC) && ret.Succeeded() && is_drive_through) {
01787     /* Rebuild the drive throuhg road stop. As a road stop can only be
01788      * removed by the owner of the roadstop, _current_company is the
01789      * owner of the road stop. */
01790     MakeRoadNormal(tile, road_bits, rts, ClosestTownFromTile(tile, UINT_MAX)->index,
01791         road_owner, tram_owner);
01792   }
01793 
01794   return ret;
01795 }
01796 
01804 static uint GetMinimalAirportDistanceToTile(const AirportSpec *as, TileIndex town_tile, TileIndex airport_tile)
01805 {
01806   uint ttx = TileX(town_tile); // X, Y of town
01807   uint tty = TileY(town_tile);
01808 
01809   uint atx = TileX(airport_tile); // X, Y of northern airport corner
01810   uint aty = TileY(airport_tile);
01811 
01812   uint btx = TileX(airport_tile) + as->size_x - 1; // X, Y of southern corner
01813   uint bty = TileY(airport_tile) + as->size_y - 1;
01814 
01815   /* if ttx < atx, dx = atx - ttx
01816    * if atx <= ttx <= btx, dx = 0
01817    * else, dx = ttx - btx (similiar for dy) */
01818   uint dx = ttx < atx ? atx - ttx : (ttx <= btx ? 0 : ttx - btx);
01819   uint dy = tty < aty ? aty - tty : (tty <= bty ? 0 : tty - bty);
01820 
01821   return dx + dy;
01822 }
01823 
01832 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIndex town_tile, TileIndex tile)
01833 {
01834   /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
01835    * So no need to go any further*/
01836   if (as->noise_level < 2) return as->noise_level;
01837 
01838   uint distance = GetMinimalAirportDistanceToTile(as, town_tile, tile);
01839 
01840   /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
01841    * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
01842    * Basically, it says that the less tolerant a town is, the bigger the distance before
01843    * an actual decrease can be granted */
01844   uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
01845 
01846   /* now, we want to have the distance segmented using the distance judged bareable by town
01847    * This will give us the coefficient of reduction the distance provides. */
01848   uint noise_reduction = distance / town_tolerance_distance;
01849 
01850   /* If the noise reduction equals the airport noise itself, don't give it for free.
01851    * Otherwise, simply reduce the airport's level. */
01852   return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
01853 }
01854 
01862 Town *AirportGetNearestTown(const AirportSpec *as, TileIndex airport_tile)
01863 {
01864   Town *t, *nearest = NULL;
01865   uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
01866   uint mindist = UINT_MAX - add; // prevent overflow
01867   FOR_ALL_TOWNS(t) {
01868     if (DistanceManhattan(t->xy, airport_tile) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
01869       uint dist = GetMinimalAirportDistanceToTile(as, t->xy, airport_tile);
01870       if (dist < mindist) {
01871         nearest = t;
01872         mindist = dist;
01873       }
01874     }
01875   }
01876 
01877   return nearest;
01878 }
01879 
01880 
01882 void UpdateAirportsNoise()
01883 {
01884   Town *t;
01885   const Station *st;
01886 
01887   FOR_ALL_TOWNS(t) t->noise_reached = 0;
01888 
01889   FOR_ALL_STATIONS(st) {
01890     if (st->airport_tile != INVALID_TILE) {
01891       const AirportSpec *as = st->GetAirportSpec();
01892       Town *nearest = AirportGetNearestTown(as, st->airport_tile);
01893       nearest->noise_reached += GetAirportNoiseLevelForTown(as, nearest->xy, st->airport_tile);
01894     }
01895   }
01896 }
01897 
01908 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01909 {
01910   bool airport_upgrade = true;
01911   StationID station_to_join = GB(p2, 16, 16);
01912   bool reuse = (station_to_join != NEW_STATION);
01913   if (!reuse) station_to_join = INVALID_STATION;
01914   bool distant_join = (station_to_join != INVALID_STATION);
01915 
01916   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01917 
01918   if (p1 >= NUM_AIRPORTS) return CMD_ERROR;
01919 
01920   if (!CheckIfAuthorityAllowsNewStation(tile, flags)) {
01921     return CMD_ERROR;
01922   }
01923 
01924   /* Check if a valid, buildable airport was chosen for construction */
01925   const AirportSpec *as = AirportSpec::Get(p1);
01926   if (!as->IsAvailable()) return CMD_ERROR;
01927 
01928   Town *t = ClosestTownFromTile(tile, UINT_MAX);
01929   int w = as->size_x;
01930   int h = as->size_y;
01931 
01932   if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
01933     _error_message = STR_ERROR_STATION_TOO_SPREAD_OUT;
01934     return CMD_ERROR;
01935   }
01936 
01937   CommandCost cost = CheckFlatLandBelow(tile, w, h, flags, 0, NULL);
01938   if (cost.Failed()) return cost;
01939 
01940   /* Go get the final noise level, that is base noise minus factor from distance to town center */
01941   Town *nearest = AirportGetNearestTown(as, tile);
01942   uint newnoise_level = GetAirportNoiseLevelForTown(as, nearest->xy, tile);
01943 
01944   /* Check if local auth would allow a new airport */
01945   StringID authority_refuse_message = STR_NULL;
01946 
01947   if (_settings_game.economy.station_noise_level) {
01948     /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
01949     if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
01950       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
01951     }
01952   } else {
01953     uint num = 0;
01954     const Station *st;
01955     FOR_ALL_STATIONS(st) {
01956       if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport_type != AT_OILRIG) num++;
01957     }
01958     if (num >= 2) {
01959       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
01960     }
01961   }
01962 
01963   if (authority_refuse_message != STR_NULL) {
01964     SetDParam(0, t->index);
01965     return_cmd_error(authority_refuse_message);
01966   }
01967 
01968   Station *st = NULL;
01969   CommandCost ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
01970   if (ret.Failed()) return ret;
01971 
01972   /* Distant join */
01973   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
01974 
01975   /* Find a deleted station close to us */
01976   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
01977 
01978   if (st != NULL) {
01979     if (st->owner != _current_company) {
01980       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01981     }
01982 
01983     if (!st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST)) return CMD_ERROR;
01984 
01985     if (st->airport_tile != INVALID_TILE) {
01986       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
01987     }
01988   } else {
01989     airport_upgrade = false;
01990 
01991     /* allocate and initialize new station */
01992     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01993 
01994     if (flags & DC_EXEC) {
01995       st = new Station(tile);
01996 
01997       st->town = t;
01998       st->string_id = GenerateStationName(st, tile, !(GetAirport(p1)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
01999 
02000       if (Company::IsValidID(_current_company)) {
02001         SetBit(st->town->have_ratings, _current_company);
02002       }
02003     }
02004   }
02005 
02006   cost.AddCost(_price[PR_BUILD_STATION_AIRPORT] * w * h);
02007 
02008   if (flags & DC_EXEC) {
02009     /* Always add the noise, so there will be no need to recalculate when option toggles */
02010     nearest->noise_reached += newnoise_level;
02011 
02012     st->airport_tile = tile;
02013     st->AddFacility(FACIL_AIRPORT, tile);
02014     st->airport_type = (byte)p1;
02015     st->airport_flags = 0;
02016 
02017     st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02018 
02019     /* if airport was demolished while planes were en-route to it, the
02020      * positions can no longer be the same (v->u.air.pos), since different
02021      * airports have different indexes. So update all planes en-route to this
02022      * airport. Only update if
02023      * 1. airport is upgraded
02024      * 2. airport is added to existing station (unfortunately unavoideable)
02025      */
02026     if (airport_upgrade) UpdateAirplanesOnNewStation(st);
02027 
02028     const AirportTileTable *it = as->table[0];
02029     do {
02030       TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
02031       MakeAirport(cur_tile, st->owner, st->index, it->gfx);
02032     } while ((++it)->ti.x != -0x80);
02033 
02034     st->UpdateVirtCoord();
02035     UpdateStationAcceptance(st, false);
02036     st->RecomputeIndustriesNear();
02037     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02038     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02039     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
02040 
02041     if (_settings_game.economy.station_noise_level) {
02042       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02043     }
02044   }
02045 
02046   return cost;
02047 }
02048 
02055 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02056 {
02057   Station *st = Station::GetByTile(tile);
02058 
02059   if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
02060     return CMD_ERROR;
02061   }
02062 
02063   tile = st->airport_tile;
02064 
02065   const AirportSpec *as = st->GetAirportSpec();
02066   int w = as->size_x;
02067   int h = as->size_y;
02068 
02069   CommandCost cost(EXPENSES_CONSTRUCTION);
02070 
02071   const Aircraft *a;
02072   FOR_ALL_AIRCRAFT(a) {
02073     if (!a->IsNormalAircraft()) continue;
02074     if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02075   }
02076 
02077   TILE_LOOP(tile_cur, w, h, tile) {
02078     if (!EnsureNoVehicleOnGround(tile_cur)) return CMD_ERROR;
02079 
02080     if (!st->TileBelongsToAirport(tile_cur)) continue;
02081 
02082     cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02083 
02084     if (flags & DC_EXEC) {
02085       DeleteAnimatedTile(tile_cur);
02086       DoClearSquare(tile_cur);
02087     }
02088   }
02089 
02090   if (flags & DC_EXEC) {
02091     for (uint i = 0; i < as->nof_depots; ++i) {
02092       DeleteWindowById(
02093         WC_VEHICLE_DEPOT, st->GetHangarTile(i)
02094       );
02095     }
02096 
02097     /* Go get the final noise level, that is base noise minus factor from distance to town center.
02098      * And as for construction, always remove it, even if the setting is not set, in order to avoid the
02099      * need of recalculation */
02100     Town *nearest = AirportGetNearestTown(as, tile);
02101     nearest->noise_reached -= GetAirportNoiseLevelForTown(as, nearest->xy, tile);
02102 
02103     st->rect.AfterRemoveRect(st, tile, w, h);
02104 
02105     st->airport_tile = INVALID_TILE;
02106     st->facilities &= ~FACIL_AIRPORT;
02107 
02108     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
02109 
02110     if (_settings_game.economy.station_noise_level) {
02111       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02112     }
02113 
02114     st->UpdateVirtCoord();
02115     st->RecomputeIndustriesNear();
02116     DeleteStationIfEmpty(st);
02117   }
02118 
02119   return cost;
02120 }
02121 
02128 bool HasStationInUse(StationID station, CompanyID company)
02129 {
02130   const Vehicle *v;
02131   FOR_ALL_VEHICLES(v) {
02132     if (company == INVALID_COMPANY || v->owner == company) {
02133       const Order *order;
02134       FOR_VEHICLE_ORDERS(v, order) {
02135         if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02136           return true;
02137         }
02138       }
02139     }
02140   }
02141   return false;
02142 }
02143 
02144 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02145   {-1,  0},
02146   { 0,  0},
02147   { 0,  0},
02148   { 0, -1}
02149 };
02150 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02151 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02152 
02161 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02162 {
02163   StationID station_to_join = GB(p2, 16, 16);
02164   bool reuse = (station_to_join != NEW_STATION);
02165   if (!reuse) station_to_join = INVALID_STATION;
02166   bool distant_join = (station_to_join != INVALID_STATION);
02167 
02168   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02169 
02170   DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile, NULL));
02171   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02172   direction = ReverseDiagDir(direction);
02173 
02174   /* Docks cannot be placed on rapids */
02175   if (IsWaterTile(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02176 
02177   if (!CheckIfAuthorityAllowsNewStation(tile, flags)) return CMD_ERROR;
02178 
02179   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02180 
02181   if (DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR).Failed()) return CMD_ERROR;
02182 
02183   TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02184 
02185   if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
02186     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02187   }
02188 
02189   if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02190 
02191   /* Get the water class of the water tile before it is cleared.*/
02192   WaterClass wc = GetWaterClass(tile_cur);
02193 
02194   if (DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR).Failed()) return CMD_ERROR;
02195 
02196   tile_cur += TileOffsByDiagDir(direction);
02197   if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
02198     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02199   }
02200 
02201   /* middle */
02202   Station *st = NULL;
02203   CommandCost ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
02204       TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02205           _dock_w_chk[direction], _dock_h_chk[direction]), &st);
02206   if (ret.Failed()) return ret;
02207 
02208   /* Distant join */
02209   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02210 
02211   /* Find a deleted station close to us */
02212   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02213 
02214   if (st != NULL) {
02215     if (st->owner != _current_company) {
02216       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02217     }
02218 
02219     if (!st->rect.BeforeAddRect(
02220         tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02221         _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST)) return CMD_ERROR;
02222 
02223     if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02224   } else {
02225     /* allocate and initialize new station */
02226     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02227 
02228     if (flags & DC_EXEC) {
02229       st = new Station(tile);
02230 
02231       st->town = ClosestTownFromTile(tile, UINT_MAX);
02232       st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
02233 
02234       if (Company::IsValidID(_current_company)) {
02235         SetBit(st->town->have_ratings, _current_company);
02236       }
02237     }
02238   }
02239 
02240   if (flags & DC_EXEC) {
02241     st->dock_tile = tile;
02242     st->AddFacility(FACIL_DOCK, tile);
02243 
02244     st->rect.BeforeAddRect(
02245         tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02246         _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
02247 
02248     MakeDock(tile, st->owner, st->index, direction, wc);
02249 
02250     st->UpdateVirtCoord();
02251     UpdateStationAcceptance(st, false);
02252     st->RecomputeIndustriesNear();
02253     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02254     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02255     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
02256   }
02257 
02258   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02259 }
02260 
02267 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02268 {
02269   Station *st = Station::GetByTile(tile);
02270   if (!CheckOwnership(st->owner)) return CMD_ERROR;
02271 
02272   TileIndex tile1 = st->dock_tile;
02273   TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02274 
02275   if (!EnsureNoVehicleOnGround(tile1)) return CMD_ERROR;
02276   if (!EnsureNoVehicleOnGround(tile2)) return CMD_ERROR;
02277 
02278   if (flags & DC_EXEC) {
02279     DoClearSquare(tile1);
02280     MakeWaterKeepingClass(tile2, st->owner);
02281 
02282     st->rect.AfterRemoveTile(st, tile1);
02283     st->rect.AfterRemoveTile(st, tile2);
02284 
02285     MarkTileDirtyByTile(tile2);
02286 
02287     st->dock_tile = INVALID_TILE;
02288     st->facilities &= ~FACIL_DOCK;
02289 
02290     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
02291     st->UpdateVirtCoord();
02292     st->RecomputeIndustriesNear();
02293     DeleteStationIfEmpty(st);
02294   }
02295 
02296   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02297 }
02298 
02299 #include "table/station_land.h"
02300 
02301 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02302 {
02303   return &_station_display_datas[st][gfx];
02304 }
02305 
02306 static void DrawTile_Station(TileInfo *ti)
02307 {
02308   const DrawTileSprites *t = NULL;
02309   RoadTypes roadtypes;
02310   int32 total_offset;
02311   int32 custom_ground_offset;
02312 
02313   if (HasStationRail(ti->tile)) {
02314     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02315     roadtypes = ROADTYPES_NONE;
02316     total_offset = rti->total_offset;
02317     custom_ground_offset = rti->custom_ground_offset;
02318   } else {
02319     roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02320     total_offset = 0;
02321     custom_ground_offset = 0;
02322   }
02323   uint32 relocation = 0;
02324   const BaseStation *st = NULL;
02325   const StationSpec *statspec = NULL;
02326   Owner owner = GetTileOwner(ti->tile);
02327 
02328   SpriteID palette;
02329   if (Company::IsValidID(owner)) {
02330     palette = COMPANY_SPRITE_COLOUR(owner);
02331   } else {
02332     /* Some stations are not owner by a company, namely oil rigs */
02333     palette = PALETTE_TO_GREY;
02334   }
02335 
02336   if (IsCustomStationSpecIndex(ti->tile)) {
02337     /* look for customization */
02338     st = BaseStation::GetByTile(ti->tile);
02339     statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02340 
02341     if (statspec != NULL) {
02342       uint tile = GetStationGfx(ti->tile);
02343 
02344       relocation = GetCustomStationRelocation(statspec, st, ti->tile);
02345 
02346       if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02347         uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02348         if (callback != CALLBACK_FAILED) tile = (callback & ~1) + GetRailStationAxis(ti->tile);
02349       }
02350 
02351       /* Ensure the chosen tile layout is valid for this custom station */
02352       if (statspec->renderdata != NULL) {
02353         t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)];
02354       }
02355     }
02356   }
02357 
02358   if (t == NULL || t->seq == NULL) t = &_station_display_datas[GetStationType(ti->tile)][GetStationGfx(ti->tile)];
02359 
02360   /* don't show foundation for docks */
02361   if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02362     if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02363       /* Station has custom foundations. */
02364       SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile);
02365 
02366       if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02367         /* Station provides extended foundations. */
02368 
02369         static const uint8 foundation_parts[] = {
02370           0, 0, 0, 0, // Invalid,  Invalid,   Invalid,   SLOPE_SW
02371           0, 1, 2, 3, // Invalid,  SLOPE_EW,  SLOPE_SE,  SLOPE_WSE
02372           0, 4, 5, 6, // Invalid,  SLOPE_NW,  SLOPE_NS,  SLOPE_NWS
02373           7, 8, 9     // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
02374         };
02375 
02376         AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02377       } else {
02378         /* Draw simple foundations, built up from 8 possible foundation sprites. */
02379 
02380         /* Each set bit represents one of the eight composite sprites to be drawn.
02381          * 'Invalid' entries will not drawn but are included for completeness. */
02382         static const uint8 composite_foundation_parts[] = {
02383           /* Invalid  (00000000), Invalid   (11010001), Invalid   (11100100), SLOPE_SW  (11100000) */
02384              0x00,                0xD1,                 0xE4,                 0xE0,
02385           /* Invalid  (11001010), SLOPE_EW  (11001001), SLOPE_SE  (11000100), SLOPE_WSE (11000000) */
02386              0xCA,                0xC9,                 0xC4,                 0xC0,
02387           /* Invalid  (11010010), SLOPE_NW  (10010001), SLOPE_NS  (11100100), SLOPE_NWS (10100000) */
02388              0xD2,                0x91,                 0xE4,                 0xA0,
02389           /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
02390              0x4A,                0x09,                 0x44
02391         };
02392 
02393         uint8 parts = composite_foundation_parts[ti->tileh];
02394 
02395         /* If foundations continue beyond the tile's upper sides then
02396          * mask out the last two pieces. */
02397         uint z;
02398         Slope slope = GetFoundationSlope(ti->tile, &z);
02399         if (!HasFoundationNW(ti->tile, slope, z)) ClrBit(parts, 6);
02400         if (!HasFoundationNE(ti->tile, slope, z)) ClrBit(parts, 7);
02401 
02402         StartSpriteCombine();
02403         for (int i = 0; i < 8; i++) {
02404           if (HasBit(parts, i)) {
02405             AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02406           }
02407         }
02408         EndSpriteCombine();
02409       }
02410 
02411       OffsetGroundSprite(31, 1);
02412       ti->z += ApplyFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02413     } else {
02414       DrawFoundation(ti, FOUNDATION_LEVELED);
02415     }
02416   }
02417 
02418   if (IsBuoy(ti->tile) || IsDock(ti->tile) || (IsOilRig(ti->tile) && GetWaterClass(ti->tile) != WATER_CLASS_INVALID)) {
02419     if (ti->tileh == SLOPE_FLAT) {
02420       DrawWaterClassGround(ti);
02421     } else {
02422       assert(IsDock(ti->tile));
02423       TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02424       WaterClass wc = GetWaterClass(water_tile);
02425       if (wc == WATER_CLASS_SEA) {
02426         DrawShoreTile(ti->tileh);
02427       } else {
02428         DrawClearLandTile(ti, 3);
02429       }
02430     }
02431   } else {
02432     SpriteID image = t->ground.sprite;
02433     SpriteID pal   = t->ground.pal;
02434     if (HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
02435       image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
02436       image += custom_ground_offset;
02437     } else {
02438       image += total_offset;
02439     }
02440     DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02441 
02442     /* PBS debugging, draw reserved tracks darker */
02443     if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02444       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02445       DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02446     }
02447   }
02448 
02449   if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);
02450 
02451   if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02452     Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02453     DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02454     DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02455   }
02456 
02457   if (IsRailWaypoint(ti->tile)) {
02458     /* Don't offset the waypoint graphics; they're always the same. */
02459     total_offset = 0;
02460   }
02461 
02462   DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02463 }
02464 
02465 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02466 {
02467   int32 total_offset = 0;
02468   SpriteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02469   const DrawTileSprites *t = &_station_display_datas[st][image];
02470 
02471   if (railtype != INVALID_RAILTYPE) {
02472     const RailtypeInfo *rti = GetRailTypeInfo(railtype);
02473     total_offset = rti->total_offset;
02474   }
02475 
02476   SpriteID img = t->ground.sprite;
02477   DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02478 
02479   if (roadtype == ROADTYPE_TRAM) {
02480     DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02481   }
02482 
02483   /* Default waypoint has no railtype specific sprites */
02484   DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02485 }
02486 
02487 static uint GetSlopeZ_Station(TileIndex tile, uint x, uint y)
02488 {
02489   return GetTileMaxZ(tile);
02490 }
02491 
02492 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02493 {
02494   return FlatteningFoundation(tileh);
02495 }
02496 
02497 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02498 {
02499   td->owner[0] = GetTileOwner(tile);
02500   if (IsDriveThroughStopTile(tile)) {
02501     Owner road_owner = INVALID_OWNER;
02502     Owner tram_owner = INVALID_OWNER;
02503     RoadTypes rts = GetRoadTypes(tile);
02504     if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02505     if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02506 
02507     /* Is there a mix of owners? */
02508     if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02509         (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02510       uint i = 1;
02511       if (road_owner != INVALID_OWNER) {
02512         td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02513         td->owner[i] = road_owner;
02514         i++;
02515       }
02516       if (tram_owner != INVALID_OWNER) {
02517         td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02518         td->owner[i] = tram_owner;
02519       }
02520     }
02521   }
02522   td->build_date = BaseStation::GetByTile(tile)->build_date;
02523 
02524   const StationSpec *spec = GetStationSpec(tile);
02525 
02526   if (spec != NULL) {
02527     td->station_class = GetStationClassName(spec->sclass);
02528     td->station_name = spec->name;
02529 
02530     if (spec->grffile != NULL) {
02531       const GRFConfig *gc = GetGRFConfig(spec->grffile->grfid);
02532       td->grf = gc->name;
02533     }
02534   }
02535 
02536   StringID str;
02537   switch (GetStationType(tile)) {
02538     default: NOT_REACHED();
02539     case STATION_RAIL:     str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
02540     case STATION_AIRPORT:
02541       str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
02542       break;
02543     case STATION_TRUCK:    str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
02544     case STATION_BUS:      str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
02545     case STATION_OILRIG:   str = STR_INDUSTRY_NAME_OIL_RIG; break;
02546     case STATION_DOCK:     str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
02547     case STATION_BUOY:     str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
02548     case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
02549   }
02550   td->str = str;
02551 }
02552 
02553 
02554 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
02555 {
02556   TrackBits trackbits = TRACK_BIT_NONE;
02557 
02558   switch (mode) {
02559     case TRANSPORT_RAIL:
02560       if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
02561         trackbits = TrackToTrackBits(GetRailStationTrack(tile));
02562       }
02563       break;
02564 
02565     case TRANSPORT_WATER:
02566       /* buoy is coded as a station, it is always on open water */
02567       if (IsBuoy(tile)) {
02568         trackbits = TRACK_BIT_ALL;
02569         /* remove tracks that connect NE map edge */
02570         if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
02571         /* remove tracks that connect NW map edge */
02572         if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
02573       }
02574       break;
02575 
02576     case TRANSPORT_ROAD:
02577       if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
02578         DiagDirection dir = GetRoadStopDir(tile);
02579         Axis axis = DiagDirToAxis(dir);
02580 
02581         if (side != INVALID_DIAGDIR) {
02582           if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
02583         }
02584 
02585         trackbits = AxisToTrackBits(axis);
02586       }
02587       break;
02588 
02589     default:
02590       break;
02591   }
02592 
02593   return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
02594 }
02595 
02596 
02597 static void TileLoop_Station(TileIndex tile)
02598 {
02599   /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
02600    * hardcoded.....not good */
02601   switch (GetStationType(tile)) {
02602     case STATION_AIRPORT:
02603       if (AirportTileSpec::Get(GetStationGfx(tile))->anim_next != AIRPORTTILE_NOANIM) {
02604         AddAnimatedTile(tile);
02605       }
02606       break;
02607 
02608     case STATION_DOCK:
02609       if (GetTileSlope(tile, NULL) != SLOPE_FLAT) break; // only handle water part
02610     /* FALL THROUGH */
02611     case STATION_OILRIG: //(station part)
02612     case STATION_BUOY:
02613       TileLoop_Water(tile);
02614       break;
02615 
02616     default: break;
02617   }
02618 }
02619 
02620 
02621 static void AnimateTile_Station(TileIndex tile)
02622 {
02623   if (HasStationRail(tile)) {
02624     AnimateStationTile(tile);
02625     return;
02626   }
02627 
02628   if (IsAirport(tile)) {
02629     const AirportTileSpec *ats = AirportTileSpec::Get(GetStationGfx(tile));
02630     uint16 mask = (1 << ats->animation_speed) - 1;
02631     if (ats->anim_next != AIRPORTTILE_NOANIM && (_tick_counter & mask) == 0) {
02632       SetStationGfx(tile, ats->anim_next);
02633       MarkTileDirtyByTile(tile);
02634     }
02635   }
02636 }
02637 
02638 
02639 static bool ClickTile_Station(TileIndex tile)
02640 {
02641   const BaseStation *st = BaseStation::GetByTile(tile);
02642 
02643   if (st->facilities & FACIL_WAYPOINT) {
02644     ShowWaypointWindow(Waypoint::From(st));
02645   } else if (IsHangar(tile)) {
02646     ShowDepotWindow(tile, VEH_AIRCRAFT);
02647   } else {
02648     ShowStationViewWindow(st->index);
02649   }
02650   return true;
02651 }
02652 
02653 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
02654 {
02655   if (v->type == VEH_TRAIN) {
02656     StationID station_id = GetStationIndex(tile);
02657     if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
02658     if (!IsRailStation(tile) || !Train::From(v)->IsFrontEngine()) return VETSB_CONTINUE;
02659 
02660     int station_ahead;
02661     int station_length;
02662     int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
02663 
02664     /* Stop whenever that amount of station ahead + the distance from the
02665      * begin of the platform to the stop location is longer than the length
02666      * of the platform. Station ahead 'includes' the current tile where the
02667      * vehicle is on, so we need to substract that. */
02668     if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
02669 
02670     DiagDirection dir = DirToDiagDir(v->direction);
02671 
02672     x &= 0xF;
02673     y &= 0xF;
02674 
02675     if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
02676     if (y == TILE_SIZE / 2) {
02677       if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
02678       stop &= TILE_SIZE - 1;
02679 
02680       if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
02681       if (x < stop) {
02682         uint16 spd;
02683 
02684         v->vehstatus |= VS_TRAIN_SLOWING;
02685         spd = max(0, (stop - x) * 20 - 15);
02686         if (spd < v->cur_speed) v->cur_speed = spd;
02687       }
02688     }
02689   } else if (v->type == VEH_ROAD) {
02690     RoadVehicle *rv = RoadVehicle::From(v);
02691     if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
02692       if (IsRoadStop(tile) && rv->IsRoadVehFront()) {
02693         /* Attempt to allocate a parking bay in a road stop */
02694         return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
02695       }
02696     }
02697   }
02698 
02699   return VETSB_CONTINUE;
02700 }
02701 
02708 static bool StationHandleBigTick(BaseStation *st)
02709 {
02710   if (!st->IsInUse() && ++st->delete_ctr >= 8) {
02711     delete st;
02712     return false;
02713   }
02714 
02715   if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
02716 
02717   return true;
02718 }
02719 
02720 static inline void byte_inc_sat(byte *p)
02721 {
02722   byte b = *p + 1;
02723   if (b != 0) *p = b;
02724 }
02725 
02726 static void UpdateStationRating(Station *st)
02727 {
02728   bool waiting_changed = false;
02729 
02730   byte_inc_sat(&st->time_since_load);
02731   byte_inc_sat(&st->time_since_unload);
02732 
02733   const CargoSpec *cs;
02734   FOR_ALL_CARGOSPECS(cs) {
02735     GoodsEntry *ge = &st->goods[cs->Index()];
02736     /* Slowly increase the rating back to his original level in the case we
02737      *  didn't deliver cargo yet to this station. This happens when a bribe
02738      *  failed while you didn't moved that cargo yet to a station. */
02739     if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP) && ge->rating < INITIAL_STATION_RATING) {
02740       ge->rating++;
02741     }
02742 
02743     /* Only change the rating if we are moving this cargo */
02744     if (HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) {
02745       byte_inc_sat(&ge->days_since_pickup);
02746 
02747       bool skip = false;
02748       int rating = 0;
02749       uint waiting = ge->cargo.Count();
02750 
02751       if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
02752         /* Perform custom station rating. If it succeeds the speed, days in transit and
02753          * waiting cargo ratings must not be executed. */
02754 
02755         /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
02756         uint last_speed = ge->last_speed;
02757         if (last_speed == 0) last_speed = 0xFF;
02758 
02759         uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(waiting, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
02760         /* Convert to the 'old' vehicle types */
02761         uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
02762         uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
02763         if (callback != CALLBACK_FAILED) {
02764           skip = true;
02765           rating = GB(callback, 0, 14);
02766 
02767           /* Simulate a 15 bit signed value */
02768           if (HasBit(callback, 14)) rating -= 0x4000;
02769         }
02770       }
02771 
02772       if (!skip) {
02773         int b = ge->last_speed - 85;
02774         if (b >= 0) rating += b >> 2;
02775 
02776         byte days = ge->days_since_pickup;
02777         if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
02778         (days > 21) ||
02779         (rating += 25, days > 12) ||
02780         (rating += 25, days > 6) ||
02781         (rating += 45, days > 3) ||
02782         (rating += 35, true);
02783 
02784         (rating -= 90, waiting > 1500) ||
02785         (rating += 55, waiting > 1000) ||
02786         (rating += 35, waiting > 600) ||
02787         (rating += 10, waiting > 300) ||
02788         (rating += 20, waiting > 100) ||
02789         (rating += 10, true);
02790       }
02791 
02792       if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
02793 
02794       byte age = ge->last_age;
02795       (age >= 3) ||
02796       (rating += 10, age >= 2) ||
02797       (rating += 10, age >= 1) ||
02798       (rating += 13, true);
02799 
02800       {
02801         int or_ = ge->rating; // old rating
02802 
02803         /* only modify rating in steps of -2, -1, 0, 1 or 2 */
02804         ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
02805 
02806         /* if rating is <= 64 and more than 200 items waiting,
02807          * remove some random amount of goods from the station */
02808         if (rating <= 64 && waiting >= 200) {
02809           int dec = Random() & 0x1F;
02810           if (waiting < 400) dec &= 7;
02811           waiting -= dec + 1;
02812           waiting_changed = true;
02813         }
02814 
02815         /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
02816         if (rating <= 127 && waiting != 0) {
02817           uint32 r = Random();
02818           if (rating <= (int)GB(r, 0, 7)) {
02819             /* Need to have int, otherwise it will just overflow etc. */
02820             waiting = max((int)waiting - (int)GB(r, 8, 2) - 1, 0);
02821             waiting_changed = true;
02822           }
02823         }
02824 
02825         /* At some point we really must cap the cargo. Previously this
02826          * was a strict 4095, but now we'll have a less strict, but
02827          * increasingly agressive truncation of the amount of cargo. */
02828         static const uint WAITING_CARGO_THRESHOLD  = 1 << 12;
02829         static const uint WAITING_CARGO_CUT_FACTOR = 1 <<  6;
02830         static const uint MAX_WAITING_CARGO        = 1 << 15;
02831 
02832         if (waiting > WAITING_CARGO_THRESHOLD) {
02833           uint difference = waiting - WAITING_CARGO_THRESHOLD;
02834           waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
02835 
02836           waiting = min(waiting, MAX_WAITING_CARGO);
02837           waiting_changed = true;
02838         }
02839 
02840         if (waiting_changed) ge->cargo.Truncate(waiting);
02841       }
02842     }
02843   }
02844 
02845   StationID index = st->index;
02846   if (waiting_changed) {
02847     SetWindowDirty(WC_STATION_VIEW, index); // update whole window
02848   } else {
02849     SetWindowWidgetDirty(WC_STATION_VIEW, index, SVW_RATINGLIST); // update only ratings list
02850   }
02851 }
02852 
02853 /* called for every station each tick */
02854 static void StationHandleSmallTick(BaseStation *st)
02855 {
02856   if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
02857 
02858   byte b = st->delete_ctr + 1;
02859   if (b >= 185) b = 0;
02860   st->delete_ctr = b;
02861 
02862   if (b == 0) UpdateStationRating(Station::From(st));
02863 }
02864 
02865 void OnTick_Station()
02866 {
02867   if (_game_mode == GM_EDITOR) return;
02868 
02869   BaseStation *st;
02870   FOR_ALL_BASE_STATIONS(st) {
02871     StationHandleSmallTick(st);
02872 
02873     /* Run 250 tick interval trigger for station animation.
02874      * Station index is included so that triggers are not all done
02875      * at the same time. */
02876     if ((_tick_counter + st->index) % 250 == 0) {
02877       /* Stop processing this station if it was deleted */
02878       if (!StationHandleBigTick(st)) continue;
02879       StationAnimationTrigger(st, st->xy, STAT_ANIM_250_TICKS);
02880     }
02881   }
02882 }
02883 
02884 void StationMonthlyLoop()
02885 {
02886   /* not used */
02887 }
02888 
02889 
02890 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
02891 {
02892   Station *st;
02893 
02894   FOR_ALL_STATIONS(st) {
02895     if (st->owner == owner &&
02896         DistanceManhattan(tile, st->xy) <= radius) {
02897       for (CargoID i = 0; i < NUM_CARGO; i++) {
02898         GoodsEntry *ge = &st->goods[i];
02899 
02900         if (ge->acceptance_pickup != 0) {
02901           ge->rating = Clamp(ge->rating + amount, 0, 255);
02902         }
02903       }
02904     }
02905   }
02906 }
02907 
02908 static void UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
02909 {
02910   st->goods[type].cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id));
02911   SetBit(st->goods[type].acceptance_pickup, GoodsEntry::PICKUP);
02912 
02913   StationAnimationTrigger(st, st->xy, STAT_ANIM_NEW_CARGO, type);
02914 
02915   SetWindowDirty(WC_STATION_VIEW, st->index);
02916   st->MarkTilesDirty(true);
02917 }
02918 
02919 static bool IsUniqueStationName(const char *name)
02920 {
02921   const Station *st;
02922 
02923   FOR_ALL_STATIONS(st) {
02924     if (st->name != NULL && strcmp(st->name, name) == 0) return false;
02925   }
02926 
02927   return true;
02928 }
02929 
02938 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02939 {
02940   Station *st = Station::GetIfValid(p1);
02941   if (st == NULL || !CheckOwnership(st->owner)) return CMD_ERROR;
02942 
02943   bool reset = StrEmpty(text);
02944 
02945   if (!reset) {
02946     if (strlen(text) >= MAX_LENGTH_STATION_NAME_BYTES) return CMD_ERROR;
02947     if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02948   }
02949 
02950   if (flags & DC_EXEC) {
02951     free(st->name);
02952     st->name = reset ? NULL : strdup(text);
02953 
02954     st->UpdateVirtCoord();
02955     InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
02956   }
02957 
02958   return CommandCost();
02959 }
02960 
02967 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
02968 {
02969   /* area to search = producer plus station catchment radius */
02970   int max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
02971 
02972   for (int dy = -max_rad; dy < location.h + max_rad; dy++) {
02973     for (int dx = -max_rad; dx < location.w + max_rad; dx++) {
02974       TileIndex cur_tile = TileAddWrap(location.tile, dx, dy);
02975       if (cur_tile == INVALID_TILE || !IsTileType(cur_tile, MP_STATION)) continue;
02976 
02977       Station *st = Station::GetByTile(cur_tile);
02978       if (st == NULL) continue;
02979 
02980       if (_settings_game.station.modified_catchment) {
02981         int rad = st->GetCatchmentRadius();
02982         if (dx < -rad || dx >= rad + location.w || dy < -rad || dy >= rad + location.h) continue;
02983       }
02984 
02985       /* Insert the station in the set. This will fail if it has
02986        * already been added.
02987        */
02988       stations->Include(st);
02989     }
02990   }
02991 }
02992 
02997 const StationList *StationFinder::GetStations()
02998 {
02999   if (this->tile != INVALID_TILE) {
03000     FindStationsAroundTiles(*this, &this->stations);
03001     this->tile = INVALID_TILE;
03002   }
03003   return &this->stations;
03004 }
03005 
03006 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03007 {
03008   /* Return if nothing to do. Also the rounding below fails for 0. */
03009   if (amount == 0) return 0;
03010 
03011   Station *st1 = NULL;   // Station with best rating
03012   Station *st2 = NULL;   // Second best station
03013   uint best_rating1 = 0; // rating of st1
03014   uint best_rating2 = 0; // rating of st2
03015 
03016   for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03017     Station *st = *st_iter;
03018 
03019     /* Is the station reserved exclusively for somebody else? */
03020     if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03021 
03022     if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
03023 
03024     if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue; // Selectively servicing stations, and not this one
03025 
03026     if (IsCargoInClass(type, CC_PASSENGERS)) {
03027       if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
03028     } else {
03029       if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
03030     }
03031 
03032     /* This station can be used, add it to st1/st2 */
03033     if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03034       st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03035     } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03036       st2 = st; best_rating2 = st->goods[type].rating;
03037     }
03038   }
03039 
03040   /* no stations around at all? */
03041   if (st1 == NULL) return 0;
03042 
03043   if (st2 == NULL) {
03044     /* only one station around */
03045     uint moved = amount * best_rating1 / 256 + 1;
03046     UpdateStationWaiting(st1, type, moved, source_type, source_id);
03047     return moved;
03048   }
03049 
03050   /* several stations around, the best two (highest rating) are in st1 and st2 */
03051   assert(st1 != NULL);
03052   assert(st2 != NULL);
03053   assert(best_rating1 != 0 || best_rating2 != 0);
03054 
03055   /* the 2nd highest one gets a penalty */
03056   best_rating2 >>= 1;
03057 
03058   /* amount given to station 1 */
03059   uint t = (best_rating1 * (amount + 1)) / (best_rating1 + best_rating2);
03060 
03061   uint moved = 0;
03062   if (t != 0) {
03063     moved = t * best_rating1 / 256 + 1;
03064     amount -= t;
03065     UpdateStationWaiting(st1, type, moved, source_type, source_id);
03066   }
03067 
03068   if (amount != 0) {
03069     amount = amount * best_rating2 / 256 + 1;
03070     moved += amount;
03071     UpdateStationWaiting(st2, type, amount, source_type, source_id);
03072   }
03073 
03074   return moved;
03075 }
03076 
03077 void BuildOilRig(TileIndex tile)
03078 {
03079   if (!Station::CanAllocateItem()) {
03080     DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03081     return;
03082   }
03083 
03084   Station *st = new Station(tile);
03085   st->town = ClosestTownFromTile(tile, UINT_MAX);
03086 
03087   st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03088 
03089   assert(IsTileType(tile, MP_INDUSTRY));
03090   DeleteAnimatedTile(tile);
03091   MakeOilrig(tile, st->index, GetWaterClass(tile));
03092 
03093   st->owner = OWNER_NONE;
03094   st->airport_type = AT_OILRIG;
03095   st->airport_tile = tile;
03096   st->dock_tile = tile;
03097   st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03098   st->build_date = _date;
03099 
03100   st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03101 
03102   for (CargoID j = 0; j < NUM_CARGO; j++) {
03103     st->goods[j].acceptance_pickup = 0;
03104     st->goods[j].days_since_pickup = 255;
03105     st->goods[j].rating = INITIAL_STATION_RATING;
03106     st->goods[j].last_speed = 0;
03107     st->goods[j].last_age = 255;
03108   }
03109 
03110   st->UpdateVirtCoord();
03111   UpdateStationAcceptance(st, false);
03112   st->RecomputeIndustriesNear();
03113 }
03114 
03115 void DeleteOilRig(TileIndex tile)
03116 {
03117   Station *st = Station::GetByTile(tile);
03118 
03119   MakeWaterKeepingClass(tile, OWNER_NONE);
03120   MarkTileDirtyByTile(tile);
03121 
03122   st->dock_tile = INVALID_TILE;
03123   st->airport_tile = INVALID_TILE;
03124   st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03125   st->airport_flags = 0;
03126 
03127   st->rect.AfterRemoveTile(st, tile);
03128 
03129   st->UpdateVirtCoord();
03130   st->RecomputeIndustriesNear();
03131   if (!st->IsInUse()) delete st;
03132 }
03133 
03134 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03135 {
03136   if (IsDriveThroughStopTile(tile)) {
03137     for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03138       /* Update all roadtypes, no matter if they are present */
03139       if (GetRoadOwner(tile, rt) == old_owner) {
03140         SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03141       }
03142     }
03143   }
03144 
03145   if (!IsTileOwner(tile, old_owner)) return;
03146 
03147   if (new_owner != INVALID_OWNER) {
03148     /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
03149     SetTileOwner(tile, new_owner);
03150     InvalidateWindowClassesData(WC_STATION_LIST, 0);
03151   } else {
03152     if (IsDriveThroughStopTile(tile)) {
03153       /* Remove the drive-through road stop */
03154       DoCommand(tile, 0, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03155       assert(IsTileType(tile, MP_ROAD));
03156       /* Change owner of tile and all roadtypes */
03157       ChangeTileOwner(tile, old_owner, new_owner);
03158     } else {
03159       DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03160       /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
03161        * Update owner of buoy if it was not removed (was in orders).
03162        * Do not update when owned by OWNER_WATER (sea and rivers). */
03163       if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03164     }
03165   }
03166 }
03167 
03176 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03177 {
03178   /* Yeah... water can always remove stops, right? */
03179   if (_current_company == OWNER_WATER) return true;
03180 
03181   Owner road_owner = _current_company;
03182   Owner tram_owner = _current_company;
03183 
03184   RoadTypes rts = GetRoadTypes(tile);
03185   if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03186   if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03187 
03188   if ((road_owner != OWNER_TOWN && !CheckOwnership(road_owner)) || !CheckOwnership(tram_owner)) return false;
03189 
03190   return road_owner != OWNER_TOWN || CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags);
03191 }
03192 
03193 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
03194 {
03195   if (flags & DC_AUTO) {
03196     switch (GetStationType(tile)) {
03197       default: break;
03198       case STATION_RAIL:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
03199       case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
03200       case STATION_AIRPORT:  return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
03201       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);
03202       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);
03203       case STATION_BUOY:     return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
03204       case STATION_DOCK:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
03205       case STATION_OILRIG:
03206         SetDParam(0, STR_INDUSTRY_NAME_OIL_RIG);
03207         return_cmd_error(STR_ERROR_UNMOVABLE_OBJECT_IN_THE_WAY);
03208     }
03209   }
03210 
03211   switch (GetStationType(tile)) {
03212     case STATION_RAIL:     return RemoveRailStation(tile, flags);
03213     case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
03214     case STATION_AIRPORT:  return RemoveAirport(tile, flags);
03215     case STATION_TRUCK:
03216       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags))
03217         return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03218       return RemoveRoadStop(tile, flags);
03219     case STATION_BUS:
03220       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags))
03221         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03222       return RemoveRoadStop(tile, flags);
03223     case STATION_BUOY:     return RemoveBuoy(tile, flags);
03224     case STATION_DOCK:     return RemoveDock(tile, flags);
03225     default: break;
03226   }
03227 
03228   return CMD_ERROR;
03229 }
03230 
03231 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
03232 {
03233   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
03234     /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
03235      *       TTDP does not call it.
03236      */
03237     if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03238       switch (GetStationType(tile)) {
03239         case STATION_WAYPOINT:
03240         case STATION_RAIL: {
03241           DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
03242           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03243           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03244           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03245         }
03246 
03247         case STATION_AIRPORT:
03248           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03249 
03250         case STATION_TRUCK:
03251         case STATION_BUS: {
03252           DiagDirection direction = GetRoadStopDir(tile);
03253           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03254           if (IsDriveThroughStopTile(tile)) {
03255             if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03256           }
03257           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03258         }
03259 
03260         default: break;
03261       }
03262     }
03263   }
03264   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03265 }
03266 
03267 
03268 extern const TileTypeProcs _tile_type_station_procs = {
03269   DrawTile_Station,           // draw_tile_proc
03270   GetSlopeZ_Station,          // get_slope_z_proc
03271   ClearTile_Station,          // clear_tile_proc
03272   NULL,                       // add_accepted_cargo_proc
03273   GetTileDesc_Station,        // get_tile_desc_proc
03274   GetTileTrackStatus_Station, // get_tile_track_status_proc
03275   ClickTile_Station,          // click_tile_proc
03276   AnimateTile_Station,        // animate_tile_proc
03277   TileLoop_Station,           // tile_loop_clear
03278   ChangeTileOwner_Station,    // change_tile_owner_clear
03279   NULL,                       // add_produced_cargo_proc
03280   VehicleEnter_Station,       // vehicle_enter_tile_proc
03281   GetFoundation_Station,      // get_foundation_proc
03282   TerraformTile_Station,      // terraform_tile_proc
03283 };

Generated on Wed Jan 20 23:38:40 2010 for OpenTTD by  doxygen 1.5.6