# station_cmd.cpp

Go to the documentation of this file.

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