# station_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: station_cmd.cpp 19278 2010-02-27 16:41:10Z 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)
    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           CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
    00753           if (ret.Failed()) return ret;
    00754           cost.AddCost(ret);
    00755           /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
    00756           continue;
    00757         }
    00758       }
    00759       CommandCost ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00760       if (ret.Failed()) return ret;
    00761       cost.AddCost(ret);
    00762     }
    00763   }
    00764
    00765   return cost;
    00766 }
    00767
    00775 bool CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
    00776 {
    00777   TileArea cur_ta = st->train_station;
    00778
    00779   if (_settings_game.station.nonuniform_stations) {
    00780     /* determine new size of train station region.. */
    00781     int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
    00782     int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
    00783     new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
    00784     new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
    00785     new_ta.tile = TileXY(x, y);
    00786   } else {
    00787     /* do not allow modifying non-uniform stations,
    00788      * the uniform-stations code wouldn't handle it well */
    00789     TILE_LOOP(t, cur_ta.w, cur_ta.h, cur_ta.tile) {
    00790       if (!st->TileBelongsToRailStation(t)) { // there may be adjoined station
    00791         _error_message = STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED;
    00792         return false;
    00793       }
    00794     }
    00795
    00796     /* check so the orientation is the same */
    00797     if (GetRailStationAxis(cur_ta.tile) != axis) {
    00798       _error_message = STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED;
    00799       return false;
    00800     }
    00801
    00802     /* check if the new station adjoins the old station in either direction */
    00803     if (cur_ta.w == new_ta.w && cur_ta.tile == new_ta.tile + TileDiffXY(0, new_ta.h)) {
    00804       /* above */
    00805       new_ta.h += cur_ta.h;
    00806     } else if (cur_ta.w == new_ta.w && cur_ta.tile == new_ta.tile - TileDiffXY(0, cur_ta.h)) {
    00807       /* below */
    00808       new_ta.tile = cur_ta.tile;
    00809       new_ta.h += new_ta.h;
    00810     } else if (cur_ta.h == new_ta.h && cur_ta.tile == new_ta.tile + TileDiffXY(new_ta.w, 0)) {
    00811       /* to the left */
    00812       new_ta.w += cur_ta.w;
    00813     } else if (cur_ta.h == new_ta.h && cur_ta.tile == new_ta.tile - TileDiffXY(cur_ta.w, 0)) {
    00814       /* to the right */
    00815       new_ta.tile = cur_ta.tile;
    00816       new_ta.w += cur_ta.w;
    00817     } else {
    00818       _error_message = STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED;
    00819       return false;
    00820     }
    00821   }
    00822   /* make sure the final size is not too big. */
    00823   if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
    00824     _error_message = STR_ERROR_STATION_TOO_SPREAD_OUT;
    00825     return false;
    00826   }
    00827
    00828   return true;
    00829 }
    00830
    00831 static inline byte *CreateSingle(byte *layout, int n)
    00832 {
    00833   int i = n;
    00834   do *layout++ = 0; while (--i);
    00835   layout[((n - 1) >> 1) - n] = 2;
    00836   return layout;
    00837 }
    00838
    00839 static inline byte *CreateMulti(byte *layout, int n, byte b)
    00840 {
    00841   int i = n;
    00842   do *layout++ = b; while (--i);
    00843   if (n > 4) {
    00844     layout[0 - n] = 0;
    00845     layout[n - 1 - n] = 0;
    00846   }
    00847   return layout;
    00848 }
    00849
    00850 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
    00851 {
    00852   if (statspec != NULL && statspec->lengths >= plat_len &&
    00853       statspec->platforms[plat_len - 1] >= numtracks &&
    00854       statspec->layouts[plat_len - 1][numtracks - 1]) {
    00855     /* Custom layout defined, follow it. */
    00856     memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
    00857       plat_len * numtracks);
    00858     return;
    00859   }
    00860
    00861   if (plat_len == 1) {
    00862     CreateSingle(layout, numtracks);
    00863   } else {
    00864     if (numtracks & 1) layout = CreateSingle(layout, plat_len);
    00865     numtracks >>= 1;
    00866
    00867     while (--numtracks >= 0) {
    00868       layout = CreateMulti(layout, plat_len, 4);
    00869       layout = CreateMulti(layout, plat_len, 6);
    00870     }
    00871   }
    00872 }
    00873
    00885 template <class T, StringID error_message>
    00886 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
    00887 {
    00888   assert(*st == NULL);
    00889   bool check_surrounding = true;
    00890
    00891   if (_settings_game.station.adjacent_stations) {
    00892     if (existing_station != INVALID_STATION) {
    00893       if (adjacent && existing_station != station_to_join) {
    00894         /* You can't build an adjacent station over the top of one that
    00895          * already exists. */
    00896         return_cmd_error(error_message);
    00897       } else {
    00898         /* Extend the current station, and don't check whether it will
    00899          * be near any other stations. */
    00900         *st = T::GetIfValid(existing_station);
    00901         check_surrounding = (*st == NULL);
    00902       }
    00903     } else {
    00904       /* There's no station here. Don't check the tiles surrounding this
    00905        * one if the company wanted to build an adjacent station. */
    00906       if (adjacent) check_surrounding = false;
    00907     }
    00908   }
    00909
    00910   if (check_surrounding) {
    00911     /* Make sure there are no similar stations around us. */
    00912     if (!GetStationAround(ta, existing_station, st)) return CMD_ERROR;
    00913   }
    00914
    00915   /* Distant join */
    00916   if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
    00917
    00918   return CommandCost();
    00919 }
    00920
    00930 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
    00931 {
    00932   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
    00933 }
    00934
    00944 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
    00945 {
    00946   return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
    00947 }
    00948
    00966 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00967 {
    00968   /* Unpack parameters */
    00969   RailType rt    = (RailType)GB(p1, 0, 4);
    00970   Axis axis      = Extract<Axis, 4>(p1);
    00971   byte numtracks = GB(p1,  8, 8);
    00972   byte plat_len  = GB(p1, 16, 8);
    00973   bool adjacent  = HasBit(p1, 24);
    00974
    00975   StationClassID spec_class = (StationClassID)GB(p2, 0, 8);
    00976   byte spec_index           = GB(p2, 8, 8);
    00977   StationID station_to_join = GB(p2, 16, 16);
    00978
    00979   /* Does the authority allow this? */
    00980   if (!CheckIfAuthorityAllowsNewStation(tile_org, flags)) return CMD_ERROR;
    00981   if (!ValParamRailtype(rt)) return CMD_ERROR;
    00982
    00983   /* Check if the given station class is valid */
    00984   if ((uint)spec_class >= GetNumStationClasses()) return CMD_ERROR;
    00985   if (spec_index >= GetNumCustomStations(spec_class)) return CMD_ERROR;
    00986   if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
    00987
    00988   int w_org, h_org;
    00989   if (axis == AXIS_X) {
    00990     w_org = plat_len;
    00991     h_org = numtracks;
    00992   } else {
    00993     h_org = plat_len;
    00994     w_org = numtracks;
    00995   }
    00996
    00997   bool reuse = (station_to_join != NEW_STATION);
    00998   if (!reuse) station_to_join = INVALID_STATION;
    00999   bool distant_join = (station_to_join != INVALID_STATION);
    01000
    01001   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
    01002
    01003   if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
    01004
    01005   /* these values are those that will be stored in train_tile and station_platforms */
    01006   TileArea new_location(tile_org, w_org, h_org);
    01007
    01008   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
    01009   StationID est = INVALID_STATION;
    01010   /* Clear the land below the station. */
    01011   CommandCost cost = CheckFlatLandBelow(tile_org, w_org, h_org, flags, 5 << axis, _settings_game.station.nonuniform_stations ? &est : NULL, true, rt);
    01012   if (cost.Failed()) return cost;
    01013   /* Add construction expenses. */
    01014   cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
    01015
    01016   Station *st = NULL;
    01017   CommandCost ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
    01018   if (ret.Failed()) return ret;
    01019
    01020   /* See if there is a deleted station close to us. */
    01021   if (st == NULL && reuse) st = GetClosestDeletedStation(tile_org);
    01022
    01023   if (st != NULL) {
    01024     /* Reuse an existing station. */
    01025     if (st->owner != _current_company)
    01026       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
    01027
    01028     if (st->train_station.tile != INVALID_TILE) {
    01029       /* check if we want to expanding an already existing station? */
    01030       if (!_settings_game.station.join_stations)
    01031         return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_RAILROAD);
    01032       if (!CanExpandRailStation(st, new_location, axis))
    01033         return CMD_ERROR;
    01034     }
    01035
    01036     /* XXX can't we pack this in the "else" part of the if above? */
    01037     if (!st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST)) return CMD_ERROR;
    01038   } else {
    01039     /* allocate and initialize new station */
    01040     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    01041
    01042     if (flags & DC_EXEC) {
    01043       st = new Station(tile_org);
    01044
    01045       st->town = ClosestTownFromTile(tile_org, UINT_MAX);
    01046       st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);
    01047
    01048       if (Company::IsValidID(_current_company)) {
    01049         SetBit(st->town->have_ratings, _current_company);
    01050       }
    01051     }
    01052   }
    01053
    01054   /* Check if we can allocate a custom stationspec to this station */
    01055   const StationSpec *statspec = GetCustomStationSpec(spec_class, spec_index);
    01056   int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
    01057   if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
    01058
    01059   if (statspec != NULL) {
    01060     /* Perform NewStation checks */
    01061
    01062     /* Check if the station size is permitted */
    01063     if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
    01064       return CMD_ERROR;
    01065     }
    01066
    01067     /* Check if the station is buildable */
    01068     if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL) && GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) {
    01069       return CMD_ERROR;
    01070     }
    01071   }
    01072
    01073   if (flags & DC_EXEC) {
    01074     TileIndexDiff tile_delta;
    01075     byte *layout_ptr;
    01076     byte numtracks_orig;
    01077     Track track;
    01078
    01079     st->train_station = new_location;
    01080     st->AddFacility(FACIL_TRAIN, new_location.tile);
    01081
    01082     st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
    01083
    01084     if (statspec != NULL) {
    01085       /* Include this station spec's animation trigger bitmask
    01086        * in the station's cached copy. */
    01087       st->cached_anim_triggers |= statspec->anim_triggers;
    01088     }
    01089
    01090     tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
    01091     track = AxisToTrack(axis);
    01092
    01093     layout_ptr = AllocaM(byte, numtracks * plat_len);
    01094     GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
    01095
    01096     numtracks_orig = numtracks;
    01097
    01098     SmallVector<Train*, 4> affected_vehicles;
    01099     do {
    01100       TileIndex tile = tile_org;
    01101       int w = plat_len;
    01102       do {
    01103         byte layout = *layout_ptr++;
    01104         if (IsRailStationTile(tile) && HasStationReservation(tile)) {
    01105           /* Check for trains having a reservation for this tile. */
    01106           Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
    01107           if (v != NULL) {
    01108             FreeTrainTrackReservation(v);
    01109             *affected_vehicles.Append() = v;
    01110             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
    01111             for (; v->Next() != NULL; v = v->Next()) { }
    01112             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
    01113           }
    01114         }
    01115
    01116         /* Remove animation if overbuilding */
    01117         DeleteAnimatedTile(tile);
    01118         byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
    01119         MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
    01120         /* Free the spec if we overbuild something */
    01121         DeallocateSpecFromStation(st, old_specindex);
    01122
    01123         SetCustomStationSpecIndex(tile, specindex);
    01124         SetStationTileRandomBits(tile, GB(Random(), 0, 4));
    01125         SetStationAnimationFrame(tile, 0);
    01126
    01127         if (statspec != NULL) {
    01128           /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
    01129           uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
    01130
    01131           /* As the station is not yet completely finished, the station does not yet exist. */
    01132           uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
    01133           if (callback != CALLBACK_FAILED && callback < 8) SetStationGfx(tile, (callback & ~1) + axis);
    01134
    01135           /* Trigger station animation -- after building? */
    01136           StationAnimationTrigger(st, tile, STAT_ANIM_BUILT);
    01137         }
    01138
    01139         tile += tile_delta;
    01140       } while (--w);
    01141       AddTrackToSignalBuffer(tile_org, track, _current_company);
    01142       YapfNotifyTrackLayoutChange(tile_org, track);
    01143       tile_org += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
    01144     } while (--numtracks);
    01145
    01146     for (uint i = 0; i < affected_vehicles.Length(); ++i) {
    01147       /* Restore reservations of trains. */
    01148       Train *v = affected_vehicles[i];
    01149       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
    01150       TryPathReserve(v, true, true);
    01151       for (; v->Next() != NULL; v = v->Next()) { }
    01152       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
    01153     }
    01154
    01155     st->MarkTilesDirty(false);
    01156     st->UpdateVirtCoord();
    01157     UpdateStationAcceptance(st, false);
    01158     st->RecomputeIndustriesNear();
    01159     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
    01160     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
    01161     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
    01162   }
    01163
    01164   return cost;
    01165 }
    01166
    01167 static void MakeRailStationAreaSmaller(BaseStation *st)
    01168 {
    01169   TileArea ta = st->train_station;
    01170
    01171 restart:
    01172
    01173   /* too small? */
    01174   if (ta.w != 0 && ta.h != 0) {
    01175     /* check the left side, x = constant, y changes */
    01176     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
    01177       /* the left side is unused? */
    01178       if (++i == ta.h) {
    01179         ta.tile += TileDiffXY(1, 0);
    01180         ta.w--;
    01181         goto restart;
    01182       }
    01183     }
    01184
    01185     /* check the right side, x = constant, y changes */
    01186     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
    01187       /* the right side is unused? */
    01188       if (++i == ta.h) {
    01189         ta.w--;
    01190         goto restart;
    01191       }
    01192     }
    01193
    01194     /* check the upper side, y = constant, x changes */
    01195     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
    01196       /* the left side is unused? */
    01197       if (++i == ta.w) {
    01198         ta.tile += TileDiffXY(0, 1);
    01199         ta.h--;
    01200         goto restart;
    01201       }
    01202     }
    01203
    01204     /* check the lower side, y = constant, x changes */
    01205     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
    01206       /* the left side is unused? */
    01207       if (++i == ta.w) {
    01208         ta.h--;
    01209         goto restart;
    01210       }
    01211     }
    01212   } else {
    01213     ta.Clear();
    01214   }
    01215
    01216   st->train_station = ta;
    01217 }
    01218
    01229 template <class T>
    01230 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
    01231 {
    01232   /* Count of the number of tiles removed */
    01233   int quantity = 0;
    01234   CommandCost total_cost(EXPENSES_CONSTRUCTION);
    01235
    01236   /* Do the action for every tile into the area */
    01237   TILE_AREA_LOOP(tile, ta) {
    01238     /* Make sure the specified tile is a rail station */
    01239     if (!HasStationTileRail(tile)) continue;
    01240
    01241     /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
    01242     if (!EnsureNoVehicleOnGround(tile)) continue;
    01243
    01244     /* Check ownership of station */
    01245     T *st = T::GetByTile(tile);
    01246     if (st == NULL) continue;
    01247     if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) continue;
    01248
    01249     /* Do not allow removing from stations if non-uniform stations are not enabled
    01250      * The check must be here to give correct error message
    01251      */
    01252     if (!_settings_game.station.nonuniform_stations) return_cmd_error(STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED);
    01253
    01254     /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
    01255     quantity++;
    01256
    01257     if (flags & DC_EXEC) {
    01258       /* read variables before the station tile is removed */
    01259       uint specindex = GetCustomStationSpecIndex(tile);
    01260       Track track = GetRailStationTrack(tile);
    01261       Owner owner = GetTileOwner(tile);
    01262       RailType rt = GetRailType(tile);
    01263       Train *v = NULL;
    01264
    01265       if (HasStationReservation(tile)) {
    01266         v = GetTrainForReservation(tile, track);
    01267         if (v != NULL) {
    01268           /* Free train reservation. */
    01269           FreeTrainTrackReservation(v);
    01270           if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
    01271           Vehicle *temp = v;
    01272           for (; temp->Next() != NULL; temp = temp->Next()) { }
    01273           if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
    01274         }
    01275       }
    01276
    01277       DoClearSquare(tile);
    01278       if (keep_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
    01279
    01280       st->rect.AfterRemoveTile(st, tile);
    01281       AddTrackToSignalBuffer(tile, track, owner);
    01282       YapfNotifyTrackLayoutChange(tile, track);
    01283
    01284       DeallocateSpecFromStation(st, specindex);
    01285
    01286       affected_stations.Include(st);
    01287
    01288       if (v != NULL) {
    01289         /* Restore station reservation. */
    01290         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
    01291         TryPathReserve(v, true, true);
    01292         for (; v->Next() != NULL; v = v->Next()) { }
    01293         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
    01294       }
    01295     }
    01296     if (keep_rail) {
    01297       /* Don't refund the 'steel' of the track! */
    01298       total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
    01299     }
    01300   }
    01301
    01302   if (quantity == 0) return CMD_ERROR;
    01303
    01304   for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
    01305     T *st = *stp;
    01306
    01307     /* now we need to make the "spanned" area of the railway station smaller
    01308      * if we deleted something at the edges.
    01309      * we also need to adjust train_tile. */
    01310     MakeRailStationAreaSmaller(st);
    01311     UpdateStationSignCoord(st);
    01312
    01313     /* if we deleted the whole station, delete the train facility. */
    01314     if (st->train_station.tile == INVALID_TILE) {
    01315       st->facilities &= ~FACIL_TRAIN;
    01316       SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
    01317       st->UpdateVirtCoord();
    01318       DeleteStationIfEmpty(st);
    01319     }
    01320   }
    01321
    01322   total_cost.AddCost(quantity * removal_cost);
    01323   return total_cost;
    01324 }
    01325
    01336 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01337 {
    01338   TileIndex end = p1 == 0 ? start : p1;
    01339   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
    01340
    01341   TileArea ta(start, end);
    01342   SmallVector<Station *, 4> affected_stations;
    01343
    01344   CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
    01345   if (ret.Failed()) return ret;
    01346
    01347   /* Do all station specific functions here. */
    01348   for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
    01349     Station *st = *stp;
    01350
    01351     if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
    01352     st->MarkTilesDirty(false);
    01353     st->RecomputeIndustriesNear();
    01354   }
    01355
    01356   /* Now apply the rail cost to the number that we deleted */
    01357   return ret;
    01358 }
    01359
    01370 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01371 {
    01372   TileIndex end = p1 == 0 ? start : p1;
    01373   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
    01374
    01375   TileArea ta(start, end);
    01376   SmallVector<Waypoint *, 4> affected_stations;
    01377
    01378   return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
    01379 }
    01380
    01381
    01389 template <class T>
    01390 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
    01391 {
    01392   /* Current company owns the station? */
    01393   if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) return CMD_ERROR;
    01394
    01395   /* determine width and height of platforms */
    01396   TileArea ta = st->train_station;
    01397
    01398   assert(ta.w != 0 && ta.h != 0);
    01399
    01400   CommandCost cost(EXPENSES_CONSTRUCTION);
    01401   /* clear all areas of the station */
    01402   TILE_AREA_LOOP(tile, ta) {
    01403     /* for nonuniform stations, only remove tiles that are actually train station tiles */
    01404     if (!st->TileBelongsToRailStation(tile)) continue;
    01405
    01406     if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
    01407
    01408     cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
    01409     if (flags & DC_EXEC) {
    01410       /* read variables before the station tile is removed */
    01411       Track track = GetRailStationTrack(tile);
    01412       Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
    01413       Train *v = NULL;
    01414       if (HasStationReservation(tile)) {
    01415         v = GetTrainForReservation(tile, track);
    01416         if (v != NULL) FreeTrainTrackReservation(v);
    01417       }
    01418       DoClearSquare(tile);
    01419       AddTrackToSignalBuffer(tile, track, owner);
    01420       YapfNotifyTrackLayoutChange(tile, track);
    01421       if (v != NULL) TryPathReserve(v, true);
    01422     }
    01423   }
    01424
    01425   if (flags & DC_EXEC) {
    01426     st->rect.AfterRemoveRect(st, st->train_station.tile, st->train_station.w, st->train_station.h);
    01427
    01428     st->train_station.Clear();
    01429
    01430     st->facilities &= ~FACIL_TRAIN;
    01431
    01432     free(st->speclist);
    01433     st->num_specs = 0;
    01434     st->speclist  = NULL;
    01435     st->cached_anim_triggers = 0;
    01436
    01437     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
    01438     st->UpdateVirtCoord();
    01439     DeleteStationIfEmpty(st);
    01440   }
    01441
    01442   return cost;
    01443 }
    01444
    01451 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
    01452 {
    01453   /* if there is flooding and non-uniform stations are enabled, remove platforms tile by tile */
    01454   if (_current_company == OWNER_WATER && _settings_game.station.nonuniform_stations) {
    01455     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
    01456   }
    01457
    01458   Station *st = Station::GetByTile(tile);
    01459   CommandCost cost = RemoveRailStation(st, flags);
    01460
    01461   if (flags & DC_EXEC) st->RecomputeIndustriesNear();
    01462
    01463   return cost;
    01464 }
    01465
    01472 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
    01473 {
    01474   /* if there is flooding and non-uniform stations are enabled, remove waypoints tile by tile */
    01475   if (_current_company == OWNER_WATER && _settings_game.station.nonuniform_stations) {
    01476     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
    01477   }
    01478
    01479   return RemoveRailStation(Waypoint::GetByTile(tile), flags);
    01480 }
    01481
    01482
    01488 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
    01489 {
    01490   RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
    01491
    01492   if (*primary_stop == NULL) {
    01493     /* we have no roadstop of the type yet, so write a "primary stop" */
    01494     return primary_stop;
    01495   } else {
    01496     /* there are stops already, so append to the end of the list */
    01497     RoadStop *stop = *primary_stop;
    01498     while (stop->next != NULL) stop = stop->next;
    01499     return &stop->next;
    01500   }
    01501 }
    01502
    01515 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01516 {
    01517   bool type = HasBit(p2, 0);
    01518   bool is_drive_through = HasBit(p2, 1);
    01519   bool build_over_road  = is_drive_through && IsNormalRoadTile(tile);
    01520   RoadTypes rts = (RoadTypes)GB(p2, 2, 2);
    01521   StationID station_to_join = GB(p2, 16, 16);
    01522   bool reuse = (station_to_join != NEW_STATION);
    01523   if (!reuse) station_to_join = INVALID_STATION;
    01524   bool distant_join = (station_to_join != INVALID_STATION);
    01525   Owner tram_owner = _current_company;
    01526   Owner road_owner = _current_company;
    01527
    01528   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
    01529
    01530   if (!AreValidRoadTypes(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
    01531
    01532   /* Trams only have drive through stops */
    01533   if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
    01534
    01535   /* Saveguard the parameters */
    01536   if (!IsValidDiagDirection((DiagDirection)p1)) return CMD_ERROR;
    01537   /* If it is a drive-through stop check for valid axis */
    01538   if (is_drive_through && !IsValidAxis((Axis)p1)) return CMD_ERROR;
    01539   /* Road bits in the wrong direction */
    01540   if (build_over_road && (GetAllRoadBits(tile) & ((Axis)p1 == AXIS_X ? ROAD_Y : ROAD_X)) != 0) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
    01541
    01542   if (!CheckIfAuthorityAllowsNewStation(tile, flags)) return CMD_ERROR;
    01543
    01544   RoadTypes cur_rts = IsNormalRoadTile(tile) ? GetRoadTypes(tile) : ROADTYPES_NONE;
    01545   uint num_roadbits = 0;
    01546   /* Not allowed to build over this road */
    01547   if (build_over_road) {
    01548     /* there is a road, check if we can build road+tram stop over it */
    01549     if (HasBit(cur_rts, ROADTYPE_ROAD)) {
    01550       road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    01551       if (road_owner == OWNER_TOWN) {
    01552         if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
    01553       } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE && !CheckOwnership(road_owner)) {
    01554         return CMD_ERROR;
    01555       }
    01556       num_roadbits += CountBits(GetRoadBits(tile, ROADTYPE_ROAD));
    01557     }
    01558
    01559     /* there is a tram, check if we can build road+tram stop over it */
    01560     if (HasBit(cur_rts, ROADTYPE_TRAM)) {
    01561       tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
    01562       if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE && !CheckOwnership(tram_owner)) {
    01563         return CMD_ERROR;
    01564       }
    01565       num_roadbits += CountBits(GetRoadBits(tile, ROADTYPE_TRAM));
    01566     }
    01567
    01568     /* Don't allow building the roadstop when vehicles are already driving on it */
    01569     if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
    01570
    01571     /* Do not remove roadtypes! */
    01572     rts |= cur_rts;
    01573   }
    01574
    01575   CommandCost cost = CheckFlatLandBelow(tile, 1, 1, flags, is_drive_through ? 5 << p1 : 1 << p1, NULL, !build_over_road);
    01576   if (cost.Failed()) return cost;
    01577   uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
    01578   cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
    01579
    01580   Station *st = NULL;
    01581   CommandCost ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 5), TileArea(tile, 1, 1), &st);
    01582   if (ret.Failed()) return ret;
    01583
    01584   /* Find a deleted station close to us */
    01585   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
    01586
    01587   /* give us a road stop in the list, and check if something went wrong */
    01588   if (!RoadStop::CanAllocateItem()) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
    01589
    01590   if (st != NULL) {
    01591     if (st->owner != _current_company) {
    01592       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
    01593     }
    01594
    01595     if (!st->rect.BeforeAddTile(tile, StationRect::ADD_TEST)) return CMD_ERROR;
    01596   } else {
    01597     /* allocate and initialize new station */
    01598     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    01599
    01600     if (flags & DC_EXEC) {
    01601       st = new Station(tile);
    01602
    01603       st->town = ClosestTownFromTile(tile, UINT_MAX);
    01604       st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
    01605
    01606       if (Company::IsValidID(_current_company)) {
    01607         SetBit(st->town->have_ratings, _current_company);
    01608       }
    01609     }
    01610   }
    01611
    01612   cost.AddCost(_price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
    01613
    01614   if (flags & DC_EXEC) {
    01615     RoadStop *road_stop = new RoadStop(tile);
    01616     /* Insert into linked list of RoadStops */
    01617     RoadStop **currstop = FindRoadStopSpot(type, st);
    01618     *currstop = road_stop;
    01619
    01620     if (type) {
    01621       st->truck_station.Add(tile);
    01622     } else {
    01623       st->bus_station.Add(tile);
    01624     }
    01625
    01626     /* initialize an empty station */
    01627     st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, tile);
    01628
    01629     st->rect.BeforeAddTile(tile, StationRect::ADD_TRY);
    01630
    01631     RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
    01632     if (is_drive_through) {
    01633       MakeDriveThroughRoadStop(tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts, (Axis)p1);
    01634       road_stop->MakeDriveThrough();
    01635     } else {
    01636       MakeRoadStop(tile, st->owner, st->index, rs_type, rts, (DiagDirection)p1);
    01637     }
    01638
    01639     st->UpdateVirtCoord();
    01640     UpdateStationAcceptance(st, false);
    01641     st->RecomputeIndustriesNear();
    01642     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
    01643     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
    01644     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
    01645   }
    01646   return cost;
    01647 }
    01648
    01649
    01650 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
    01651 {
    01652   if (v->type == VEH_ROAD) {
    01653     /* Okay... we are a road vehicle on a drive through road stop.
    01654      * But that road stop has just been removed, so we need to make
    01655      * sure we are in a valid state... however, vehicles can also
    01656      * turn on road stop tiles, so only clear the 'road stop' state
    01657      * bits and only when the state was 'in road stop', otherwise
    01658      * we'll end up clearing the turn around bits. */
    01659     RoadVehicle *rv = RoadVehicle::From(v);
    01660     if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
    01661   }
    01662
    01663   return NULL;
    01664 }
    01665
    01666
    01673 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
    01674 {
    01675   Station *st = Station::GetByTile(tile);
    01676
    01677   if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
    01678     return CMD_ERROR;
    01679   }
    01680
    01681   bool is_truck = IsTruckStop(tile);
    01682
    01683   RoadStop **primary_stop;
    01684   RoadStop *cur_stop;
    01685   if (is_truck) { // truck stop
    01686     primary_stop = &st->truck_stops;
    01687     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
    01688   } else {
    01689     primary_stop = &st->bus_stops;
    01690     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
    01691   }
    01692
    01693   assert(cur_stop != NULL);
    01694
    01695   /* don't do the check for drive-through road stops when company bankrupts */
    01696   if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
    01697     /* remove the 'going through road stop' status from all vehicles on that tile */
    01698     if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
    01699   } else {
    01700     if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
    01701   }
    01702
    01703   if (flags & DC_EXEC) {
    01704     if (*primary_stop == cur_stop) {
    01705       /* removed the first stop in the list */
    01706       *primary_stop = cur_stop->next;
    01707       /* removed the only stop? */
    01708       if (*primary_stop == NULL) {
    01709         st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
    01710       }
    01711     } else {
    01712       /* tell the predecessor in the list to skip this stop */
    01713       RoadStop *pred = *primary_stop;
    01714       while (pred->next != cur_stop) pred = pred->next;
    01715       pred->next = cur_stop->next;
    01716     }
    01717
    01718     if (IsDriveThroughStopTile(tile)) {
    01719       /* Clears the tile for us */
    01720       cur_stop->ClearDriveThrough();
    01721     } else {
    01722       DoClearSquare(tile);
    01723     }
    01724
    01725     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
    01726     delete cur_stop;
    01727
    01728     /* Make sure no vehicle is going to the old roadstop */
    01729     RoadVehicle *v;
    01730     FOR_ALL_ROADVEHICLES(v) {
    01731       if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
    01732           v->dest_tile == tile) {
    01733         v->dest_tile = v->GetOrderStationLocation(st->index);
    01734       }
    01735     }
    01736
    01737     st->rect.AfterRemoveTile(st, tile);
    01738
    01739     st->UpdateVirtCoord();
    01740     st->RecomputeIndustriesNear();
    01741     DeleteStationIfEmpty(st);
    01742
    01743     /* Update the tile area of the truck/bus stop */
    01744     if (is_truck) {
    01745       st->truck_station.Clear();
    01746       for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
    01747     } else {
    01748       st->bus_station.Clear();
    01749       for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
    01750     }
    01751   }
    01752
    01753   return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
    01754 }
    01755
    01764 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01765 {
    01766   /* Make sure the specified tile is a road stop of the correct type */
    01767   if (!IsTileType(tile, MP_STATION) || !IsRoadStop(tile) || (uint32)GetRoadStopType(tile) != GB(p2, 0, 1)) return CMD_ERROR;
    01768
    01769   /* Save the stop info before it is removed */
    01770   bool is_drive_through = IsDriveThroughStopTile(tile);
    01771   RoadTypes rts = GetRoadTypes(tile);
    01772   RoadBits road_bits = IsDriveThroughStopTile(tile) ?
    01773       ((GetRoadStopDir(tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
    01774       DiagDirToRoadBits(GetRoadStopDir(tile));
    01775
    01776   Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    01777   Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
    01778   CommandCost ret = RemoveRoadStop(tile, flags);
    01779
    01780   /* If the stop was a drive-through stop replace the road */
    01781   if ((flags & DC_EXEC) && ret.Succeeded() && is_drive_through) {
    01782     /* Rebuild the drive throuhg road stop. As a road stop can only be
    01783      * removed by the owner of the roadstop, _current_company is the
    01784      * owner of the road stop. */
    01785     MakeRoadNormal(tile, road_bits, rts, ClosestTownFromTile(tile, UINT_MAX)->index,
    01786         road_owner, tram_owner);
    01787   }
    01788
    01789   return ret;
    01790 }
    01791
    01799 static uint GetMinimalAirportDistanceToTile(const AirportSpec *as, TileIndex town_tile, TileIndex airport_tile)
    01800 {
    01801   uint ttx = TileX(town_tile); // X, Y of town
    01802   uint tty = TileY(town_tile);
    01803
    01804   uint atx = TileX(airport_tile); // X, Y of northern airport corner
    01805   uint aty = TileY(airport_tile);
    01806
    01807   uint btx = TileX(airport_tile) + as->size_x - 1; // X, Y of southern corner
    01808   uint bty = TileY(airport_tile) + as->size_y - 1;
    01809
    01810   /* if ttx < atx, dx = atx - ttx
    01811    * if atx <= ttx <= btx, dx = 0
    01812    * else, dx = ttx - btx (similiar for dy) */
    01813   uint dx = ttx < atx ? atx - ttx : (ttx <= btx ? 0 : ttx - btx);
    01814   uint dy = tty < aty ? aty - tty : (tty <= bty ? 0 : tty - bty);
    01815
    01816   return dx + dy;
    01817 }
    01818
    01827 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIndex town_tile, TileIndex tile)
    01828 {
    01829   /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
    01830    * So no need to go any further*/
    01831   if (as->noise_level < 2) return as->noise_level;
    01832
    01833   uint distance = GetMinimalAirportDistanceToTile(as, town_tile, tile);
    01834
    01835   /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
    01836    * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
    01837    * Basically, it says that the less tolerant a town is, the bigger the distance before
    01838    * an actual decrease can be granted */
    01839   uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
    01840
    01841   /* now, we want to have the distance segmented using the distance judged bareable by town
    01842    * This will give us the coefficient of reduction the distance provides. */
    01843   uint noise_reduction = distance / town_tolerance_distance;
    01844
    01845   /* If the noise reduction equals the airport noise itself, don't give it for free.
    01846    * Otherwise, simply reduce the airport's level. */
    01847   return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
    01848 }
    01849
    01857 Town *AirportGetNearestTown(const AirportSpec *as, TileIndex airport_tile)
    01858 {
    01859   Town *t, *nearest = NULL;
    01860   uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
    01861   uint mindist = UINT_MAX - add; // prevent overflow
    01862   FOR_ALL_TOWNS(t) {
    01863     if (DistanceManhattan(t->xy, airport_tile) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
    01864       uint dist = GetMinimalAirportDistanceToTile(as, t->xy, airport_tile);
    01865       if (dist < mindist) {
    01866         nearest = t;
    01867         mindist = dist;
    01868       }
    01869     }
    01870   }
    01871
    01872   return nearest;
    01873 }
    01874
    01875
    01877 void UpdateAirportsNoise()
    01878 {
    01879   Town *t;
    01880   const Station *st;
    01881
    01882   FOR_ALL_TOWNS(t) t->noise_reached = 0;
    01883
    01884   FOR_ALL_STATIONS(st) {
    01885     if (st->airport_tile != INVALID_TILE) {
    01886       const AirportSpec *as = st->GetAirportSpec();
    01887       Town *nearest = AirportGetNearestTown(as, st->airport_tile);
    01888       nearest->noise_reached += GetAirportNoiseLevelForTown(as, nearest->xy, st->airport_tile);
    01889     }
    01890   }
    01891 }
    01892
    01903 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01904 {
    01905   bool airport_upgrade = true;
    01906   StationID station_to_join = GB(p2, 16, 16);
    01907   bool reuse = (station_to_join != NEW_STATION);
    01908   if (!reuse) station_to_join = INVALID_STATION;
    01909   bool distant_join = (station_to_join != INVALID_STATION);
    01910
    01911   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
    01912
    01913   if (p1 >= NUM_AIRPORTS) return CMD_ERROR;
    01914
    01915   if (!CheckIfAuthorityAllowsNewStation(tile, flags)) {
    01916     return CMD_ERROR;
    01917   }
    01918
    01919   /* Check if a valid, buildable airport was chosen for construction */
    01920   const AirportSpec *as = AirportSpec::Get(p1);
    01921   if (!as->IsAvailable()) return CMD_ERROR;
    01922
    01923   Town *t = ClosestTownFromTile(tile, UINT_MAX);
    01924   int w = as->size_x;
    01925   int h = as->size_y;
    01926
    01927   if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
    01928     _error_message = STR_ERROR_STATION_TOO_SPREAD_OUT;
    01929     return CMD_ERROR;
    01930   }
    01931
    01932   CommandCost cost = CheckFlatLandBelow(tile, w, h, flags, 0, NULL);
    01933   if (cost.Failed()) return cost;
    01934
    01935   /* Go get the final noise level, that is base noise minus factor from distance to town center */
    01936   Town *nearest = AirportGetNearestTown(as, tile);
    01937   uint newnoise_level = GetAirportNoiseLevelForTown(as, nearest->xy, tile);
    01938
    01939   /* Check if local auth would allow a new airport */
    01940   StringID authority_refuse_message = STR_NULL;
    01941
    01942   if (_settings_game.economy.station_noise_level) {
    01943     /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
    01944     if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
    01945       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
    01946     }
    01947   } else {
    01948     uint num = 0;
    01949     const Station *st;
    01950     FOR_ALL_STATIONS(st) {
    01951       if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport_type != AT_OILRIG) num++;
    01952     }
    01953     if (num >= 2) {
    01954       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
    01955     }
    01956   }
    01957
    01958   if (authority_refuse_message != STR_NULL) {
    01959     SetDParam(0, t->index);
    01960     return_cmd_error(authority_refuse_message);
    01961   }
    01962
    01963   Station *st = NULL;
    01964   CommandCost ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
    01965   if (ret.Failed()) return ret;
    01966
    01967   /* Distant join */
    01968   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
    01969
    01970   /* Find a deleted station close to us */
    01971   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
    01972
    01973   if (st != NULL) {
    01974     if (st->owner != _current_company) {
    01975       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
    01976     }
    01977
    01978     if (!st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST)) return CMD_ERROR;
    01979
    01980     if (st->airport_tile != INVALID_TILE) {
    01981       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
    01982     }
    01983   } else {
    01984     airport_upgrade = false;
    01985
    01986     /* allocate and initialize new station */
    01987     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    01988
    01989     if (flags & DC_EXEC) {
    01990       st = new Station(tile);
    01991
    01992       st->town = t;
    01993       st->string_id = GenerateStationName(st, tile, !(GetAirport(p1)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
    01994
    01995       if (Company::IsValidID(_current_company)) {
    01996         SetBit(st->town->have_ratings, _current_company);
    01997       }
    01998     }
    01999   }
    02000
    02001   cost.AddCost(_price[PR_BUILD_STATION_AIRPORT] * w * h);
    02002
    02003   if (flags & DC_EXEC) {
    02004     /* Always add the noise, so there will be no need to recalculate when option toggles */
    02005     nearest->noise_reached += newnoise_level;
    02006
    02007     st->airport_tile = tile;
    02008     st->AddFacility(FACIL_AIRPORT, tile);
    02009     st->airport_type = (byte)p1;
    02010     st->airport_flags = 0;
    02011
    02012     st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
    02013
    02014     /* if airport was demolished while planes were en-route to it, the
    02015      * positions can no longer be the same (v->u.air.pos), since different
    02016      * airports have different indexes. So update all planes en-route to this
    02017      * airport. Only update if
    02018      * 1. airport is upgraded
    02019      * 2. airport is added to existing station (unfortunately unavoideable)
    02020      */
    02021     if (airport_upgrade) UpdateAirplanesOnNewStation(st);
    02022
    02023     const AirportTileTable *it = as->table[0];
    02024     do {
    02025       TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
    02026       MakeAirport(cur_tile, st->owner, st->index, it->gfx);
    02027     } while ((++it)->ti.x != -0x80);
    02028
    02029     st->UpdateVirtCoord();
    02030     UpdateStationAcceptance(st, false);
    02031     st->RecomputeIndustriesNear();
    02032     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
    02033     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
    02034     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
    02035
    02036     if (_settings_game.economy.station_noise_level) {
    02037       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
    02038     }
    02039   }
    02040
    02041   return cost;
    02042 }
    02043
    02050 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
    02051 {
    02052   Station *st = Station::GetByTile(tile);
    02053
    02054   if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
    02055     return CMD_ERROR;
    02056   }
    02057
    02058   tile = st->airport_tile;
    02059
    02060   const AirportSpec *as = st->GetAirportSpec();
    02061   int w = as->size_x;
    02062   int h = as->size_y;
    02063
    02064   CommandCost cost(EXPENSES_CONSTRUCTION);
    02065
    02066   const Aircraft *a;
    02067   FOR_ALL_AIRCRAFT(a) {
    02068     if (!a->IsNormalAircraft()) continue;
    02069     if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
    02070   }
    02071
    02072   TILE_LOOP(tile_cur, w, h, tile) {
    02073     if (!EnsureNoVehicleOnGround(tile_cur)) return CMD_ERROR;
    02074
    02075     if (!st->TileBelongsToAirport(tile_cur)) continue;
    02076
    02077     cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
    02078
    02079     if (flags & DC_EXEC) {
    02080       DeleteAnimatedTile(tile_cur);
    02081       DoClearSquare(tile_cur);
    02082     }
    02083   }
    02084
    02085   if (flags & DC_EXEC) {
    02086     for (uint i = 0; i < as->nof_depots; ++i) {
    02087       DeleteWindowById(
    02088         WC_VEHICLE_DEPOT, st->GetHangarTile(i)
    02089       );
    02090     }
    02091
    02092     /* Go get the final noise level, that is base noise minus factor from distance to town center.
    02093      * And as for construction, always remove it, even if the setting is not set, in order to avoid the
    02094      * need of recalculation */
    02095     Town *nearest = AirportGetNearestTown(as, tile);
    02096     nearest->noise_reached -= GetAirportNoiseLevelForTown(as, nearest->xy, tile);
    02097
    02098     st->rect.AfterRemoveRect(st, tile, w, h);
    02099
    02100     st->airport_tile = INVALID_TILE;
    02101     st->facilities &= ~FACIL_AIRPORT;
    02102
    02103     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
    02104
    02105     if (_settings_game.economy.station_noise_level) {
    02106       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
    02107     }
    02108
    02109     st->UpdateVirtCoord();
    02110     st->RecomputeIndustriesNear();
    02111     DeleteStationIfEmpty(st);
    02112   }
    02113
    02114   return cost;
    02115 }
    02116
    02123 bool HasStationInUse(StationID station, CompanyID company)
    02124 {
    02125   const Vehicle *v;
    02126   FOR_ALL_VEHICLES(v) {
    02127     if (company == INVALID_COMPANY || v->owner == company) {
    02128       const Order *order;
    02129       FOR_VEHICLE_ORDERS(v, order) {
    02130         if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
    02131           return true;
    02132         }
    02133       }
    02134     }
    02135   }
    02136   return false;
    02137 }
    02138
    02139 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
    02140   {-1,  0},
    02141   { 0,  0},
    02142   { 0,  0},
    02143   { 0, -1}
    02144 };
    02145 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
    02146 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
    02147
    02156 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02157 {
    02158   StationID station_to_join = GB(p2, 16, 16);
    02159   bool reuse = (station_to_join != NEW_STATION);
    02160   if (!reuse) station_to_join = INVALID_STATION;
    02161   bool distant_join = (station_to_join != INVALID_STATION);
    02162
    02163   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
    02164
    02165   DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile, NULL));
    02166   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    02167   direction = ReverseDiagDir(direction);
    02168
    02169   /* Docks cannot be placed on rapids */
    02170   if (IsWaterTile(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    02171
    02172   if (!CheckIfAuthorityAllowsNewStation(tile, flags)) return CMD_ERROR;
    02173
    02174   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    02175
    02176   if (DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR).Failed()) return CMD_ERROR;
    02177
    02178   TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
    02179
    02180   if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
    02181     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    02182   }
    02183
    02184   if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    02185
    02186   /* Get the water class of the water tile before it is cleared.*/
    02187   WaterClass wc = GetWaterClass(tile_cur);
    02188
    02189   if (DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR).Failed()) return CMD_ERROR;
    02190
    02191   tile_cur += TileOffsByDiagDir(direction);
    02192   if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
    02193     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    02194   }
    02195
    02196   /* middle */
    02197   Station *st = NULL;
    02198   CommandCost ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
    02199       TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
    02200           _dock_w_chk[direction], _dock_h_chk[direction]), &st);
    02201   if (ret.Failed()) return ret;
    02202
    02203   /* Distant join */
    02204   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
    02205
    02206   /* Find a deleted station close to us */
    02207   if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
    02208
    02209   if (st != NULL) {
    02210     if (st->owner != _current_company) {
    02211       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
    02212     }
    02213
    02214     if (!st->rect.BeforeAddRect(
    02215         tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
    02216         _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST)) return CMD_ERROR;
    02217
    02218     if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
    02219   } else {
    02220     /* allocate and initialize new station */
    02221     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    02222
    02223     if (flags & DC_EXEC) {
    02224       st = new Station(tile);
    02225
    02226       st->town = ClosestTownFromTile(tile, UINT_MAX);
    02227       st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
    02228
    02229       if (Company::IsValidID(_current_company)) {
    02230         SetBit(st->town->have_ratings, _current_company);
    02231       }
    02232     }
    02233   }
    02234
    02235   if (flags & DC_EXEC) {
    02236     st->dock_tile = tile;
    02237     st->AddFacility(FACIL_DOCK, tile);
    02238
    02239     st->rect.BeforeAddRect(
    02240         tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
    02241         _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
    02242
    02243     MakeDock(tile, st->owner, st->index, direction, wc);
    02244
    02245     st->UpdateVirtCoord();
    02246     UpdateStationAcceptance(st, false);
    02247     st->RecomputeIndustriesNear();
    02248     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
    02249     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
    02250     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
    02251   }
    02252
    02253   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
    02254 }
    02255
    02262 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
    02263 {
    02264   Station *st = Station::GetByTile(tile);
    02265   if (!CheckOwnership(st->owner)) return CMD_ERROR;
    02266
    02267   TileIndex tile1 = st->dock_tile;
    02268   TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
    02269
    02270   if (!EnsureNoVehicleOnGround(tile1)) return CMD_ERROR;
    02271   if (!EnsureNoVehicleOnGround(tile2)) return CMD_ERROR;
    02272
    02273   if (flags & DC_EXEC) {
    02274     DoClearSquare(tile1);
    02275     MakeWaterKeepingClass(tile2, st->owner);
    02276
    02277     st->rect.AfterRemoveTile(st, tile1);
    02278     st->rect.AfterRemoveTile(st, tile2);
    02279
    02280     MarkTileDirtyByTile(tile2);
    02281
    02282     st->dock_tile = INVALID_TILE;
    02283     st->facilities &= ~FACIL_DOCK;
    02284
    02285     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
    02286     st->UpdateVirtCoord();
    02287     st->RecomputeIndustriesNear();
    02288     DeleteStationIfEmpty(st);
    02289   }
    02290
    02291   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
    02292 }
    02293
    02294 #include "table/station_land.h"
    02295
    02296 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
    02297 {
    02298   return &_station_display_datas[st][gfx];
    02299 }
    02300
    02301 static void DrawTile_Station(TileInfo *ti)
    02302 {
    02303   const DrawTileSprites *t = NULL;
    02304   RoadTypes roadtypes;
    02305   int32 total_offset;
    02306   int32 custom_ground_offset;
    02307   const RailtypeInfo *rti = NULL;
    02308   uint32 relocation = 0;
    02309   const BaseStation *st = NULL;
    02310   const StationSpec *statspec = NULL;
    02311
    02312   if (HasStationRail(ti->tile)) {
    02313     rti = GetRailTypeInfo(GetRailType(ti->tile));
    02314     roadtypes = ROADTYPES_NONE;
    02315     total_offset = rti->total_offset;
    02316     custom_ground_offset = rti->custom_ground_offset;
    02317
    02318     if (IsCustomStationSpecIndex(ti->tile)) {
    02319       /* look for customization */
    02320       st = BaseStation::GetByTile(ti->tile);
    02321       statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
    02322
    02323       if (statspec != NULL) {
    02324         uint tile = GetStationGfx(ti->tile);
    02325
    02326         relocation = GetCustomStationRelocation(statspec, st, ti->tile);
    02327
    02328         if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
    02329           uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
    02330           if (callback != CALLBACK_FAILED) tile = (callback & ~1) + GetRailStationAxis(ti->tile);
    02331         }
    02332
    02333         /* Ensure the chosen tile layout is valid for this custom station */
    02334         if (statspec->renderdata != NULL) {
    02335           t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)];
    02336         }
    02337       }
    02338     }
    02339   } else {
    02340     roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
    02341     total_offset = 0;
    02342     custom_ground_offset = 0;
    02343   }
    02344
    02345   if (IsAirport(ti->tile)) {
    02346     switch (GetStationGfx(ti->tile)) {
    02347       case APT_RADAR_GRASS_FENCE_SW:
    02348         t = &_station_display_datas_airport_radar_grass_fence_sw[GetStationAnimationFrame(ti->tile)];
    02349         break;
    02350       case APT_GRASS_FENCE_NE_FLAG:
    02351         t = &_station_display_datas_airport_flag_grass_fence_ne[GetStationAnimationFrame(ti->tile)];
    02352         break;
    02353       case APT_RADAR_FENCE_SW:
    02354         t = &_station_display_datas_airport_radar_fence_sw[GetStationAnimationFrame(ti->tile)];
    02355         break;
    02356       case APT_RADAR_FENCE_NE:
    02357         t = &_station_display_datas_airport_radar_fence_ne[GetStationAnimationFrame(ti->tile)];
    02358         break;
    02359       case APT_GRASS_FENCE_NE_FLAG_2:
    02360         t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetStationAnimationFrame(ti->tile)];
    02361         break;
    02362     }
    02363   }
    02364
    02365   Owner owner = GetTileOwner(ti->tile);
    02366
    02367   PaletteID palette;
    02368   if (Company::IsValidID(owner)) {
    02369     palette = COMPANY_SPRITE_COLOUR(owner);
    02370   } else {
    02371     /* Some stations are not owner by a company, namely oil rigs */
    02372     palette = PALETTE_TO_GREY;
    02373   }
    02374
    02375   if (t == NULL || t->seq == NULL) t = &_station_display_datas[GetStationType(ti->tile)][GetStationGfx(ti->tile)];
    02376
    02377   /* don't show foundation for docks */
    02378   if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
    02379     if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
    02380       /* Station has custom foundations. */
    02381       SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile);
    02382
    02383       if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
    02384         /* Station provides extended foundations. */
    02385
    02386         static const uint8 foundation_parts[] = {
    02387           0, 0, 0, 0, // Invalid,  Invalid,   Invalid,   SLOPE_SW
    02388           0, 1, 2, 3, // Invalid,  SLOPE_EW,  SLOPE_SE,  SLOPE_WSE
    02389           0, 4, 5, 6, // Invalid,  SLOPE_NW,  SLOPE_NS,  SLOPE_NWS
    02390           7, 8, 9     // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
    02391         };
    02392
    02393         AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
    02394       } else {
    02395         /* Draw simple foundations, built up from 8 possible foundation sprites. */
    02396
    02397         /* Each set bit represents one of the eight composite sprites to be drawn.
    02398          * 'Invalid' entries will not drawn but are included for completeness. */
    02399         static const uint8 composite_foundation_parts[] = {
    02400           /* Invalid  (00000000), Invalid   (11010001), Invalid   (11100100), SLOPE_SW  (11100000) */
    02401              0x00,                0xD1,                 0xE4,                 0xE0,
    02402           /* Invalid  (11001010), SLOPE_EW  (11001001), SLOPE_SE  (11000100), SLOPE_WSE (11000000) */
    02403              0xCA,                0xC9,                 0xC4,                 0xC0,
    02404           /* Invalid  (11010010), SLOPE_NW  (10010001), SLOPE_NS  (11100100), SLOPE_NWS (10100000) */
    02405              0xD2,                0x91,                 0xE4,                 0xA0,
    02406           /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
    02407              0x4A,                0x09,                 0x44
    02408         };
    02409
    02410         uint8 parts = composite_foundation_parts[ti->tileh];
    02411
    02412         /* If foundations continue beyond the tile's upper sides then
    02413          * mask out the last two pieces. */
    02414         uint z;
    02415         Slope slope = GetFoundationSlope(ti->tile, &z);
    02416         if (!HasFoundationNW(ti->tile, slope, z)) ClrBit(parts, 6);
    02417         if (!HasFoundationNE(ti->tile, slope, z)) ClrBit(parts, 7);
    02418
    02419         StartSpriteCombine();
    02420         for (int i = 0; i < 8; i++) {
    02421           if (HasBit(parts, i)) {
    02422             AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
    02423           }
    02424         }
    02425         EndSpriteCombine();
    02426       }
    02427
    02428       OffsetGroundSprite(31, 1);
    02429       ti->z += ApplyFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
    02430     } else {
    02431       DrawFoundation(ti, FOUNDATION_LEVELED);
    02432     }
    02433   }
    02434
    02435   if (IsBuoy(ti->tile) || IsDock(ti->tile) || (IsOilRig(ti->tile) && GetWaterClass(ti->tile) != WATER_CLASS_INVALID)) {
    02436     if (ti->tileh == SLOPE_FLAT) {
    02437       DrawWaterClassGround(ti);
    02438     } else {
    02439       assert(IsDock(ti->tile));
    02440       TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
    02441       WaterClass wc = GetWaterClass(water_tile);
    02442       if (wc == WATER_CLASS_SEA) {
    02443         DrawShoreTile(ti->tileh);
    02444       } else {
    02445         DrawClearLandTile(ti, 3);
    02446       }
    02447     }
    02448   } else {
    02449     SpriteID image = t->ground.sprite;
    02450     PaletteID pal  = t->ground.pal;
    02451     if (rti != NULL && rti->UsesOverlay() && (image == SPR_RAIL_TRACK_X || image == SPR_RAIL_TRACK_Y)) {
    02452       SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
    02453       DrawGroundSprite(SPR_FLAT_GRASS_TILE, PAL_NONE);
    02454       DrawGroundSprite(ground + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE);
    02455
    02456       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
    02457         SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
    02458         DrawGroundSprite(overlay + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PALETTE_CRASH);
    02459       }
    02460     } else {
    02461       if (HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
    02462         image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
    02463         image += custom_ground_offset;
    02464       } else {
    02465         image += total_offset;
    02466       }
    02467       DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
    02468
    02469       /* PBS debugging, draw reserved tracks darker */
    02470       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
    02471         const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
    02472         DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
    02473       }
    02474     }
    02475   }
    02476
    02477   if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);
    02478
    02479   if (HasBit(roadtypes, ROADTYPE_TRAM)) {
    02480     Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
    02481     DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
    02482     DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
    02483   }
    02484
    02485   if (IsRailWaypoint(ti->tile)) {
    02486     /* Don't offset the waypoint graphics; they're always the same. */
    02487     total_offset = 0;
    02488   }
    02489
    02490   DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
    02491 }
    02492
    02493 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
    02494 {
    02495   int32 total_offset = 0;
    02496   PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
    02497   const DrawTileSprites *t = &_station_display_datas[st][image];
    02498   const RailtypeInfo *rti = NULL;
    02499
    02500   if (railtype != INVALID_RAILTYPE) {
    02501     rti = GetRailTypeInfo(railtype);
    02502     total_offset = rti->total_offset;
    02503   }
    02504
    02505   SpriteID img = t->ground.sprite;
    02506   if ((img == SPR_RAIL_TRACK_X || img == SPR_RAIL_TRACK_Y) && rti->UsesOverlay()) {
    02507     SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
    02508     DrawSprite(SPR_FLAT_GRASS_TILE, PAL_NONE, x, y);
    02509     DrawSprite(ground + (img == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE, x, y);
    02510   } else {
    02511     DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
    02512   }
    02513
    02514   if (roadtype == ROADTYPE_TRAM) {
    02515     DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
    02516   }
    02517
    02518   /* Default waypoint has no railtype specific sprites */
    02519   DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
    02520 }
    02521
    02522 static uint GetSlopeZ_Station(TileIndex tile, uint x, uint y)
    02523 {
    02524   return GetTileMaxZ(tile);
    02525 }
    02526
    02527 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
    02528 {
    02529   return FlatteningFoundation(tileh);
    02530 }
    02531
    02532 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
    02533 {
    02534   td->owner[0] = GetTileOwner(tile);
    02535   if (IsDriveThroughStopTile(tile)) {
    02536     Owner road_owner = INVALID_OWNER;
    02537     Owner tram_owner = INVALID_OWNER;
    02538     RoadTypes rts = GetRoadTypes(tile);
    02539     if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    02540     if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
    02541
    02542     /* Is there a mix of owners? */
    02543     if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
    02544         (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
    02545       uint i = 1;
    02546       if (road_owner != INVALID_OWNER) {
    02547         td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
    02548         td->owner[i] = road_owner;
    02549         i++;
    02550       }
    02551       if (tram_owner != INVALID_OWNER) {
    02552         td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
    02553         td->owner[i] = tram_owner;
    02554       }
    02555     }
    02556   }
    02557   td->build_date = BaseStation::GetByTile(tile)->build_date;
    02558
    02559   if (HasStationTileRail(tile)) {
    02560     const StationSpec *spec = GetStationSpec(tile);
    02561
    02562     if (spec != NULL) {
    02563       td->station_class = GetStationClassName(spec->sclass);
    02564       td->station_name  = spec->name;
    02565
    02566       if (spec->grffile != NULL) {
    02567         const GRFConfig *gc = GetGRFConfig(spec->grffile->grfid);
    02568         td->grf = gc->name;
    02569       }
    02570     }
    02571   }
    02572
    02573   StringID str;
    02574   switch (GetStationType(tile)) {
    02575     default: NOT_REACHED();
    02576     case STATION_RAIL:     str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
    02577     case STATION_AIRPORT:
    02578       str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
    02579       break;
    02580     case STATION_TRUCK:    str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
    02581     case STATION_BUS:      str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
    02582     case STATION_OILRIG:   str = STR_INDUSTRY_NAME_OIL_RIG; break;
    02583     case STATION_DOCK:     str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
    02584     case STATION_BUOY:     str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
    02585     case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
    02586   }
    02587   td->str = str;
    02588 }
    02589
    02590
    02591 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
    02592 {
    02593   TrackBits trackbits = TRACK_BIT_NONE;
    02594
    02595   switch (mode) {
    02596     case TRANSPORT_RAIL:
    02597       if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
    02598         trackbits = TrackToTrackBits(GetRailStationTrack(tile));
    02599       }
    02600       break;
    02601
    02602     case TRANSPORT_WATER:
    02603       /* buoy is coded as a station, it is always on open water */
    02604       if (IsBuoy(tile)) {
    02605         trackbits = TRACK_BIT_ALL;
    02606         /* remove tracks that connect NE map edge */
    02607         if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
    02608         /* remove tracks that connect NW map edge */
    02609         if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
    02610       }
    02611       break;
    02612
    02613     case TRANSPORT_ROAD:
    02614       if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
    02615         DiagDirection dir = GetRoadStopDir(tile);
    02616         Axis axis = DiagDirToAxis(dir);
    02617
    02618         if (side != INVALID_DIAGDIR) {
    02619           if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
    02620         }
    02621
    02622         trackbits = AxisToTrackBits(axis);
    02623       }
    02624       break;
    02625
    02626     default:
    02627       break;
    02628   }
    02629
    02630   return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
    02631 }
    02632
    02633
    02634 static void TileLoop_Station(TileIndex tile)
    02635 {
    02636   /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
    02637    * hardcoded.....not good */
    02638   switch (GetStationType(tile)) {
    02639     case STATION_AIRPORT:
    02640       if (AirportTileSpec::Get(GetStationGfx(tile))->animation_info != 0xFFFF) {
    02641         AddAnimatedTile(tile);
    02642       }
    02643       break;
    02644
    02645     case STATION_DOCK:
    02646       if (GetTileSlope(tile, NULL) != SLOPE_FLAT) break; // only handle water part
    02647     /* FALL THROUGH */
    02648     case STATION_OILRIG: //(station part)
    02649     case STATION_BUOY:
    02650       TileLoop_Water(tile);
    02651       break;
    02652
    02653     default: break;
    02654   }
    02655 }
    02656
    02657
    02658 static void AnimateTile_Station(TileIndex tile)
    02659 {
    02660   if (HasStationRail(tile)) {
    02661     AnimateStationTile(tile);
    02662     return;
    02663   }
    02664
    02665   if (IsAirport(tile)) {
    02666     const AirportTileSpec *ats = AirportTileSpec::Get(GetStationGfx(tile));
    02667     uint16 mask = (1 << ats->animation_speed) - 1;
    02668     if (ats->animation_info != 0xFFFF && (_tick_counter & mask) == 0) {
    02669       uint8 next_frame = GetStationAnimationFrame(tile) + 1;
    02670       if (next_frame >= GB(ats->animation_info, 0, 8)) next_frame = 0;
    02671       SetStationAnimationFrame(tile, next_frame);
    02672       MarkTileDirtyByTile(tile);
    02673     }
    02674   }
    02675 }
    02676
    02677
    02678 static bool ClickTile_Station(TileIndex tile)
    02679 {
    02680   const BaseStation *st = BaseStation::GetByTile(tile);
    02681
    02682   if (st->facilities & FACIL_WAYPOINT) {
    02683     ShowWaypointWindow(Waypoint::From(st));
    02684   } else if (IsHangar(tile)) {
    02685     ShowDepotWindow(tile, VEH_AIRCRAFT);
    02686   } else {
    02687     ShowStationViewWindow(st->index);
    02688   }
    02689   return true;
    02690 }
    02691
    02692 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
    02693 {
    02694   if (v->type == VEH_TRAIN) {
    02695     StationID station_id = GetStationIndex(tile);
    02696     if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
    02697     if (!IsRailStation(tile) || !Train::From(v)->IsFrontEngine()) return VETSB_CONTINUE;
    02698
    02699     int station_ahead;
    02700     int station_length;
    02701     int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
    02702
    02703     /* Stop whenever that amount of station ahead + the distance from the
    02704      * begin of the platform to the stop location is longer than the length
    02705      * of the platform. Station ahead 'includes' the current tile where the
    02706      * vehicle is on, so we need to substract that. */
    02707     if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
    02708
    02709     DiagDirection dir = DirToDiagDir(v->direction);
    02710
    02711     x &= 0xF;
    02712     y &= 0xF;
    02713
    02714     if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
    02715     if (y == TILE_SIZE / 2) {
    02716       if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
    02717       stop &= TILE_SIZE - 1;
    02718
    02719       if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
    02720       if (x < stop) {
    02721         uint16 spd;
    02722
    02723         v->vehstatus |= VS_TRAIN_SLOWING;
    02724         spd = max(0, (stop - x) * 20 - 15);
    02725         if (spd < v->cur_speed) v->cur_speed = spd;
    02726       }
    02727     }
    02728   } else if (v->type == VEH_ROAD) {
    02729     RoadVehicle *rv = RoadVehicle::From(v);
    02730     if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
    02731       if (IsRoadStop(tile) && rv->IsRoadVehFront()) {
    02732         /* Attempt to allocate a parking bay in a road stop */
    02733         return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
    02734       }
    02735     }
    02736   }
    02737
    02738   return VETSB_CONTINUE;
    02739 }
    02740
    02747 static bool StationHandleBigTick(BaseStation *st)
    02748 {
    02749   if (!st->IsInUse() && ++st->delete_ctr >= 8) {
    02750     delete st;
    02751     return false;
    02752   }
    02753
    02754   if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
    02755
    02756   return true;
    02757 }
    02758
    02759 static inline void byte_inc_sat(byte *p)
    02760 {
    02761   byte b = *p + 1;
    02762   if (b != 0) *p = b;
    02763 }
    02764
    02765 static void UpdateStationRating(Station *st)
    02766 {
    02767   bool waiting_changed = false;
    02768
    02769   byte_inc_sat(&st->time_since_load);
    02770   byte_inc_sat(&st->time_since_unload);
    02771
    02772   const CargoSpec *cs;
    02773   FOR_ALL_CARGOSPECS(cs) {
    02774     GoodsEntry *ge = &st->goods[cs->Index()];
    02775     /* Slowly increase the rating back to his original level in the case we
    02776      *  didn't deliver cargo yet to this station. This happens when a bribe
    02777      *  failed while you didn't moved that cargo yet to a station. */
    02778     if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP) && ge->rating < INITIAL_STATION_RATING) {
    02779       ge->rating++;
    02780     }
    02781
    02782     /* Only change the rating if we are moving this cargo */
    02783     if (HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) {
    02784       byte_inc_sat(&ge->days_since_pickup);
    02785
    02786       bool skip = false;
    02787       int rating = 0;
    02788       uint waiting = ge->cargo.Count();
    02789
    02790       if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
    02791         /* Perform custom station rating. If it succeeds the speed, days in transit and
    02792          * waiting cargo ratings must not be executed. */
    02793
    02794         /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
    02795         uint last_speed = ge->last_speed;
    02796         if (last_speed == 0) last_speed = 0xFF;
    02797
    02798         uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(waiting, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
    02799         /* Convert to the 'old' vehicle types */
    02800         uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
    02801         uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
    02802         if (callback != CALLBACK_FAILED) {
    02803           skip = true;
    02804           rating = GB(callback, 0, 14);
    02805
    02806           /* Simulate a 15 bit signed value */
    02807           if (HasBit(callback, 14)) rating -= 0x4000;
    02808         }
    02809       }
    02810
    02811       if (!skip) {
    02812         int b = ge->last_speed - 85;
    02813         if (b >= 0) rating += b >> 2;
    02814
    02815         byte days = ge->days_since_pickup;
    02816         if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
    02817         (days > 21) ||
    02818         (rating += 25, days > 12) ||
    02819         (rating += 25, days > 6) ||
    02820         (rating += 45, days > 3) ||
    02821         (rating += 35, true);
    02822
    02823         (rating -= 90, waiting > 1500) ||
    02824         (rating += 55, waiting > 1000) ||
    02825         (rating += 35, waiting > 600) ||
    02826         (rating += 10, waiting > 300) ||
    02827         (rating += 20, waiting > 100) ||
    02828         (rating += 10, true);
    02829       }
    02830
    02831       if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
    02832
    02833       byte age = ge->last_age;
    02834       (age >= 3) ||
    02835       (rating += 10, age >= 2) ||
    02836       (rating += 10, age >= 1) ||
    02837       (rating += 13, true);
    02838
    02839       {
    02840         int or_ = ge->rating; // old rating
    02841
    02842         /* only modify rating in steps of -2, -1, 0, 1 or 2 */
    02843         ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
    02844
    02845         /* if rating is <= 64 and more than 200 items waiting,
    02846          * remove some random amount of goods from the station */
    02847         if (rating <= 64 && waiting >= 200) {
    02848           int dec = Random() & 0x1F;
    02849           if (waiting < 400) dec &= 7;
    02850           waiting -= dec + 1;
    02851           waiting_changed = true;
    02852         }
    02853
    02854         /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
    02855         if (rating <= 127 && waiting != 0) {
    02856           uint32 r = Random();
    02857           if (rating <= (int)GB(r, 0, 7)) {
    02858             /* Need to have int, otherwise it will just overflow etc. */
    02859             waiting = max((int)waiting - (int)GB(r, 8, 2) - 1, 0);
    02860             waiting_changed = true;
    02861           }
    02862         }
    02863
    02864         /* At some point we really must cap the cargo. Previously this
    02865          * was a strict 4095, but now we'll have a less strict, but
    02866          * increasingly agressive truncation of the amount of cargo. */
    02867         static const uint WAITING_CARGO_THRESHOLD  = 1 << 12;
    02868         static const uint WAITING_CARGO_CUT_FACTOR = 1 <<  6;
    02869         static const uint MAX_WAITING_CARGO        = 1 << 15;
    02870
    02871         if (waiting > WAITING_CARGO_THRESHOLD) {
    02872           uint difference = waiting - WAITING_CARGO_THRESHOLD;
    02873           waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
    02874
    02875           waiting = min(waiting, MAX_WAITING_CARGO);
    02876           waiting_changed = true;
    02877         }
    02878
    02879         if (waiting_changed) ge->cargo.Truncate(waiting);
    02880       }
    02881     }
    02882   }
    02883
    02884   StationID index = st->index;
    02885   if (waiting_changed) {
    02886     SetWindowDirty(WC_STATION_VIEW, index); // update whole window
    02887   } else {
    02888     SetWindowWidgetDirty(WC_STATION_VIEW, index, SVW_RATINGLIST); // update only ratings list
    02889   }
    02890 }
    02891
    02892 /* called for every station each tick */
    02893 static void StationHandleSmallTick(BaseStation *st)
    02894 {
    02895   if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
    02896
    02897   byte b = st->delete_ctr + 1;
    02898   if (b >= 185) b = 0;
    02899   st->delete_ctr = b;
    02900
    02901   if (b == 0) UpdateStationRating(Station::From(st));
    02902 }
    02903
    02904 void OnTick_Station()
    02905 {
    02906   if (_game_mode == GM_EDITOR) return;
    02907
    02908   BaseStation *st;
    02909   FOR_ALL_BASE_STATIONS(st) {
    02910     StationHandleSmallTick(st);
    02911
    02912     /* Run 250 tick interval trigger for station animation.
    02913      * Station index is included so that triggers are not all done
    02914      * at the same time. */
    02915     if ((_tick_counter + st->index) % 250 == 0) {
    02916       /* Stop processing this station if it was deleted */
    02917       if (!StationHandleBigTick(st)) continue;
    02918       StationAnimationTrigger(st, st->xy, STAT_ANIM_250_TICKS);
    02919     }
    02920   }
    02921 }
    02922
    02923 void StationMonthlyLoop()
    02924 {
    02925   /* not used */
    02926 }
    02927
    02928
    02929 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
    02930 {
    02931   Station *st;
    02932
    02933   FOR_ALL_STATIONS(st) {
    02934     if (st->owner == owner &&
    02935         DistanceManhattan(tile, st->xy) <= radius) {
    02936       for (CargoID i = 0; i < NUM_CARGO; i++) {
    02937         GoodsEntry *ge = &st->goods[i];
    02938
    02939         if (ge->acceptance_pickup != 0) {
    02940           ge->rating = Clamp(ge->rating + amount, 0, 255);
    02941         }
    02942       }
    02943     }
    02944   }
    02945 }
    02946
    02947 static void UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
    02948 {
    02949   st->goods[type].cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id));
    02950   SetBit(st->goods[type].acceptance_pickup, GoodsEntry::PICKUP);
    02951
    02952   StationAnimationTrigger(st, st->xy, STAT_ANIM_NEW_CARGO, type);
    02953
    02954   SetWindowDirty(WC_STATION_VIEW, st->index);
    02955   st->MarkTilesDirty(true);
    02956 }
    02957
    02958 static bool IsUniqueStationName(const char *name)
    02959 {
    02960   const Station *st;
    02961
    02962   FOR_ALL_STATIONS(st) {
    02963     if (st->name != NULL && strcmp(st->name, name) == 0) return false;
    02964   }
    02965
    02966   return true;
    02967 }
    02968
    02977 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02978 {
    02979   Station *st = Station::GetIfValid(p1);
    02980   if (st == NULL || !CheckOwnership(st->owner)) return CMD_ERROR;
    02981
    02982   bool reset = StrEmpty(text);
    02983
    02984   if (!reset) {
    02985     if (strlen(text) >= MAX_LENGTH_STATION_NAME_BYTES) return CMD_ERROR;
    02986     if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    02987   }
    02988
    02989   if (flags & DC_EXEC) {
    02990     free(st->name);
    02991     st->name = reset ? NULL : strdup(text);
    02992
    02993     st->UpdateVirtCoord();
    02994     InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
    02995   }
    02996
    02997   return CommandCost();
    02998 }
    02999
    03006 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
    03007 {
    03008   /* area to search = producer plus station catchment radius */
    03009   int max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
    03010
    03011   for (int dy = -max_rad; dy < location.h + max_rad; dy++) {
    03012     for (int dx = -max_rad; dx < location.w + max_rad; dx++) {
    03013       TileIndex cur_tile = TileAddWrap(location.tile, dx, dy);
    03014       if (cur_tile == INVALID_TILE || !IsTileType(cur_tile, MP_STATION)) continue;
    03015
    03016       Station *st = Station::GetByTile(cur_tile);
    03017       if (st == NULL) continue;
    03018
    03019       if (_settings_game.station.modified_catchment) {
    03020         int rad = st->GetCatchmentRadius();
    03021         if (dx < -rad || dx >= rad + location.w || dy < -rad || dy >= rad + location.h) continue;
    03022       }
    03023
    03024       /* Insert the station in the set. This will fail if it has
    03025        * already been added.
    03026        */
    03027       stations->Include(st);
    03028     }
    03029   }
    03030 }
    03031
    03036 const StationList *StationFinder::GetStations()
    03037 {
    03038   if (this->tile != INVALID_TILE) {
    03039     FindStationsAroundTiles(*this, &this->stations);
    03040     this->tile = INVALID_TILE;
    03041   }
    03042   return &this->stations;
    03043 }
    03044
    03045 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
    03046 {
    03047   /* Return if nothing to do. Also the rounding below fails for 0. */
    03048   if (amount == 0) return 0;
    03049
    03050   Station *st1 = NULL;   // Station with best rating
    03051   Station *st2 = NULL;   // Second best station
    03052   uint best_rating1 = 0; // rating of st1
    03053   uint best_rating2 = 0; // rating of st2
    03054
    03055   for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
    03056     Station *st = *st_iter;
    03057
    03058     /* Is the station reserved exclusively for somebody else? */
    03059     if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
    03060
    03061     if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
    03062
    03063     if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue; // Selectively servicing stations, and not this one
    03064
    03065     if (IsCargoInClass(type, CC_PASSENGERS)) {
    03066       if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
    03067     } else {
    03068       if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
    03069     }
    03070
    03071     /* This station can be used, add it to st1/st2 */
    03072     if (st1 == NULL || st->goods[type].rating >= best_rating1) {
    03073       st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
    03074     } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
    03075       st2 = st; best_rating2 = st->goods[type].rating;
    03076     }
    03077   }
    03078
    03079   /* no stations around at all? */
    03080   if (st1 == NULL) return 0;
    03081
    03082   if (st2 == NULL) {
    03083     /* only one station around */
    03084     uint moved = amount * best_rating1 / 256 + 1;
    03085     UpdateStationWaiting(st1, type, moved, source_type, source_id);
    03086     return moved;
    03087   }
    03088
    03089   /* several stations around, the best two (highest rating) are in st1 and st2 */
    03090   assert(st1 != NULL);
    03091   assert(st2 != NULL);
    03092   assert(best_rating1 != 0 || best_rating2 != 0);
    03093
    03094   /* the 2nd highest one gets a penalty */
    03095   best_rating2 >>= 1;
    03096
    03097   /* amount given to station 1 */
    03098   uint t = (best_rating1 * (amount + 1)) / (best_rating1 + best_rating2);
    03099
    03100   uint moved = 0;
    03101   if (t != 0) {
    03102     moved = t * best_rating1 / 256 + 1;
    03103     amount -= t;
    03104     UpdateStationWaiting(st1, type, moved, source_type, source_id);
    03105   }
    03106
    03107   if (amount != 0) {
    03108     amount = amount * best_rating2 / 256 + 1;
    03109     moved += amount;
    03110     UpdateStationWaiting(st2, type, amount, source_type, source_id);
    03111   }
    03112
    03113   return moved;
    03114 }
    03115
    03116 void BuildOilRig(TileIndex tile)
    03117 {
    03118   if (!Station::CanAllocateItem()) {
    03119     DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
    03120     return;
    03121   }
    03122
    03123   Station *st = new Station(tile);
    03124   st->town = ClosestTownFromTile(tile, UINT_MAX);
    03125
    03126   st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
    03127
    03128   assert(IsTileType(tile, MP_INDUSTRY));
    03129   DeleteAnimatedTile(tile);
    03130   MakeOilrig(tile, st->index, GetWaterClass(tile));
    03131
    03132   st->owner = OWNER_NONE;
    03133   st->airport_type = AT_OILRIG;
    03134   st->airport_tile = tile;
    03135   st->dock_tile = tile;
    03136   st->facilities = FACIL_AIRPORT | FACIL_DOCK;
    03137   st->build_date = _date;
    03138
    03139   st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
    03140
    03141   for (CargoID j = 0; j < NUM_CARGO; j++) {
    03142     st->goods[j].acceptance_pickup = 0;
    03143     st->goods[j].days_since_pickup = 255;
    03144     st->goods[j].rating = INITIAL_STATION_RATING;
    03145     st->goods[j].last_speed = 0;
    03146     st->goods[j].last_age = 255;
    03147   }
    03148
    03149   st->UpdateVirtCoord();
    03150   UpdateStationAcceptance(st, false);
    03151   st->RecomputeIndustriesNear();
    03152 }
    03153
    03154 void DeleteOilRig(TileIndex tile)
    03155 {
    03156   Station *st = Station::GetByTile(tile);
    03157
    03158   MakeWaterKeepingClass(tile, OWNER_NONE);
    03159   MarkTileDirtyByTile(tile);
    03160
    03161   st->dock_tile = INVALID_TILE;
    03162   st->airport_tile = INVALID_TILE;
    03163   st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
    03164   st->airport_flags = 0;
    03165
    03166   st->rect.AfterRemoveTile(st, tile);
    03167
    03168   st->UpdateVirtCoord();
    03169   st->RecomputeIndustriesNear();
    03170   if (!st->IsInUse()) delete st;
    03171 }
    03172
    03173 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
    03174 {
    03175   if (IsDriveThroughStopTile(tile)) {
    03176     for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
    03177       /* Update all roadtypes, no matter if they are present */
    03178       if (GetRoadOwner(tile, rt) == old_owner) {
    03179         SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
    03180       }
    03181     }
    03182   }
    03183
    03184   if (!IsTileOwner(tile, old_owner)) return;
    03185
    03186   if (new_owner != INVALID_OWNER) {
    03187     /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
    03188     SetTileOwner(tile, new_owner);
    03189     InvalidateWindowClassesData(WC_STATION_LIST, 0);
    03190   } else {
    03191     if (IsDriveThroughStopTile(tile)) {
    03192       /* Remove the drive-through road stop */
    03193       DoCommand(tile, 0, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
    03194       assert(IsTileType(tile, MP_ROAD));
    03195       /* Change owner of tile and all roadtypes */
    03196       ChangeTileOwner(tile, old_owner, new_owner);
    03197     } else {
    03198       DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
    03199       /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
    03200        * Update owner of buoy if it was not removed (was in orders).
    03201        * Do not update when owned by OWNER_WATER (sea and rivers). */
    03202       if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
    03203     }
    03204   }
    03205 }
    03206
    03215 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
    03216 {
    03217   /* Yeah... water can always remove stops, right? */
    03218   if (_current_company == OWNER_WATER) return true;
    03219
    03220   Owner road_owner = _current_company;
    03221   Owner tram_owner = _current_company;
    03222
    03223   RoadTypes rts = GetRoadTypes(tile);
    03224   if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    03225   if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
    03226
    03227   if ((road_owner != OWNER_TOWN && !CheckOwnership(road_owner)) || !CheckOwnership(tram_owner)) return false;
    03228
    03229   return road_owner != OWNER_TOWN || CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags);
    03230 }
    03231
    03232 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
    03233 {
    03234   if (flags & DC_AUTO) {
    03235     switch (GetStationType(tile)) {
    03236       default: break;
    03237       case STATION_RAIL:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
    03238       case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
    03239       case STATION_AIRPORT:  return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
    03240       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);
    03241       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);
    03242       case STATION_BUOY:     return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
    03243       case STATION_DOCK:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
    03244       case STATION_OILRIG:
    03245         SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
    03246         return_cmd_error(STR_ERROR_UNMOVABLE_OBJECT_IN_THE_WAY);
    03247     }
    03248   }
    03249
    03250   switch (GetStationType(tile)) {
    03251     case STATION_RAIL:     return RemoveRailStation(tile, flags);
    03252     case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
    03253     case STATION_AIRPORT:  return RemoveAirport(tile, flags);
    03254     case STATION_TRUCK:
    03255       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags))
    03256         return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
    03257       return RemoveRoadStop(tile, flags);
    03258     case STATION_BUS:
    03259       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags))
    03260         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
    03261       return RemoveRoadStop(tile, flags);
    03262     case STATION_BUOY:     return RemoveBuoy(tile, flags);
    03263     case STATION_DOCK:     return RemoveDock(tile, flags);
    03264     default: break;
    03265   }
    03266
    03267   return CMD_ERROR;
    03268 }
    03269
    03270 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
    03271 {
    03272   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
    03273     /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
    03274      *       TTDP does not call it.
    03275      */
    03276     if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
    03277       switch (GetStationType(tile)) {
    03278         case STATION_WAYPOINT:
    03279         case STATION_RAIL: {
    03280           DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
    03281           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
    03282           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
    03283           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    03284         }
    03285
    03286         case STATION_AIRPORT:
    03287           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    03288
    03289         case STATION_TRUCK:
    03290         case STATION_BUS: {
    03291           DiagDirection direction = GetRoadStopDir(tile);
    03292           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
    03293           if (IsDriveThroughStopTile(tile)) {
    03294             if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
    03295           }
    03296           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    03297         }
    03298
    03299         default: break;
    03300       }
    03301     }
    03302   }
    03303   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    03304 }
    03305
    03306
    03307 extern const TileTypeProcs _tile_type_station_procs = {
    03308   DrawTile_Station,           // draw_tile_proc
    03309   GetSlopeZ_Station,          // get_slope_z_proc
    03310   ClearTile_Station,          // clear_tile_proc
    03311   NULL,                       // add_accepted_cargo_proc
    03312   GetTileDesc_Station,        // get_tile_desc_proc
    03313   GetTileTrackStatus_Station, // get_tile_track_status_proc
    03314   ClickTile_Station,          // click_tile_proc
    03315   AnimateTile_Station,        // animate_tile_proc
    03316   TileLoop_Station,           // tile_loop_clear
    03317   ChangeTileOwner_Station,    // change_tile_owner_clear
    03318   NULL,                       // add_produced_cargo_proc
    03319   VehicleEnter_Station,       // vehicle_enter_tile_proc
    03320   GetFoundation_Station,      // get_foundation_proc
    03321   TerraformTile_Station,      // terraform_tile_proc
    03322 };