# station_cmd.cpp

Go to the documentation of this file.

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