# station_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: station_cmd.cpp 26393 2014-03-06 21:19:41Z fonsinchen $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "aircraft.h"
    00014 #include "bridge_map.h"
    00015 #include "cmd_helper.h"
    00016 #include "viewport_func.h"
    00017 #include "command_func.h"
    00018 #include "town.h"
    00019 #include "news_func.h"
    00020 #include "train.h"
    00021 #include "ship.h"
    00022 #include "roadveh.h"
    00023 #include "industry.h"
    00024 #include "newgrf_cargo.h"
    00025 #include "newgrf_debug.h"
    00026 #include "newgrf_station.h"
    00027 #include "newgrf_canal.h" /* For the buoy */
    00028 #include "pathfinder/yapf/yapf_cache.h"
    00029 #include "road_internal.h" /* For drawing catenary/checking road removal */
    00030 #include "autoslope.h"
    00031 #include "water.h"
    00032 #include "strings_func.h"
    00033 #include "clear_func.h"
    00034 #include "date_func.h"
    00035 #include "vehicle_func.h"
    00036 #include "string_func.h"
    00037 #include "animated_tile_func.h"
    00038 #include "elrail_func.h"
    00039 #include "station_base.h"
    00040 #include "roadstop_base.h"
    00041 #include "newgrf_railtype.h"
    00042 #include "waypoint_base.h"
    00043 #include "waypoint_func.h"
    00044 #include "pbs.h"
    00045 #include "debug.h"
    00046 #include "core/random_func.hpp"
    00047 #include "company_base.h"
    00048 #include "table/airporttile_ids.h"
    00049 #include "newgrf_airporttiles.h"
    00050 #include "order_backup.h"
    00051 #include "newgrf_house.h"
    00052 #include "company_gui.h"
    00053 #include "linkgraph/linkgraph_base.h"
    00054 #include "linkgraph/refresh.h"
    00055 #include "widgets/station_widget.h"
    00056
    00057 #include "table/strings.h"
    00058
    00065 bool IsHangar(TileIndex t)
    00066 {
    00067   assert(IsTileType(t, MP_STATION));
    00068
    00069   /* If the tile isn't an airport there's no chance it's a hangar. */
    00070   if (!IsAirport(t)) return false;
    00071
    00072   const Station *st = Station::GetByTile(t);
    00073   const AirportSpec *as = st->airport.GetSpec();
    00074
    00075   for (uint i = 0; i < as->nof_depots; i++) {
    00076     if (st->airport.GetHangarTile(i) == t) return true;
    00077   }
    00078
    00079   return false;
    00080 }
    00081
    00089 template <class T>
    00090 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
    00091 {
    00092   ta.tile -= TileDiffXY(1, 1);
    00093   ta.w    += 2;
    00094   ta.h    += 2;
    00095
    00096   /* check around to see if there's any stations there */
    00097   TILE_AREA_LOOP(tile_cur, ta) {
    00098     if (IsTileType(tile_cur, MP_STATION)) {
    00099       StationID t = GetStationIndex(tile_cur);
    00100       if (!T::IsValidID(t)) continue;
    00101
    00102       if (closest_station == INVALID_STATION) {
    00103         closest_station = t;
    00104       } else if (closest_station != t) {
    00105         return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
    00106       }
    00107     }
    00108   }
    00109   *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
    00110   return CommandCost();
    00111 }
    00112
    00118 typedef bool (*CMSAMatcher)(TileIndex tile);
    00119
    00126 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
    00127 {
    00128   int num = 0;
    00129
    00130   for (int dx = -3; dx <= 3; dx++) {
    00131     for (int dy = -3; dy <= 3; dy++) {
    00132       TileIndex t = TileAddWrap(tile, dx, dy);
    00133       if (t != INVALID_TILE && cmp(t)) num++;
    00134     }
    00135   }
    00136
    00137   return num;
    00138 }
    00139
    00145 static bool CMSAMine(TileIndex tile)
    00146 {
    00147   /* No industry */
    00148   if (!IsTileType(tile, MP_INDUSTRY)) return false;
    00149
    00150   const Industry *ind = Industry::GetByTile(tile);
    00151
    00152   /* No extractive industry */
    00153   if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
    00154
    00155   for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
    00156     /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
    00157      * Also the production of passengers and mail is ignored. */
    00158     if (ind->produced_cargo[i] != CT_INVALID &&
    00159         (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
    00160       return true;
    00161     }
    00162   }
    00163
    00164   return false;
    00165 }
    00166
    00172 static bool CMSAWater(TileIndex tile)
    00173 {
    00174   return IsTileType(tile, MP_WATER) && IsWater(tile);
    00175 }
    00176
    00182 static bool CMSATree(TileIndex tile)
    00183 {
    00184   return IsTileType(tile, MP_TREES);
    00185 }
    00186
    00187 #define M(x) ((x) - STR_SV_STNAME)
    00188
    00189 enum StationNaming {
    00190   STATIONNAMING_RAIL,
    00191   STATIONNAMING_ROAD,
    00192   STATIONNAMING_AIRPORT,
    00193   STATIONNAMING_OILRIG,
    00194   STATIONNAMING_DOCK,
    00195   STATIONNAMING_HELIPORT,
    00196 };
    00197
    00199 struct StationNameInformation {
    00200   uint32 free_names;
    00201   bool *indtypes;
    00202 };
    00203
    00212 static bool FindNearIndustryName(TileIndex tile, void *user_data)
    00213 {
    00214   /* All already found industry types */
    00215   StationNameInformation *sni = (StationNameInformation*)user_data;
    00216   if (!IsTileType(tile, MP_INDUSTRY)) return false;
    00217
    00218   /* If the station name is undefined it means that it doesn't name a station */
    00219   IndustryType indtype = GetIndustryType(tile);
    00220   if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
    00221
    00222   /* In all cases if an industry that provides a name is found two of
    00223    * the standard names will be disabled. */
    00224   sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
    00225   return !sni->indtypes[indtype];
    00226 }
    00227
    00228 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
    00229 {
    00230   static const uint32 _gen_station_name_bits[] = {
    00231     0,                                       // STATIONNAMING_RAIL
    00232     0,                                       // STATIONNAMING_ROAD
    00233     1U << M(STR_SV_STNAME_AIRPORT),          // STATIONNAMING_AIRPORT
    00234     1U << M(STR_SV_STNAME_OILFIELD),         // STATIONNAMING_OILRIG
    00235     1U << M(STR_SV_STNAME_DOCKS),            // STATIONNAMING_DOCK
    00236     1U << M(STR_SV_STNAME_HELIPORT),         // STATIONNAMING_HELIPORT
    00237   };
    00238
    00239   const Town *t = st->town;
    00240   uint32 free_names = UINT32_MAX;
    00241
    00242   bool indtypes[NUM_INDUSTRYTYPES];
    00243   memset(indtypes, 0, sizeof(indtypes));
    00244
    00245   const Station *s;
    00246   FOR_ALL_STATIONS(s) {
    00247     if (s != st && s->town == t) {
    00248       if (s->indtype != IT_INVALID) {
    00249         indtypes[s->indtype] = true;
    00250         StringID name = GetIndustrySpec(s->indtype)->station_name;
    00251         if (name != STR_UNDEFINED) {
    00252           /* Filter for other industrytypes with the same name */
    00253           for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
    00254             const IndustrySpec *indsp = GetIndustrySpec(it);
    00255             if (indsp->enabled && indsp->station_name == name) indtypes[it] = true;
    00256           }
    00257         }
    00258         continue;
    00259       }
    00260       uint str = M(s->string_id);
    00261       if (str <= 0x20) {
    00262         if (str == M(STR_SV_STNAME_FOREST)) {
    00263           str = M(STR_SV_STNAME_WOODS);
    00264         }
    00265         ClrBit(free_names, str);
    00266       }
    00267     }
    00268   }
    00269
    00270   TileIndex indtile = tile;
    00271   StationNameInformation sni = { free_names, indtypes };
    00272   if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
    00273     /* An industry has been found nearby */
    00274     IndustryType indtype = GetIndustryType(indtile);
    00275     const IndustrySpec *indsp = GetIndustrySpec(indtype);
    00276     /* STR_NULL means it only disables oil rig/mines */
    00277     if (indsp->station_name != STR_NULL) {
    00278       st->indtype = indtype;
    00279       return STR_SV_STNAME_FALLBACK;
    00280     }
    00281   }
    00282
    00283   /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
    00284   free_names = sni.free_names;
    00285
    00286   /* check default names */
    00287   uint32 tmp = free_names & _gen_station_name_bits[name_class];
    00288   if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
    00289
    00290   /* check mine? */
    00291   if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
    00292     if (CountMapSquareAround(tile, CMSAMine) >= 2) {
    00293       return STR_SV_STNAME_MINES;
    00294     }
    00295   }
    00296
    00297   /* check close enough to town to get central as name? */
    00298   if (DistanceMax(tile, t->xy) < 8) {
    00299     if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
    00300
    00301     if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
    00302   }
    00303
    00304   /* Check lakeside */
    00305   if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
    00306       DistanceFromEdge(tile) < 20 &&
    00307       CountMapSquareAround(tile, CMSAWater) >= 5) {
    00308     return STR_SV_STNAME_LAKESIDE;
    00309   }
    00310
    00311   /* Check woods */
    00312   if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
    00313         CountMapSquareAround(tile, CMSATree) >= 8 ||
    00314         CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
    00315       ) {
    00316     return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
    00317   }
    00318
    00319   /* check elevation compared to town */
    00320   int z = GetTileZ(tile);
    00321   int z2 = GetTileZ(t->xy);
    00322   if (z < z2) {
    00323     if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
    00324   } else if (z > z2) {
    00325     if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
    00326   }
    00327
    00328   /* check direction compared to town */
    00329   static const int8 _direction_and_table[] = {
    00330     ~( (1 << M(STR_SV_STNAME_WEST))  | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
    00331     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
    00332     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
    00333     ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
    00334   };
    00335
    00336   free_names &= _direction_and_table[
    00337     (TileX(tile) < TileX(t->xy)) +
    00338     (TileY(tile) < TileY(t->xy)) * 2];
    00339
    00340   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));
    00341   return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
    00342 }
    00343 #undef M
    00344
    00350 static Station *GetClosestDeletedStation(TileIndex tile)
    00351 {
    00352   uint threshold = 8;
    00353   Station *best_station = NULL;
    00354   Station *st;
    00355
    00356   FOR_ALL_STATIONS(st) {
    00357     if (!st->IsInUse() && st->owner == _current_company) {
    00358       uint cur_dist = DistanceManhattan(tile, st->xy);
    00359
    00360       if (cur_dist < threshold) {
    00361         threshold = cur_dist;
    00362         best_station = st;
    00363       }
    00364     }
    00365   }
    00366
    00367   return best_station;
    00368 }
    00369
    00370
    00371 void Station::GetTileArea(TileArea *ta, StationType type) const
    00372 {
    00373   switch (type) {
    00374     case STATION_RAIL:
    00375       *ta = this->train_station;
    00376       return;
    00377
    00378     case STATION_AIRPORT:
    00379       *ta = this->airport;
    00380       return;
    00381
    00382     case STATION_TRUCK:
    00383       *ta = this->truck_station;
    00384       return;
    00385
    00386     case STATION_BUS:
    00387       *ta = this->bus_station;
    00388       return;
    00389
    00390     case STATION_DOCK:
    00391     case STATION_OILRIG:
    00392       ta->tile = this->dock_tile;
    00393       break;
    00394
    00395     default: NOT_REACHED();
    00396   }
    00397
    00398   ta->w = 1;
    00399   ta->h = 1;
    00400 }
    00401
    00405 void Station::UpdateVirtCoord()
    00406 {
    00407   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
    00408
    00409   pt.y -= 32 * ZOOM_LVL_BASE;
    00410   if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
    00411
    00412   SetDParam(0, this->index);
    00413   SetDParam(1, this->facilities);
    00414   this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
    00415
    00416   SetWindowDirty(WC_STATION_VIEW, this->index);
    00417 }
    00418
    00420 void UpdateAllStationVirtCoords()
    00421 {
    00422   BaseStation *st;
    00423
    00424   FOR_ALL_BASE_STATIONS(st) {
    00425     st->UpdateVirtCoord();
    00426   }
    00427 }
    00428
    00434 static uint GetAcceptanceMask(const Station *st)
    00435 {
    00436   uint mask = 0;
    00437
    00438   for (CargoID i = 0; i < NUM_CARGO; i++) {
    00439     if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) mask |= 1 << i;
    00440   }
    00441   return mask;
    00442 }
    00443
    00448 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
    00449 {
    00450   for (uint i = 0; i < num_items; i++) {
    00451     SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
    00452   }
    00453
    00454   SetDParam(0, st->index);
    00455   AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
    00456 }
    00457
    00465 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
    00466 {
    00467   CargoArray produced;
    00468
    00469   int x = TileX(tile);
    00470   int y = TileY(tile);
    00471
    00472   /* expand the region by rad tiles on each side
    00473    * while making sure that we remain inside the board. */
    00474   int x2 = min(x + w + rad, MapSizeX());
    00475   int x1 = max(x - rad, 0);
    00476
    00477   int y2 = min(y + h + rad, MapSizeY());
    00478   int y1 = max(y - rad, 0);
    00479
    00480   assert(x1 < x2);
    00481   assert(y1 < y2);
    00482   assert(w > 0);
    00483   assert(h > 0);
    00484
    00485   TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
    00486
    00487   /* Loop over all tiles to get the produced cargo of
    00488    * everything except industries */
    00489   TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
    00490
    00491   /* Loop over the industries. They produce cargo for
    00492    * anything that is within 'rad' from their bounding
    00493    * box. As such if you have e.g. a oil well the tile
    00494    * area loop might not hit an industry tile while
    00495    * the industry would produce cargo for the station.
    00496    */
    00497   const Industry *i;
    00498   FOR_ALL_INDUSTRIES(i) {
    00499     if (!ta.Intersects(i->location)) continue;
    00500
    00501     for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
    00502       CargoID cargo = i->produced_cargo[j];
    00503       if (cargo != CT_INVALID) produced[cargo]++;
    00504     }
    00505   }
    00506
    00507   return produced;
    00508 }
    00509
    00518 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
    00519 {
    00520   CargoArray acceptance;
    00521   if (always_accepted != NULL) *always_accepted = 0;
    00522
    00523   int x = TileX(tile);
    00524   int y = TileY(tile);
    00525
    00526   /* expand the region by rad tiles on each side
    00527    * while making sure that we remain inside the board. */
    00528   int x2 = min(x + w + rad, MapSizeX());
    00529   int y2 = min(y + h + rad, MapSizeY());
    00530   int x1 = max(x - rad, 0);
    00531   int y1 = max(y - rad, 0);
    00532
    00533   assert(x1 < x2);
    00534   assert(y1 < y2);
    00535   assert(w > 0);
    00536   assert(h > 0);
    00537
    00538   for (int yc = y1; yc != y2; yc++) {
    00539     for (int xc = x1; xc != x2; xc++) {
    00540       TileIndex tile = TileXY(xc, yc);
    00541       AddAcceptedCargo(tile, acceptance, always_accepted);
    00542     }
    00543   }
    00544
    00545   return acceptance;
    00546 }
    00547
    00553 void UpdateStationAcceptance(Station *st, bool show_msg)
    00554 {
    00555   /* old accepted goods types */
    00556   uint old_acc = GetAcceptanceMask(st);
    00557
    00558   /* And retrieve the acceptance. */
    00559   CargoArray acceptance;
    00560   if (!st->rect.IsEmpty()) {
    00561     acceptance = GetAcceptanceAroundTiles(
    00562       TileXY(st->rect.left, st->rect.top),
    00563       st->rect.right  - st->rect.left + 1,
    00564       st->rect.bottom - st->rect.top  + 1,
    00565       st->GetCatchmentRadius(),
    00566       &st->always_accepted
    00567     );
    00568   }
    00569
    00570   /* Adjust in case our station only accepts fewer kinds of goods */
    00571   for (CargoID i = 0; i < NUM_CARGO; i++) {
    00572     uint amt = acceptance[i];
    00573
    00574     /* Make sure the station can accept the goods type. */
    00575     bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
    00576     if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
    00577         (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
    00578       amt = 0;
    00579     }
    00580
    00581     GoodsEntry &ge = st->goods[i];
    00582     SB(ge.acceptance_pickup, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
    00583     if (LinkGraph::IsValidID(ge.link_graph)) {
    00584       (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
    00585     }
    00586   }
    00587
    00588   /* Only show a message in case the acceptance was actually changed. */
    00589   uint new_acc = GetAcceptanceMask(st);
    00590   if (old_acc == new_acc) return;
    00591
    00592   /* show a message to report that the acceptance was changed? */
    00593   if (show_msg && st->owner == _local_company && st->IsInUse()) {
    00594     /* List of accept and reject strings for different number of
    00595      * cargo types */
    00596     static const StringID accept_msg[] = {
    00597       STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
    00598       STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
    00599     };
    00600     static const StringID reject_msg[] = {
    00601       STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
    00602       STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
    00603     };
    00604
    00605     /* Array of accepted and rejected cargo types */
    00606     CargoID accepts[2] = { CT_INVALID, CT_INVALID };
    00607     CargoID rejects[2] = { CT_INVALID, CT_INVALID };
    00608     uint num_acc = 0;
    00609     uint num_rej = 0;
    00610
    00611     /* Test each cargo type to see if its acceptance has changed */
    00612     for (CargoID i = 0; i < NUM_CARGO; i++) {
    00613       if (HasBit(new_acc, i)) {
    00614         if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
    00615           /* New cargo is accepted */
    00616           accepts[num_acc++] = i;
    00617         }
    00618       } else {
    00619         if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
    00620           /* Old cargo is no longer accepted */
    00621           rejects[num_rej++] = i;
    00622         }
    00623       }
    00624     }
    00625
    00626     /* Show news message if there are any changes */
    00627     if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
    00628     if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
    00629   }
    00630
    00631   /* redraw the station view since acceptance changed */
    00632   SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
    00633 }
    00634
    00635 static void UpdateStationSignCoord(BaseStation *st)
    00636 {
    00637   const StationRect *r = &st->rect;
    00638
    00639   if (r->IsEmpty()) return; // no tiles belong to this station
    00640
    00641   /* clamp sign coord to be inside the station rect */
    00642   st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
    00643   st->UpdateVirtCoord();
    00644
    00645   if (!Station::IsExpected(st)) return;
    00646   Station *full_station = Station::From(st);
    00647   for (CargoID c = 0; c < NUM_CARGO; ++c) {
    00648     LinkGraphID lg = full_station->goods[c].link_graph;
    00649     if (!LinkGraph::IsValidID(lg)) continue;
    00650     LinkGraph::Get(lg)->UpdateDistances(full_station->goods[c].node, st->xy);
    00651   }
    00652 }
    00653
    00663 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
    00664 {
    00665   /* Find a deleted station close to us */
    00666   if (*st == NULL && reuse) *st = GetClosestDeletedStation(area.tile);
    00667
    00668   if (*st != NULL) {
    00669     if ((*st)->owner != _current_company) {
    00670       return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
    00671     }
    00672
    00673     CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
    00674     if (ret.Failed()) return ret;
    00675   } else {
    00676     /* allocate and initialize new station */
    00677     if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    00678
    00679     if (flags & DC_EXEC) {
    00680       *st = new Station(area.tile);
    00681
    00682       (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
    00683       (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
    00684
    00685       if (Company::IsValidID(_current_company)) {
    00686         SetBit((*st)->town->have_ratings, _current_company);
    00687       }
    00688     }
    00689   }
    00690   return CommandCost();
    00691 }
    00692
    00699 static void DeleteStationIfEmpty(BaseStation *st)
    00700 {
    00701   if (!st->IsInUse()) {
    00702     st->delete_ctr = 0;
    00703     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
    00704   }
    00705   /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
    00706   UpdateStationSignCoord(st);
    00707 }
    00708
    00709 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
    00710
    00720 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
    00721 {
    00722   if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
    00723     return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00724   }
    00725
    00726   CommandCost ret = EnsureNoVehicleOnGround(tile);
    00727   if (ret.Failed()) return ret;
    00728
    00729   int z;
    00730   Slope tileh = GetTileSlope(tile, &z);
    00731
    00732   /* Prohibit building if
    00733    *   1) The tile is "steep" (i.e. stretches two height levels).
    00734    *   2) The tile is non-flat and the build_on_slopes switch is disabled.
    00735    */
    00736   if ((!allow_steep && IsSteepSlope(tileh)) ||
    00737       ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
    00738     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
    00739   }
    00740
    00741   CommandCost cost(EXPENSES_CONSTRUCTION);
    00742   int flat_z = z + GetSlopeMaxZ(tileh);
    00743   if (tileh != SLOPE_FLAT) {
    00744     /* Forbid building if the tile faces a slope in a invalid direction. */
    00745     for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
    00746       if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
    00747         return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
    00748       }
    00749     }
    00750     cost.AddCost(_price[PR_BUILD_FOUNDATION]);
    00751   }
    00752
    00753   /* The level of this tile must be equal to allowed_z. */
    00754   if (allowed_z < 0) {
    00755     /* First tile. */
    00756     allowed_z = flat_z;
    00757   } else if (allowed_z != flat_z) {
    00758     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
    00759   }
    00760
    00761   return cost;
    00762 }
    00763
    00770 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
    00771 {
    00772   CommandCost cost(EXPENSES_CONSTRUCTION);
    00773   int allowed_z = -1;
    00774
    00775   TILE_AREA_LOOP(tile_cur, tile_area) {
    00776     CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
    00777     if (ret.Failed()) return ret;
    00778     cost.AddCost(ret);
    00779
    00780     ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00781     if (ret.Failed()) return ret;
    00782     cost.AddCost(ret);
    00783   }
    00784
    00785   return cost;
    00786 }
    00787
    00802 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, SmallVector<Train *, 4> &affected_vehicles, StationClassID spec_class, byte spec_index, byte plat_len, byte numtracks)
    00803 {
    00804   CommandCost cost(EXPENSES_CONSTRUCTION);
    00805   int allowed_z = -1;
    00806   uint invalid_dirs = 5 << axis;
    00807
    00808   const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
    00809   bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
    00810
    00811   TILE_AREA_LOOP(tile_cur, tile_area) {
    00812     CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
    00813     if (ret.Failed()) return ret;
    00814     cost.AddCost(ret);
    00815
    00816     if (slope_cb) {
    00817       /* Do slope check if requested. */
    00818       ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
    00819       if (ret.Failed()) return ret;
    00820     }
    00821
    00822     /* if station is set, then we have special handling to allow building on top of already existing stations.
    00823      * so station points to INVALID_STATION if we can build on any station.
    00824      * Or it points to a station if we're only allowed to build on exactly that station. */
    00825     if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
    00826       if (!IsRailStation(tile_cur)) {
    00827         return ClearTile_Station(tile_cur, DC_AUTO); // get error message
    00828       } else {
    00829         StationID st = GetStationIndex(tile_cur);
    00830         if (*station == INVALID_STATION) {
    00831           *station = st;
    00832         } else if (*station != st) {
    00833           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
    00834         }
    00835       }
    00836     } else {
    00837       /* Rail type is only valid when building a railway station; if station to
    00838        * build isn't a rail station it's INVALID_RAILTYPE. */
    00839       if (rt != INVALID_RAILTYPE &&
    00840           IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
    00841           HasPowerOnRail(GetRailType(tile_cur), rt)) {
    00842         /* Allow overbuilding if the tile:
    00843          *  - has rail, but no signals
    00844          *  - it has exactly one track
    00845          *  - the track is in line with the station
    00846          *  - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
    00847          */
    00848         TrackBits tracks = GetTrackBits(tile_cur);
    00849         Track track = RemoveFirstTrack(&tracks);
    00850         Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
    00851
    00852         if (tracks == TRACK_BIT_NONE && track == expected_track) {
    00853           /* Check for trains having a reservation for this tile. */
    00854           if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
    00855             Train *v = GetTrainForReservation(tile_cur, track);
    00856             if (v != NULL) {
    00857               *affected_vehicles.Append() = v;
    00858             }
    00859           }
    00860           CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
    00861           if (ret.Failed()) return ret;
    00862           cost.AddCost(ret);
    00863           /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
    00864           continue;
    00865         }
    00866       }
    00867       ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00868       if (ret.Failed()) return ret;
    00869       cost.AddCost(ret);
    00870     }
    00871   }
    00872
    00873   return cost;
    00874 }
    00875
    00888 static CommandCost CheckFlatLandRoadStop(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadTypes rts)
    00889 {
    00890   CommandCost cost(EXPENSES_CONSTRUCTION);
    00891   int allowed_z = -1;
    00892
    00893   TILE_AREA_LOOP(cur_tile, tile_area) {
    00894     CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
    00895     if (ret.Failed()) return ret;
    00896     cost.AddCost(ret);
    00897
    00898     /* If station is set, then we have special handling to allow building on top of already existing stations.
    00899      * Station points to INVALID_STATION if we can build on any station.
    00900      * Or it points to a station if we're only allowed to build on exactly that station. */
    00901     if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
    00902       if (!IsRoadStop(cur_tile)) {
    00903         return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
    00904       } else {
    00905         if (is_truck_stop != IsTruckStop(cur_tile) ||
    00906             is_drive_through != IsDriveThroughStopTile(cur_tile)) {
    00907           return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
    00908         }
    00909         /* Drive-through station in the wrong direction. */
    00910         if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
    00911           return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
    00912         }
    00913         StationID st = GetStationIndex(cur_tile);
    00914         if (*station == INVALID_STATION) {
    00915           *station = st;
    00916         } else if (*station != st) {
    00917           return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
    00918         }
    00919       }
    00920     } else {
    00921       bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
    00922       /* Road bits in the wrong direction. */
    00923       RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
    00924       if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
    00925         /* Someone was pedantic and *NEEDED* three fracking different error messages. */
    00926         switch (CountBits(rb)) {
    00927           case 1:
    00928             return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
    00929
    00930           case 2:
    00931             if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
    00932             return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
    00933
    00934           default: // 3 or 4
    00935             return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
    00936         }
    00937       }
    00938
    00939       RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
    00940       uint num_roadbits = 0;
    00941       if (build_over_road) {
    00942         /* There is a road, check if we can build road+tram stop over it. */
    00943         if (HasBit(cur_rts, ROADTYPE_ROAD)) {
    00944           Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
    00945           if (road_owner == OWNER_TOWN) {
    00946             if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
    00947           } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
    00948             CommandCost ret = CheckOwnership(road_owner);
    00949             if (ret.Failed()) return ret;
    00950           }
    00951           num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
    00952         }
    00953
    00954         /* There is a tram, check if we can build road+tram stop over it. */
    00955         if (HasBit(cur_rts, ROADTYPE_TRAM)) {
    00956           Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
    00957           if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
    00958             CommandCost ret = CheckOwnership(tram_owner);
    00959             if (ret.Failed()) return ret;
    00960           }
    00961           num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
    00962         }
    00963
    00964         /* Take into account existing roadbits. */
    00965         rts |= cur_rts;
    00966       } else {
    00967         ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00968         if (ret.Failed()) return ret;
    00969         cost.AddCost(ret);
    00970       }
    00971
    00972       uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
    00973       cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
    00974     }
    00975   }
    00976
    00977   return cost;
    00978 }
    00979
    00987 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
    00988 {
    00989   TileArea cur_ta = st->train_station;
    00990
    00991   /* determine new size of train station region.. */
    00992   int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
    00993   int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
    00994   new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
    00995   new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
    00996   new_ta.tile = TileXY(x, y);
    00997
    00998   /* make sure the final size is not too big. */
    00999   if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
    01000     return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
    01001   }
    01002
    01003   return CommandCost();
    01004 }
    01005
    01006 static inline byte *CreateSingle(byte *layout, int n)
    01007 {
    01008   int i = n;
    01009   do *layout++ = 0; while (--i);
    01010   layout[((n - 1) >> 1) - n] = 2;
    01011   return layout;
    01012 }
    01013
    01014 static inline byte *CreateMulti(byte *layout, int n, byte b)
    01015 {
    01016   int i = n;
    01017   do *layout++ = b; while (--i);
    01018   if (n > 4) {
    01019     layout[0 - n] = 0;
    01020     layout[n - 1 - n] = 0;
    01021   }
    01022   return layout;
    01023 }
    01024
    01032 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
    01033 {
    01034   if (statspec != NULL && statspec->lengths >= plat_len &&
    01035       statspec->platforms[plat_len - 1] >= numtracks &&
    01036       statspec->layouts[plat_len - 1][numtracks - 1]) {
    01037     /* Custom layout defined, follow it. */
    01038     memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
    01039       plat_len * numtracks);
    01040     return;
    01041   }
    01042
    01043   if (plat_len == 1) {
    01044     CreateSingle(layout, numtracks);
    01045   } else {
    01046     if (numtracks & 1) layout = CreateSingle(layout, plat_len);
    01047     numtracks >>= 1;
    01048
    01049     while (--numtracks >= 0) {
    01050       layout = CreateMulti(layout, plat_len, 4);
    01051       layout = CreateMulti(layout, plat_len, 6);
    01052     }
    01053   }
    01054 }
    01055
    01067 template <class T, StringID error_message>
    01068 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
    01069 {
    01070   assert(*st == NULL);
    01071   bool check_surrounding = true;
    01072
    01073   if (_settings_game.station.adjacent_stations) {
    01074     if (existing_station != INVALID_STATION) {
    01075       if (adjacent && existing_station != station_to_join) {
    01076         /* You can't build an adjacent station over the top of one that
    01077          * already exists. */
    01078         return_cmd_error(error_message);
    01079       } else {
    01080         /* Extend the current station, and don't check whether it will
    01081          * be near any other stations. */
    01082         *st = T::GetIfValid(existing_station);
    01083         check_surrounding = (*st == NULL);
    01084       }
    01085     } else {
    01086       /* There's no station here. Don't check the tiles surrounding this
    01087        * one if the company wanted to build an adjacent station. */
    01088       if (adjacent) check_surrounding = false;
    01089     }
    01090   }
    01091
    01092   if (check_surrounding) {
    01093     /* Make sure there are no similar stations around us. */
    01094     CommandCost ret = GetStationAround(ta, existing_station, st);
    01095     if (ret.Failed()) return ret;
    01096   }
    01097
    01098   /* Distant join */
    01099   if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
    01100
    01101   return CommandCost();
    01102 }
    01103
    01113 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
    01114 {
    01115   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
    01116 }
    01117
    01127 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
    01128 {
    01129   return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
    01130 }
    01131
    01149 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01150 {
    01151   /* Unpack parameters */
    01152   RailType rt    = Extract<RailType, 0, 4>(p1);
    01153   Axis axis      = Extract<Axis, 4, 1>(p1);
    01154   byte numtracks = GB(p1,  8, 8);
    01155   byte plat_len  = GB(p1, 16, 8);
    01156   bool adjacent  = HasBit(p1, 24);
    01157
    01158   StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
    01159   byte spec_index           = GB(p2, 8, 8);
    01160   StationID station_to_join = GB(p2, 16, 16);
    01161
    01162   /* Does the authority allow this? */
    01163   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
    01164   if (ret.Failed()) return ret;
    01165
    01166   if (!ValParamRailtype(rt)) return CMD_ERROR;
    01167
    01168   /* Check if the given station class is valid */
    01169   if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
    01170   if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
    01171   if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
    01172
    01173   int w_org, h_org;
    01174   if (axis == AXIS_X) {
    01175     w_org = plat_len;
    01176     h_org = numtracks;
    01177   } else {
    01178     h_org = plat_len;
    01179     w_org = numtracks;
    01180   }
    01181
    01182   bool reuse = (station_to_join != NEW_STATION);
    01183   if (!reuse) station_to_join = INVALID_STATION;
    01184   bool distant_join = (station_to_join != INVALID_STATION);
    01185
    01186   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
    01187
    01188   if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
    01189
    01190   /* these values are those that will be stored in train_tile and station_platforms */
    01191   TileArea new_location(tile_org, w_org, h_org);
    01192
    01193   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
    01194   StationID est = INVALID_STATION;
    01195   SmallVector<Train *, 4> affected_vehicles;
    01196   /* Clear the land below the station. */
    01197   CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
    01198   if (cost.Failed()) return cost;
    01199   /* Add construction expenses. */
    01200   cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
    01201   cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
    01202
    01203   Station *st = NULL;
    01204   ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
    01205   if (ret.Failed()) return ret;
    01206
    01207   ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
    01208   if (ret.Failed()) return ret;
    01209
    01210   if (st != NULL && st->train_station.tile != INVALID_TILE) {
    01211     CommandCost ret = CanExpandRailStation(st, new_location, axis);
    01212     if (ret.Failed()) return ret;
    01213   }
    01214
    01215   /* Check if we can allocate a custom stationspec to this station */
    01216   const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
    01217   int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
    01218   if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
    01219
    01220   if (statspec != NULL) {
    01221     /* Perform NewStation checks */
    01222
    01223     /* Check if the station size is permitted */
    01224     if (HasBit(statspec->disallowed_platforms, min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, min(plat_len - 1, 7))) {
    01225       return CMD_ERROR;
    01226     }
    01227
    01228     /* Check if the station is buildable */
    01229     if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
    01230       uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
    01231       if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
    01232     }
    01233   }
    01234
    01235   if (flags & DC_EXEC) {
    01236     TileIndexDiff tile_delta;
    01237     byte *layout_ptr;
    01238     byte numtracks_orig;
    01239     Track track;
    01240
    01241     st->train_station = new_location;
    01242     st->AddFacility(FACIL_TRAIN, new_location.tile);
    01243
    01244     st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
    01245
    01246     if (statspec != NULL) {
    01247       /* Include this station spec's animation trigger bitmask
    01248        * in the station's cached copy. */
    01249       st->cached_anim_triggers |= statspec->animation.triggers;
    01250     }
    01251
    01252     tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
    01253     track = AxisToTrack(axis);
    01254
    01255     layout_ptr = AllocaM(byte, numtracks * plat_len);
    01256     GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
    01257
    01258     numtracks_orig = numtracks;
    01259
    01260     Company *c = Company::Get(st->owner);
    01261     TileIndex tile_track = tile_org;
    01262     do {
    01263       TileIndex tile = tile_track;
    01264       int w = plat_len;
    01265       do {
    01266         byte layout = *layout_ptr++;
    01267         if (IsRailStationTile(tile) && HasStationReservation(tile)) {
    01268           /* Check for trains having a reservation for this tile. */
    01269           Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
    01270           if (v != NULL) {
    01271             FreeTrainTrackReservation(v);
    01272             *affected_vehicles.Append() = v;
    01273             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
    01274             for (; v->Next() != NULL; v = v->Next()) { }
    01275             if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
    01276           }
    01277         }
    01278
    01279         /* Railtype can change when overbuilding. */
    01280         if (IsRailStationTile(tile)) {
    01281           if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
    01282           c->infrastructure.station--;
    01283         }
    01284
    01285         /* Remove animation if overbuilding */
    01286         DeleteAnimatedTile(tile);
    01287         byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
    01288         MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
    01289         /* Free the spec if we overbuild something */
    01290         DeallocateSpecFromStation(st, old_specindex);
    01291
    01292         SetCustomStationSpecIndex(tile, specindex);
    01293         SetStationTileRandomBits(tile, GB(Random(), 0, 4));
    01294         SetAnimationFrame(tile, 0);
    01295
    01296         if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
    01297         c->infrastructure.station++;
    01298
    01299         if (statspec != NULL) {
    01300           /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
    01301           uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
    01302
    01303           /* As the station is not yet completely finished, the station does not yet exist. */
    01304           uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
    01305           if (callback != CALLBACK_FAILED) {
    01306             if (callback < 8) {
    01307               SetStationGfx(tile, (callback & ~1) + axis);
    01308             } else {
    01309               ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
    01310             }
    01311           }
    01312
    01313           /* Trigger station animation -- after building? */
    01314           TriggerStationAnimation(st, tile, SAT_BUILT);
    01315         }
    01316
    01317         tile += tile_delta;
    01318       } while (--w);
    01319       AddTrackToSignalBuffer(tile_track, track, _current_company);
    01320       YapfNotifyTrackLayoutChange(tile_track, track);
    01321       tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
    01322     } while (--numtracks);
    01323
    01324     for (uint i = 0; i < affected_vehicles.Length(); ++i) {
    01325       /* Restore reservations of trains. */
    01326       Train *v = affected_vehicles[i];
    01327       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
    01328       TryPathReserve(v, true, true);
    01329       for (; v->Next() != NULL; v = v->Next()) { }
    01330       if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
    01331     }
    01332
    01333     /* Check whether we need to expand the reservation of trains already on the station. */
    01334     TileArea update_reservation_area;
    01335     if (axis == AXIS_X) {
    01336       update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
    01337     } else {
    01338       update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
    01339     }
    01340
    01341     TILE_AREA_LOOP(tile, update_reservation_area) {
    01342       /* Don't even try to make eye candy parts reserved. */
    01343       if (IsStationTileBlocked(tile)) continue;
    01344
    01345       DiagDirection dir = AxisToDiagDir(axis);
    01346       TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
    01347       TileIndex platform_begin = tile;
    01348       TileIndex platform_end = tile;
    01349
    01350       /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
    01351       for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
    01352         platform_begin = next_tile;
    01353       }
    01354       for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
    01355         platform_end = next_tile;
    01356       }
    01357
    01358       /* If there is at least on reservation on the platform, we reserve the whole platform. */
    01359       bool reservation = false;
    01360       for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
    01361         reservation = HasStationReservation(t);
    01362       }
    01363
    01364       if (reservation) {
    01365         SetRailStationPlatformReservation(platform_begin, dir, true);
    01366       }
    01367     }
    01368
    01369     st->MarkTilesDirty(false);
    01370     st->UpdateVirtCoord();
    01371     UpdateStationAcceptance(st, false);
    01372     st->RecomputeIndustriesNear();
    01373     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
    01374     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
    01375     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
    01376     DirtyCompanyInfrastructureWindows(st->owner);
    01377   }
    01378
    01379   return cost;
    01380 }
    01381
    01382 static void MakeRailStationAreaSmaller(BaseStation *st)
    01383 {
    01384   TileArea ta = st->train_station;
    01385
    01386 restart:
    01387
    01388   /* too small? */
    01389   if (ta.w != 0 && ta.h != 0) {
    01390     /* check the left side, x = constant, y changes */
    01391     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
    01392       /* the left side is unused? */
    01393       if (++i == ta.h) {
    01394         ta.tile += TileDiffXY(1, 0);
    01395         ta.w--;
    01396         goto restart;
    01397       }
    01398     }
    01399
    01400     /* check the right side, x = constant, y changes */
    01401     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
    01402       /* the right side is unused? */
    01403       if (++i == ta.h) {
    01404         ta.w--;
    01405         goto restart;
    01406       }
    01407     }
    01408
    01409     /* check the upper side, y = constant, x changes */
    01410     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
    01411       /* the left side is unused? */
    01412       if (++i == ta.w) {
    01413         ta.tile += TileDiffXY(0, 1);
    01414         ta.h--;
    01415         goto restart;
    01416       }
    01417     }
    01418
    01419     /* check the lower side, y = constant, x changes */
    01420     for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
    01421       /* the left side is unused? */
    01422       if (++i == ta.w) {
    01423         ta.h--;
    01424         goto restart;
    01425       }
    01426     }
    01427   } else {
    01428     ta.Clear();
    01429   }
    01430
    01431   st->train_station = ta;
    01432 }
    01433
    01444 template <class T>
    01445 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
    01446 {
    01447   /* Count of the number of tiles removed */
    01448   int quantity = 0;
    01449   CommandCost total_cost(EXPENSES_CONSTRUCTION);
    01450   /* Accumulator for the errors seen during clearing. If no errors happen,
    01451    * and the quantity is 0 there is no station. Otherwise it will be one
    01452    * of the other error that got accumulated. */
    01453   CommandCost error;
    01454
    01455   /* Do the action for every tile into the area */
    01456   TILE_AREA_LOOP(tile, ta) {
    01457     /* Make sure the specified tile is a rail station */
    01458     if (!HasStationTileRail(tile)) continue;
    01459
    01460     /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
    01461     CommandCost ret = EnsureNoVehicleOnGround(tile);
    01462     error.AddCost(ret);
    01463     if (ret.Failed()) continue;
    01464
    01465     /* Check ownership of station */
    01466     T *st = T::GetByTile(tile);
    01467     if (st == NULL) continue;
    01468
    01469     if (_current_company != OWNER_WATER) {
    01470       CommandCost ret = CheckOwnership(st->owner);
    01471       error.AddCost(ret);
    01472       if (ret.Failed()) continue;
    01473     }
    01474
    01475     /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
    01476     quantity++;
    01477
    01478     if (keep_rail || IsStationTileBlocked(tile)) {
    01479       /* Don't refund the 'steel' of the track when we keep the
    01480        *  rail, or when the tile didn't have any rail at all. */
    01481       total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
    01482     }
    01483
    01484     if (flags & DC_EXEC) {
    01485       /* read variables before the station tile is removed */
    01486       uint specindex = GetCustomStationSpecIndex(tile);
    01487       Track track = GetRailStationTrack(tile);
    01488       Owner owner = GetTileOwner(tile);
    01489       RailType rt = GetRailType(tile);
    01490       Train *v = NULL;
    01491
    01492       if (HasStationReservation(tile)) {
    01493         v = GetTrainForReservation(tile, track);
    01494         if (v != NULL) {
    01495           /* Free train reservation. */
    01496           FreeTrainTrackReservation(v);
    01497           if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
    01498           Vehicle *temp = v;
    01499           for (; temp->Next() != NULL; temp = temp->Next()) { }
    01500           if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
    01501         }
    01502       }
    01503
    01504       bool build_rail = keep_rail && !IsStationTileBlocked(tile);
    01505       if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
    01506
    01507       DoClearSquare(tile);
    01508       DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
    01509       if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
    01510       Company::Get(owner)->infrastructure.station--;
    01511       DirtyCompanyInfrastructureWindows(owner);
    01512
    01513       st->rect.AfterRemoveTile(st, tile);
    01514       AddTrackToSignalBuffer(tile, track, owner);
    01515       YapfNotifyTrackLayoutChange(tile, track);
    01516
    01517       DeallocateSpecFromStation(st, specindex);
    01518
    01519       affected_stations.Include(st);
    01520
    01521       if (v != NULL) {
    01522         /* Restore station reservation. */
    01523         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
    01524         TryPathReserve(v, true, true);
    01525         for (; v->Next() != NULL; v = v->Next()) { }
    01526         if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
    01527       }
    01528     }
    01529   }
    01530
    01531   if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
    01532
    01533   for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
    01534     T *st = *stp;
    01535
    01536     /* now we need to make the "spanned" area of the railway station smaller
    01537      * if we deleted something at the edges.
    01538      * we also need to adjust train_tile. */
    01539     MakeRailStationAreaSmaller(st);
    01540     UpdateStationSignCoord(st);
    01541
    01542     /* if we deleted the whole station, delete the train facility. */
    01543     if (st->train_station.tile == INVALID_TILE) {
    01544       st->facilities &= ~FACIL_TRAIN;
    01545       SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
    01546       st->UpdateVirtCoord();
    01547       DeleteStationIfEmpty(st);
    01548     }
    01549   }
    01550
    01551   total_cost.AddCost(quantity * removal_cost);
    01552   return total_cost;
    01553 }
    01554
    01566 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01567 {
    01568   TileIndex end = p1 == 0 ? start : p1;
    01569   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
    01570
    01571   TileArea ta(start, end);
    01572   SmallVector<Station *, 4> affected_stations;
    01573
    01574   CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
    01575   if (ret.Failed()) return ret;
    01576
    01577   /* Do all station specific functions here. */
    01578   for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
    01579     Station *st = *stp;
    01580
    01581     if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
    01582     st->MarkTilesDirty(false);
    01583     st->RecomputeIndustriesNear();
    01584   }
    01585
    01586   /* Now apply the rail cost to the number that we deleted */
    01587   return ret;
    01588 }
    01589
    01601 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01602 {
    01603   TileIndex end = p1 == 0 ? start : p1;
    01604   if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
    01605
    01606   TileArea ta(start, end);
    01607   SmallVector<Waypoint *, 4> affected_stations;
    01608
    01609   return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
    01610 }
    01611
    01612
    01620 template <class T>
    01621 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
    01622 {
    01623   /* Current company owns the station? */
    01624   if (_current_company != OWNER_WATER) {
    01625     CommandCost ret = CheckOwnership(st->owner);
    01626     if (ret.Failed()) return ret;
    01627   }
    01628
    01629   /* determine width and height of platforms */
    01630   TileArea ta = st->train_station;
    01631
    01632   assert(ta.w != 0 && ta.h != 0);
    01633
    01634   CommandCost cost(EXPENSES_CONSTRUCTION);
    01635   /* clear all areas of the station */
    01636   TILE_AREA_LOOP(tile, ta) {
    01637     /* only remove tiles that are actually train station tiles */
    01638     if (!st->TileBelongsToRailStation(tile)) continue;
    01639
    01640     CommandCost ret = EnsureNoVehicleOnGround(tile);
    01641     if (ret.Failed()) return ret;
    01642
    01643     cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
    01644     if (flags & DC_EXEC) {
    01645       /* read variables before the station tile is removed */
    01646       Track track = GetRailStationTrack(tile);
    01647       Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
    01648       Train *v = NULL;
    01649       if (HasStationReservation(tile)) {
    01650         v = GetTrainForReservation(tile, track);
    01651         if (v != NULL) FreeTrainTrackReservation(v);
    01652       }
    01653       if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
    01654       Company::Get(owner)->infrastructure.station--;
    01655       DoClearSquare(tile);
    01656       DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
    01657       AddTrackToSignalBuffer(tile, track, owner);
    01658       YapfNotifyTrackLayoutChange(tile, track);
    01659       if (v != NULL) TryPathReserve(v, true);
    01660     }
    01661   }
    01662
    01663   if (flags & DC_EXEC) {
    01664     st->rect.AfterRemoveRect(st, st->train_station);
    01665
    01666     st->train_station.Clear();
    01667
    01668     st->facilities &= ~FACIL_TRAIN;
    01669
    01670     free(st->speclist);
    01671     st->num_specs = 0;
    01672     st->speclist  = NULL;
    01673     st->cached_anim_triggers = 0;
    01674
    01675     DirtyCompanyInfrastructureWindows(st->owner);
    01676     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
    01677     st->UpdateVirtCoord();
    01678     DeleteStationIfEmpty(st);
    01679   }
    01680
    01681   return cost;
    01682 }
    01683
    01690 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
    01691 {
    01692   /* if there is flooding, remove platforms tile by tile */
    01693   if (_current_company == OWNER_WATER) {
    01694     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
    01695   }
    01696
    01697   Station *st = Station::GetByTile(tile);
    01698   CommandCost cost = RemoveRailStation(st, flags);
    01699
    01700   if (flags & DC_EXEC) st->RecomputeIndustriesNear();
    01701
    01702   return cost;
    01703 }
    01704
    01711 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
    01712 {
    01713   /* if there is flooding, remove waypoints tile by tile */
    01714   if (_current_company == OWNER_WATER) {
    01715     return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
    01716   }
    01717
    01718   return RemoveRailStation(Waypoint::GetByTile(tile), flags);
    01719 }
    01720
    01721
    01727 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
    01728 {
    01729   RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
    01730
    01731   if (*primary_stop == NULL) {
    01732     /* we have no roadstop of the type yet, so write a "primary stop" */
    01733     return primary_stop;
    01734   } else {
    01735     /* there are stops already, so append to the end of the list */
    01736     RoadStop *stop = *primary_stop;
    01737     while (stop->next != NULL) stop = stop->next;
    01738     return &stop->next;
    01739   }
    01740 }
    01741
    01742 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
    01743
    01753 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
    01754 {
    01755   return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
    01756 }
    01757
    01774 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01775 {
    01776   bool type = HasBit(p2, 0);
    01777   bool is_drive_through = HasBit(p2, 1);
    01778   RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
    01779   StationID station_to_join = GB(p2, 16, 16);
    01780   bool reuse = (station_to_join != NEW_STATION);
    01781   if (!reuse) station_to_join = INVALID_STATION;
    01782   bool distant_join = (station_to_join != INVALID_STATION);
    01783
    01784   uint8 width = (uint8)GB(p1, 0, 8);
    01785   uint8 lenght = (uint8)GB(p1, 8, 8);
    01786
    01787   /* Check if the requested road stop is too big */
    01788   if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
    01789   /* Check for incorrect width / length. */
    01790   if (width == 0 || lenght == 0) return CMD_ERROR;
    01791   /* Check if the first tile and the last tile are valid */
    01792   if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
    01793
    01794   TileArea roadstop_area(tile, width, lenght);
    01795
    01796   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
    01797
    01798   if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
    01799
    01800   /* Trams only have drive through stops */
    01801   if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
    01802
    01803   DiagDirection ddir;
    01804   Axis axis;
    01805   if (is_drive_through) {
    01806     /* By definition axis is valid, due to there being 2 axes and reading 1 bit. */
    01807     axis = Extract<Axis, 6, 1>(p2);
    01808     ddir = AxisToDiagDir(axis);
    01809   } else {
    01810     /* By definition ddir is valid, due to there being 4 diagonal directions and reading 2 bits. */
    01811     ddir = Extract<DiagDirection, 6, 2>(p2);
    01812     axis = DiagDirToAxis(ddir);
    01813   }
    01814
    01815   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
    01816   if (ret.Failed()) return ret;
    01817
    01818   /* Total road stop cost. */
    01819   CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
    01820   StationID est = INVALID_STATION;
    01821   ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << axis : 1 << ddir, is_drive_through, type, axis, &est, rts);
    01822   if (ret.Failed()) return ret;
    01823   cost.AddCost(ret);
    01824
    01825   Station *st = NULL;
    01826   ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
    01827   if (ret.Failed()) return ret;
    01828
    01829   /* Check if this number of road stops can be allocated. */
    01830   if (!RoadStop::CanAllocateItem(roadstop_area.w * roadstop_area.h)) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
    01831
    01832   ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
    01833   if (ret.Failed()) return ret;
    01834
    01835   if (flags & DC_EXEC) {
    01836     /* Check every tile in the area. */
    01837     TILE_AREA_LOOP(cur_tile, roadstop_area) {
    01838       RoadTypes cur_rts = GetRoadTypes(cur_tile);
    01839       Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
    01840       Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
    01841
    01842       if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
    01843         RemoveRoadStop(cur_tile, flags);
    01844       }
    01845
    01846       RoadStop *road_stop = new RoadStop(cur_tile);
    01847       /* Insert into linked list of RoadStops. */
    01848       RoadStop **currstop = FindRoadStopSpot(type, st);
    01849       *currstop = road_stop;
    01850
    01851       if (type) {
    01852         st->truck_station.Add(cur_tile);
    01853       } else {
    01854         st->bus_station.Add(cur_tile);
    01855       }
    01856
    01857       /* Initialize an empty station. */
    01858       st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
    01859
    01860       st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
    01861
    01862       RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
    01863       if (is_drive_through) {
    01864         /* Update company infrastructure counts. If the current tile is a normal
    01865          * road tile, count only the new road bits needed to get a full diagonal road. */
    01866         RoadType rt;
    01867         FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
    01868           Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
    01869           if (c != NULL) {
    01870             c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
    01871             DirtyCompanyInfrastructureWindows(c->index);
    01872           }
    01873         }
    01874
    01875         MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, axis);
    01876         road_stop->MakeDriveThrough();
    01877       } else {
    01878         /* Non-drive-through stop never overbuild and always count as two road bits. */
    01879         Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
    01880         MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
    01881       }
    01882       Company::Get(st->owner)->infrastructure.station++;
    01883       DirtyCompanyInfrastructureWindows(st->owner);
    01884
    01885       MarkTileDirtyByTile(cur_tile);
    01886     }
    01887   }
    01888
    01889   if (st != NULL) {
    01890     st->UpdateVirtCoord();
    01891     UpdateStationAcceptance(st, false);
    01892     st->RecomputeIndustriesNear();
    01893     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
    01894     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
    01895     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
    01896   }
    01897   return cost;
    01898 }
    01899
    01900
    01901 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
    01902 {
    01903   if (v->type == VEH_ROAD) {
    01904     /* Okay... we are a road vehicle on a drive through road stop.
    01905      * But that road stop has just been removed, so we need to make
    01906      * sure we are in a valid state... however, vehicles can also
    01907      * turn on road stop tiles, so only clear the 'road stop' state
    01908      * bits and only when the state was 'in road stop', otherwise
    01909      * we'll end up clearing the turn around bits. */
    01910     RoadVehicle *rv = RoadVehicle::From(v);
    01911     if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
    01912   }
    01913
    01914   return NULL;
    01915 }
    01916
    01917
    01924 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
    01925 {
    01926   Station *st = Station::GetByTile(tile);
    01927
    01928   if (_current_company != OWNER_WATER) {
    01929     CommandCost ret = CheckOwnership(st->owner);
    01930     if (ret.Failed()) return ret;
    01931   }
    01932
    01933   bool is_truck = IsTruckStop(tile);
    01934
    01935   RoadStop **primary_stop;
    01936   RoadStop *cur_stop;
    01937   if (is_truck) { // truck stop
    01938     primary_stop = &st->truck_stops;
    01939     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
    01940   } else {
    01941     primary_stop = &st->bus_stops;
    01942     cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
    01943   }
    01944
    01945   assert(cur_stop != NULL);
    01946
    01947   /* don't do the check for drive-through road stops when company bankrupts */
    01948   if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
    01949     /* remove the 'going through road stop' status from all vehicles on that tile */
    01950     if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
    01951   } else {
    01952     CommandCost ret = EnsureNoVehicleOnGround(tile);
    01953     if (ret.Failed()) return ret;
    01954   }
    01955
    01956   if (flags & DC_EXEC) {
    01957     if (*primary_stop == cur_stop) {
    01958       /* removed the first stop in the list */
    01959       *primary_stop = cur_stop->next;
    01960       /* removed the only stop? */
    01961       if (*primary_stop == NULL) {
    01962         st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
    01963       }
    01964     } else {
    01965       /* tell the predecessor in the list to skip this stop */
    01966       RoadStop *pred = *primary_stop;
    01967       while (pred->next != cur_stop) pred = pred->next;
    01968       pred->next = cur_stop->next;
    01969     }
    01970
    01971     /* Update company infrastructure counts. */
    01972     RoadType rt;
    01973     FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
    01974       Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
    01975       if (c != NULL) {
    01976         c->infrastructure.road[rt] -= 2;
    01977         DirtyCompanyInfrastructureWindows(c->index);
    01978       }
    01979     }
    01980     Company::Get(st->owner)->infrastructure.station--;
    01981
    01982     if (IsDriveThroughStopTile(tile)) {
    01983       /* Clears the tile for us */
    01984       cur_stop->ClearDriveThrough();
    01985     } else {
    01986       DoClearSquare(tile);
    01987     }
    01988
    01989     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
    01990     delete cur_stop;
    01991
    01992     /* Make sure no vehicle is going to the old roadstop */
    01993     RoadVehicle *v;
    01994     FOR_ALL_ROADVEHICLES(v) {
    01995       if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
    01996           v->dest_tile == tile) {
    01997         v->dest_tile = v->GetOrderStationLocation(st->index);
    01998       }
    01999     }
    02000
    02001     st->rect.AfterRemoveTile(st, tile);
    02002
    02003     st->UpdateVirtCoord();
    02004     st->RecomputeIndustriesNear();
    02005     DeleteStationIfEmpty(st);
    02006
    02007     /* Update the tile area of the truck/bus stop */
    02008     if (is_truck) {
    02009       st->truck_station.Clear();
    02010       for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
    02011     } else {
    02012       st->bus_station.Clear();
    02013       for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
    02014     }
    02015   }
    02016
    02017   return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
    02018 }
    02019
    02030 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02031 {
    02032   uint8 width = (uint8)GB(p1, 0, 8);
    02033   uint8 height = (uint8)GB(p1, 8, 8);
    02034
    02035   /* Check for incorrect width / height. */
    02036   if (width == 0 || height == 0) return CMD_ERROR;
    02037   /* Check if the first tile and the last tile are valid */
    02038   if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
    02039
    02040   TileArea roadstop_area(tile, width, height);
    02041
    02042   int quantity = 0;
    02043   CommandCost cost(EXPENSES_CONSTRUCTION);
    02044   TILE_AREA_LOOP(cur_tile, roadstop_area) {
    02045     /* Make sure the specified tile is a road stop of the correct type */
    02046     if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
    02047
    02048     /* Save the stop info before it is removed */
    02049     bool is_drive_through = IsDriveThroughStopTile(cur_tile);
    02050     RoadTypes rts = GetRoadTypes(cur_tile);
    02051     RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
    02052         ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
    02053         DiagDirToRoadBits(GetRoadStopDir(cur_tile));
    02054
    02055     Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
    02056     Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
    02057     CommandCost ret = RemoveRoadStop(cur_tile, flags);
    02058     if (ret.Failed()) return ret;
    02059     cost.AddCost(ret);
    02060
    02061     quantity++;
    02062     /* If the stop was a drive-through stop replace the road */
    02063     if ((flags & DC_EXEC) && is_drive_through) {
    02064       MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
    02065           road_owner, tram_owner);
    02066
    02067       /* Update company infrastructure counts. */
    02068       RoadType rt;
    02069       FOR_EACH_SET_ROADTYPE(rt, rts) {
    02070         Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
    02071         if (c != NULL) {
    02072           c->infrastructure.road[rt] += CountBits(road_bits);
    02073           DirtyCompanyInfrastructureWindows(c->index);
    02074         }
    02075       }
    02076     }
    02077   }
    02078
    02079   if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
    02080
    02081   return cost;
    02082 }
    02083
    02090 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
    02091 {
    02092   uint mindist = UINT_MAX;
    02093
    02094   for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
    02095     mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
    02096   }
    02097
    02098   return mindist;
    02099 }
    02100
    02110 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
    02111 {
    02112   /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
    02113    * So no need to go any further*/
    02114   if (as->noise_level < 2) return as->noise_level;
    02115
    02116   uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
    02117
    02118   /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
    02119    * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
    02120    * Basically, it says that the less tolerant a town is, the bigger the distance before
    02121    * an actual decrease can be granted */
    02122   uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
    02123
    02124   /* now, we want to have the distance segmented using the distance judged bareable by town
    02125    * This will give us the coefficient of reduction the distance provides. */
    02126   uint noise_reduction = distance / town_tolerance_distance;
    02127
    02128   /* If the noise reduction equals the airport noise itself, don't give it for free.
    02129    * Otherwise, simply reduce the airport's level. */
    02130   return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
    02131 }
    02132
    02140 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
    02141 {
    02142   Town *t, *nearest = NULL;
    02143   uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
    02144   uint mindist = UINT_MAX - add; // prevent overflow
    02145   FOR_ALL_TOWNS(t) {
    02146     if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
    02147       TileIterator *copy = it.Clone();
    02148       uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
    02149       delete copy;
    02150       if (dist < mindist) {
    02151         nearest = t;
    02152         mindist = dist;
    02153       }
    02154     }
    02155   }
    02156
    02157   return nearest;
    02158 }
    02159
    02160
    02162 void UpdateAirportsNoise()
    02163 {
    02164   Town *t;
    02165   const Station *st;
    02166
    02167   FOR_ALL_TOWNS(t) t->noise_reached = 0;
    02168
    02169   FOR_ALL_STATIONS(st) {
    02170     if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
    02171       const AirportSpec *as = st->airport.GetSpec();
    02172       AirportTileIterator it(st);
    02173       Town *nearest = AirportGetNearestTown(as, it);
    02174       nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
    02175     }
    02176   }
    02177 }
    02178
    02192 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02193 {
    02194   StationID station_to_join = GB(p2, 16, 16);
    02195   bool reuse = (station_to_join != NEW_STATION);
    02196   if (!reuse) station_to_join = INVALID_STATION;
    02197   bool distant_join = (station_to_join != INVALID_STATION);
    02198   byte airport_type = GB(p1, 0, 8);
    02199   byte layout = GB(p1, 8, 8);
    02200
    02201   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
    02202
    02203   if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
    02204
    02205   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
    02206   if (ret.Failed()) return ret;
    02207
    02208   /* Check if a valid, buildable airport was chosen for construction */
    02209   const AirportSpec *as = AirportSpec::Get(airport_type);
    02210   if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
    02211
    02212   Direction rotation = as->rotation[layout];
    02213   int w = as->size_x;
    02214   int h = as->size_y;
    02215   if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
    02216   TileArea airport_area = TileArea(tile, w, h);
    02217
    02218   if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
    02219     return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
    02220   }
    02221
    02222   CommandCost cost = CheckFlatLand(airport_area, flags);
    02223   if (cost.Failed()) return cost;
    02224
    02225   /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
    02226   AirportTileTableIterator iter(as->table[layout], tile);
    02227   Town *nearest = AirportGetNearestTown(as, iter);
    02228   uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
    02229
    02230   /* Check if local auth would allow a new airport */
    02231   StringID authority_refuse_message = STR_NULL;
    02232   Town *authority_refuse_town = NULL;
    02233
    02234   if (_settings_game.economy.station_noise_level) {
    02235     /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
    02236     if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
    02237       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
    02238       authority_refuse_town = nearest;
    02239     }
    02240   } else {
    02241     Town *t = ClosestTownFromTile(tile, UINT_MAX);
    02242     uint num = 0;
    02243     const Station *st;
    02244     FOR_ALL_STATIONS(st) {
    02245       if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
    02246     }
    02247     if (num >= 2) {
    02248       authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
    02249       authority_refuse_town = t;
    02250     }
    02251   }
    02252
    02253   if (authority_refuse_message != STR_NULL) {
    02254     SetDParam(0, authority_refuse_town->index);
    02255     return_cmd_error(authority_refuse_message);
    02256   }
    02257
    02258   Station *st = NULL;
    02259   ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
    02260   if (ret.Failed()) return ret;
    02261
    02262   /* Distant join */
    02263   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
    02264
    02265   ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
    02266   if (ret.Failed()) return ret;
    02267
    02268   if (st != NULL && st->airport.tile != INVALID_TILE) {
    02269     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
    02270   }
    02271
    02272   for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
    02273     cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
    02274   }
    02275
    02276   if (flags & DC_EXEC) {
    02277     /* Always add the noise, so there will be no need to recalculate when option toggles */
    02278     nearest->noise_reached += newnoise_level;
    02279
    02280     st->AddFacility(FACIL_AIRPORT, tile);
    02281     st->airport.type = airport_type;
    02282     st->airport.layout = layout;
    02283     st->airport.flags = 0;
    02284     st->airport.rotation = rotation;
    02285
    02286     st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
    02287
    02288     for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
    02289       MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
    02290       SetStationTileRandomBits(iter, GB(Random(), 0, 4));
    02291       st->airport.Add(iter);
    02292
    02293       if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
    02294     }
    02295
    02296     /* Only call the animation trigger after all tiles have been built */
    02297     for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
    02298       AirportTileAnimationTrigger(st, iter, AAT_BUILT);
    02299     }
    02300
    02301     UpdateAirplanesOnNewStation(st);
    02302
    02303     Company::Get(st->owner)->infrastructure.airport++;
    02304     DirtyCompanyInfrastructureWindows(st->owner);
    02305
    02306     st->UpdateVirtCoord();
    02307     UpdateStationAcceptance(st, false);
    02308     st->RecomputeIndustriesNear();
    02309     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
    02310     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
    02311     InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
    02312
    02313     if (_settings_game.economy.station_noise_level) {
    02314       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
    02315     }
    02316   }
    02317
    02318   return cost;
    02319 }
    02320
    02327 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
    02328 {
    02329   Station *st = Station::GetByTile(tile);
    02330
    02331   if (_current_company != OWNER_WATER) {
    02332     CommandCost ret = CheckOwnership(st->owner);
    02333     if (ret.Failed()) return ret;
    02334   }
    02335
    02336   tile = st->airport.tile;
    02337
    02338   CommandCost cost(EXPENSES_CONSTRUCTION);
    02339
    02340   const Aircraft *a;
    02341   FOR_ALL_AIRCRAFT(a) {
    02342     if (!a->IsNormalAircraft()) continue;
    02343     if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
    02344   }
    02345
    02346   if (flags & DC_EXEC) {
    02347     const AirportSpec *as = st->airport.GetSpec();
    02348     /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
    02349      * And as for construction, always remove it, even if the setting is not set, in order to avoid the
    02350      * need of recalculation */
    02351     AirportTileIterator it(st);
    02352     Town *nearest = AirportGetNearestTown(as, it);
    02353     nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
    02354   }
    02355
    02356   TILE_AREA_LOOP(tile_cur, st->airport) {
    02357     if (!st->TileBelongsToAirport(tile_cur)) continue;
    02358
    02359     CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
    02360     if (ret.Failed()) return ret;
    02361
    02362     cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
    02363
    02364     if (flags & DC_EXEC) {
    02365       if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
    02366       DeleteAnimatedTile(tile_cur);
    02367       DoClearSquare(tile_cur);
    02368       DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
    02369     }
    02370   }
    02371
    02372   if (flags & DC_EXEC) {
    02373     /* Clear the persistent storage. */
    02374     delete st->airport.psa;
    02375
    02376     for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
    02377       DeleteWindowById(
    02378         WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
    02379       );
    02380     }
    02381
    02382     st->rect.AfterRemoveRect(st, st->airport);
    02383
    02384     st->airport.Clear();
    02385     st->facilities &= ~FACIL_AIRPORT;
    02386
    02387     InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
    02388
    02389     if (_settings_game.economy.station_noise_level) {
    02390       SetWindowDirty(WC_TOWN_VIEW, st->town->index);
    02391     }
    02392
    02393     Company::Get(st->owner)->infrastructure.airport--;
    02394     DirtyCompanyInfrastructureWindows(st->owner);
    02395
    02396     st->UpdateVirtCoord();
    02397     st->RecomputeIndustriesNear();
    02398     DeleteStationIfEmpty(st);
    02399     DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
    02400   }
    02401
    02402   return cost;
    02403 }
    02404
    02414 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02415 {
    02416   if (!Station::IsValidID(p1)) return CMD_ERROR;
    02417   Station *st = Station::Get(p1);
    02418
    02419   if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
    02420
    02421   CommandCost ret = CheckOwnership(st->owner);
    02422   if (ret.Failed()) return ret;
    02423
    02424   if (flags & DC_EXEC) {
    02425     st->airport.flags ^= AIRPORT_CLOSED_block;
    02426     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
    02427   }
    02428   return CommandCost();
    02429 }
    02430
    02437 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
    02438 {
    02439   const Vehicle *v;
    02440   FOR_ALL_VEHICLES(v) {
    02441     if ((v->owner == company) == include_company) {
    02442       const Order *order;
    02443       FOR_VEHICLE_ORDERS(v, order) {
    02444         if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
    02445           return true;
    02446         }
    02447       }
    02448     }
    02449   }
    02450   return false;
    02451 }
    02452
    02453 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
    02454   {-1,  0},
    02455   { 0,  0},
    02456   { 0,  0},
    02457   { 0, -1}
    02458 };
    02459 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
    02460 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
    02461
    02471 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02472 {
    02473   StationID station_to_join = GB(p2, 16, 16);
    02474   bool reuse = (station_to_join != NEW_STATION);
    02475   if (!reuse) station_to_join = INVALID_STATION;
    02476   bool distant_join = (station_to_join != INVALID_STATION);
    02477
    02478   if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
    02479
    02480   DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
    02481   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    02482   direction = ReverseDiagDir(direction);
    02483
    02484   /* Docks cannot be placed on rapids */
    02485   if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    02486
    02487   CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
    02488   if (ret.Failed()) return ret;
    02489
    02490   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    02491
    02492   ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    02493   if (ret.Failed()) return ret;
    02494
    02495   TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
    02496
    02497   if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
    02498     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    02499   }
    02500
    02501   if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    02502
    02503   /* Get the water class of the water tile before it is cleared.*/
    02504   WaterClass wc = GetWaterClass(tile_cur);
    02505
    02506   ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    02507   if (ret.Failed()) return ret;
    02508
    02509   tile_cur += TileOffsByDiagDir(direction);
    02510   if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
    02511     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    02512   }
    02513
    02514   TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
    02515       _dock_w_chk[direction], _dock_h_chk[direction]);
    02516
    02517   /* middle */
    02518   Station *st = NULL;
    02519   ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
    02520   if (ret.Failed()) return ret;
    02521
    02522   /* Distant join */
    02523   if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
    02524
    02525   ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
    02526   if (ret.Failed()) return ret;
    02527
    02528   if (st != NULL && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
    02529
    02530   if (flags & DC_EXEC) {
    02531     st->dock_tile = tile;
    02532     st->AddFacility(FACIL_DOCK, tile);
    02533
    02534     st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
    02535
    02536     /* If the water part of the dock is on a canal, update infrastructure counts.
    02537      * This is needed as we've unconditionally cleared that tile before. */
    02538     if (wc == WATER_CLASS_CANAL) {
    02539       Company::Get(st->owner)->infrastructure.water++;
    02540     }
    02541     Company::Get(st->owner)->infrastructure.station += 2;
    02542     DirtyCompanyInfrastructureWindows(st->owner);
    02543
    02544     MakeDock(tile, st->owner, st->index, direction, wc);
    02545
    02546     st->UpdateVirtCoord();
    02547     UpdateStationAcceptance(st, false);
    02548     st->RecomputeIndustriesNear();
    02549     InvalidateWindowData(WC_SELECT_STATION, 0, 0);
    02550     InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
    02551     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
    02552   }
    02553
    02554   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
    02555 }
    02556
    02563 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
    02564 {
    02565   Station *st = Station::GetByTile(tile);
    02566   CommandCost ret = CheckOwnership(st->owner);
    02567   if (ret.Failed()) return ret;
    02568
    02569   TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
    02570
    02571   TileIndex tile1 = st->dock_tile;
    02572   TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
    02573
    02574   ret = EnsureNoVehicleOnGround(tile1);
    02575   if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
    02576   if (ret.Failed()) return ret;
    02577
    02578   if (flags & DC_EXEC) {
    02579     DoClearSquare(tile1);
    02580     MarkTileDirtyByTile(tile1);
    02581     MakeWaterKeepingClass(tile2, st->owner);
    02582
    02583     st->rect.AfterRemoveTile(st, tile1);
    02584     st->rect.AfterRemoveTile(st, tile2);
    02585
    02586     st->dock_tile = INVALID_TILE;
    02587     st->facilities &= ~FACIL_DOCK;
    02588
    02589     Company::Get(st->owner)->infrastructure.station -= 2;
    02590     DirtyCompanyInfrastructureWindows(st->owner);
    02591
    02592     SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
    02593     st->UpdateVirtCoord();
    02594     st->RecomputeIndustriesNear();
    02595     DeleteStationIfEmpty(st);
    02596
    02597     /* All ships that were going to our station, can't go to it anymore.
    02598      * Just clear the order, then automatically the next appropriate order
    02599      * will be selected and in case of no appropriate order it will just
    02600      * wander around the world. */
    02601     Ship *s;
    02602     FOR_ALL_SHIPS(s) {
    02603       if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
    02604         s->LeaveStation();
    02605       }
    02606
    02607       if (s->dest_tile == docking_location) {
    02608         s->dest_tile = 0;
    02609         s->current_order.Free();
    02610       }
    02611     }
    02612   }
    02613
    02614   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
    02615 }
    02616
    02617 #include "table/station_land.h"
    02618
    02619 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
    02620 {
    02621   return &_station_display_datas[st][gfx];
    02622 }
    02623
    02633 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
    02634 {
    02635   bool snow_desert;
    02636   switch (*ground) {
    02637     case SPR_RAIL_TRACK_X:
    02638       snow_desert = false;
    02639       *overlay_offset = RTO_X;
    02640       break;
    02641
    02642     case SPR_RAIL_TRACK_Y:
    02643       snow_desert = false;
    02644       *overlay_offset = RTO_Y;
    02645       break;
    02646
    02647     case SPR_RAIL_TRACK_X_SNOW:
    02648       snow_desert = true;
    02649       *overlay_offset = RTO_X;
    02650       break;
    02651
    02652     case SPR_RAIL_TRACK_Y_SNOW:
    02653       snow_desert = true;
    02654       *overlay_offset = RTO_Y;
    02655       break;
    02656
    02657     default:
    02658       return false;
    02659   }
    02660
    02661   if (ti != NULL) {
    02662     /* Decide snow/desert from tile */
    02663     switch (_settings_game.game_creation.landscape) {
    02664       case LT_ARCTIC:
    02665         snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
    02666         break;
    02667
    02668       case LT_TROPIC:
    02669         snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
    02670         break;
    02671
    02672       default:
    02673         break;
    02674     }
    02675   }
    02676
    02677   *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
    02678   return true;
    02679 }
    02680
    02681 static void DrawTile_Station(TileInfo *ti)
    02682 {
    02683   const NewGRFSpriteLayout *layout = NULL;
    02684   DrawTileSprites tmp_rail_layout;
    02685   const DrawTileSprites *t = NULL;
    02686   RoadTypes roadtypes;
    02687   int32 total_offset;
    02688   const RailtypeInfo *rti = NULL;
    02689   uint32 relocation = 0;
    02690   uint32 ground_relocation = 0;
    02691   BaseStation *st = NULL;
    02692   const StationSpec *statspec = NULL;
    02693   uint tile_layout = 0;
    02694
    02695   if (HasStationRail(ti->tile)) {
    02696     rti = GetRailTypeInfo(GetRailType(ti->tile));
    02697     roadtypes = ROADTYPES_NONE;
    02698     total_offset = rti->GetRailtypeSpriteOffset();
    02699
    02700     if (IsCustomStationSpecIndex(ti->tile)) {
    02701       /* look for customization */
    02702       st = BaseStation::GetByTile(ti->tile);
    02703       statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
    02704
    02705       if (statspec != NULL) {
    02706         tile_layout = GetStationGfx(ti->tile);
    02707
    02708         if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
    02709           uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
    02710           if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
    02711         }
    02712
    02713         /* Ensure the chosen tile layout is valid for this custom station */
    02714         if (statspec->renderdata != NULL) {
    02715           layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
    02716           if (!layout->NeedsPreprocessing()) {
    02717             t = layout;
    02718             layout = NULL;
    02719           }
    02720         }
    02721       }
    02722     }
    02723   } else {
    02724     roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
    02725     total_offset = 0;
    02726   }
    02727
    02728   StationGfx gfx = GetStationGfx(ti->tile);
    02729   if (IsAirport(ti->tile)) {
    02730     gfx = GetAirportGfx(ti->tile);
    02731     if (gfx >= NEW_AIRPORTTILE_OFFSET) {
    02732       const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
    02733       if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
    02734         return;
    02735       }
    02736       /* No sprite group (or no valid one) found, meaning no graphics associated.
    02737        * Use the substitute one instead */
    02738       assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
    02739       gfx = ats->grf_prop.subst_id;
    02740     }
    02741     switch (gfx) {
    02742       case APT_RADAR_GRASS_FENCE_SW:
    02743         t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
    02744         break;
    02745       case APT_GRASS_FENCE_NE_FLAG:
    02746         t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
    02747         break;
    02748       case APT_RADAR_FENCE_SW:
    02749         t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
    02750         break;
    02751       case APT_RADAR_FENCE_NE:
    02752         t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
    02753         break;
    02754       case APT_GRASS_FENCE_NE_FLAG_2:
    02755         t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
    02756         break;
    02757     }
    02758   }
    02759
    02760   Owner owner = GetTileOwner(ti->tile);
    02761
    02762   PaletteID palette;
    02763   if (Company::IsValidID(owner)) {
    02764     palette = COMPANY_SPRITE_COLOUR(owner);
    02765   } else {
    02766     /* Some stations are not owner by a company, namely oil rigs */
    02767     palette = PALETTE_TO_GREY;
    02768   }
    02769
    02770   if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
    02771
    02772   /* don't show foundation for docks */
    02773   if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
    02774     if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
    02775       /* Station has custom foundations.
    02776        * Check whether the foundation continues beyond the tile's upper sides. */
    02777       uint edge_info = 0;
    02778       int z;
    02779       Slope slope = GetFoundationPixelSlope(ti->tile, &z);
    02780       if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
    02781       if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
    02782       SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
    02783       if (image == 0) goto draw_default_foundation;
    02784
    02785       if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
    02786         /* Station provides extended foundations. */
    02787
    02788         static const uint8 foundation_parts[] = {
    02789           0, 0, 0, 0, // Invalid,  Invalid,   Invalid,   SLOPE_SW
    02790           0, 1, 2, 3, // Invalid,  SLOPE_EW,  SLOPE_SE,  SLOPE_WSE
    02791           0, 4, 5, 6, // Invalid,  SLOPE_NW,  SLOPE_NS,  SLOPE_NWS
    02792           7, 8, 9     // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
    02793         };
    02794
    02795         AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
    02796       } else {
    02797         /* Draw simple foundations, built up from 8 possible foundation sprites. */
    02798
    02799         /* Each set bit represents one of the eight composite sprites to be drawn.
    02800          * 'Invalid' entries will not drawn but are included for completeness. */
    02801         static const uint8 composite_foundation_parts[] = {
    02802           /* Invalid  (00000000), Invalid   (11010001), Invalid   (11100100), SLOPE_SW  (11100000) */
    02803              0x00,                0xD1,                 0xE4,                 0xE0,
    02804           /* Invalid  (11001010), SLOPE_EW  (11001001), SLOPE_SE  (11000100), SLOPE_WSE (11000000) */
    02805              0xCA,                0xC9,                 0xC4,                 0xC0,
    02806           /* Invalid  (11010010), SLOPE_NW  (10010001), SLOPE_NS  (11100100), SLOPE_NWS (10100000) */
    02807              0xD2,                0x91,                 0xE4,                 0xA0,
    02808           /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
    02809              0x4A,                0x09,                 0x44
    02810         };
    02811
    02812         uint8 parts = composite_foundation_parts[ti->tileh];
    02813
    02814         /* If foundations continue beyond the tile's upper sides then
    02815          * mask out the last two pieces. */
    02816         if (HasBit(edge_info, 0)) ClrBit(parts, 6);
    02817         if (HasBit(edge_info, 1)) ClrBit(parts, 7);
    02818
    02819         if (parts == 0) {
    02820           /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
    02821            * correct offset for the childsprites.
    02822            * So, draw the (completely empty) sprite of the default foundations. */
    02823           goto draw_default_foundation;
    02824         }
    02825
    02826         StartSpriteCombine();
    02827         for (int i = 0; i < 8; i++) {
    02828           if (HasBit(parts, i)) {
    02829             AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
    02830           }
    02831         }
    02832         EndSpriteCombine();
    02833       }
    02834
    02835       OffsetGroundSprite(31, 1);
    02836       ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
    02837     } else {
    02838 draw_default_foundation:
    02839       DrawFoundation(ti, FOUNDATION_LEVELED);
    02840     }
    02841   }
    02842
    02843   if (IsBuoy(ti->tile)) {
    02844     DrawWaterClassGround(ti);
    02845     SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
    02846     if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
    02847   } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
    02848     if (ti->tileh == SLOPE_FLAT) {
    02849       DrawWaterClassGround(ti);
    02850     } else {
    02851       assert(IsDock(ti->tile));
    02852       TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
    02853       WaterClass wc = GetWaterClass(water_tile);
    02854       if (wc == WATER_CLASS_SEA) {
    02855         DrawShoreTile(ti->tileh);
    02856       } else {
    02857         DrawClearLandTile(ti, 3);
    02858       }
    02859     }
    02860   } else {
    02861     if (layout != NULL) {
    02862       /* Sprite layout which needs preprocessing */
    02863       bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
    02864       uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
    02865       uint8 var10;
    02866       FOR_EACH_SET_BIT(var10, var10_values) {
    02867         uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
    02868         layout->ProcessRegisters(var10, var10_relocation, separate_ground);
    02869       }
    02870       tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
    02871       t = &tmp_rail_layout;
    02872       total_offset = 0;
    02873     } else if (statspec != NULL) {
    02874       /* Simple sprite layout */
    02875       ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
    02876       if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
    02877         ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
    02878       }
    02879       ground_relocation += rti->fallback_railtype;
    02880     }
    02881
    02882     SpriteID image = t->ground.sprite;
    02883     PaletteID pal  = t->ground.pal;
    02884     RailTrackOffset overlay_offset;
    02885     if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
    02886       SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
    02887       DrawGroundSprite(image, PAL_NONE);
    02888       DrawGroundSprite(ground + overlay_offset, PAL_NONE);
    02889
    02890       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
    02891         SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
    02892         DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
    02893       }
    02894     } else {
    02895       image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
    02896       if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
    02897       DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
    02898
    02899       /* PBS debugging, draw reserved tracks darker */
    02900       if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
    02901         const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
    02902         DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
    02903       }
    02904     }
    02905   }
    02906
    02907   if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
    02908
    02909   if (HasBit(roadtypes, ROADTYPE_TRAM)) {
    02910     Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
    02911     DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
    02912     DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
    02913   }
    02914
    02915   if (IsRailWaypoint(ti->tile)) {
    02916     /* Don't offset the waypoint graphics; they're always the same. */
    02917     total_offset = 0;
    02918   }
    02919
    02920   DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
    02921 }
    02922
    02923 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
    02924 {
    02925   int32 total_offset = 0;
    02926   PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
    02927   const DrawTileSprites *t = GetStationTileLayout(st, image);
    02928   const RailtypeInfo *rti = NULL;
    02929
    02930   if (railtype != INVALID_RAILTYPE) {
    02931     rti = GetRailTypeInfo(railtype);
    02932     total_offset = rti->GetRailtypeSpriteOffset();
    02933   }
    02934
    02935   SpriteID img = t->ground.sprite;
    02936   RailTrackOffset overlay_offset;
    02937   if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
    02938     SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
    02939     DrawSprite(img, PAL_NONE, x, y);
    02940     DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
    02941   } else {
    02942     DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
    02943   }
    02944
    02945   if (roadtype == ROADTYPE_TRAM) {
    02946     DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
    02947   }
    02948
    02949   /* Default waypoint has no railtype specific sprites */
    02950   DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
    02951 }
    02952
    02953 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
    02954 {
    02955   return GetTileMaxPixelZ(tile);
    02956 }
    02957
    02958 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
    02959 {
    02960   return FlatteningFoundation(tileh);
    02961 }
    02962
    02963 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
    02964 {
    02965   td->owner[0] = GetTileOwner(tile);
    02966   if (IsDriveThroughStopTile(tile)) {
    02967     Owner road_owner = INVALID_OWNER;
    02968     Owner tram_owner = INVALID_OWNER;
    02969     RoadTypes rts = GetRoadTypes(tile);
    02970     if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    02971     if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
    02972
    02973     /* Is there a mix of owners? */
    02974     if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
    02975         (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
    02976       uint i = 1;
    02977       if (road_owner != INVALID_OWNER) {
    02978         td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
    02979         td->owner[i] = road_owner;
    02980         i++;
    02981       }
    02982       if (tram_owner != INVALID_OWNER) {
    02983         td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
    02984         td->owner[i] = tram_owner;
    02985       }
    02986     }
    02987   }
    02988   td->build_date = BaseStation::GetByTile(tile)->build_date;
    02989
    02990   if (HasStationTileRail(tile)) {
    02991     const StationSpec *spec = GetStationSpec(tile);
    02992
    02993     if (spec != NULL) {
    02994       td->station_class = StationClass::Get(spec->cls_id)->name;
    02995       td->station_name  = spec->name;
    02996
    02997       if (spec->grf_prop.grffile != NULL) {
    02998         const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
    02999         td->grf = gc->GetName();
    03000       }
    03001     }
    03002
    03003     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
    03004     td->rail_speed = rti->max_speed;
    03005   }
    03006
    03007   if (IsAirport(tile)) {
    03008     const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
    03009     td->airport_class = AirportClass::Get(as->cls_id)->name;
    03010     td->airport_name = as->name;
    03011
    03012     const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
    03013     td->airport_tile_name = ats->name;
    03014
    03015     if (as->grf_prop.grffile != NULL) {
    03016       const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
    03017       td->grf = gc->GetName();
    03018     } else if (ats->grf_prop.grffile != NULL) {
    03019       const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
    03020       td->grf = gc->GetName();
    03021     }
    03022   }
    03023
    03024   StringID str;
    03025   switch (GetStationType(tile)) {
    03026     default: NOT_REACHED();
    03027     case STATION_RAIL:     str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
    03028     case STATION_AIRPORT:
    03029       str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
    03030       break;
    03031     case STATION_TRUCK:    str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
    03032     case STATION_BUS:      str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
    03033     case STATION_OILRIG:   str = STR_INDUSTRY_NAME_OIL_RIG; break;
    03034     case STATION_DOCK:     str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
    03035     case STATION_BUOY:     str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
    03036     case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
    03037   }
    03038   td->str = str;
    03039 }
    03040
    03041
    03042 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
    03043 {
    03044   TrackBits trackbits = TRACK_BIT_NONE;
    03045
    03046   switch (mode) {
    03047     case TRANSPORT_RAIL:
    03048       if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
    03049         trackbits = TrackToTrackBits(GetRailStationTrack(tile));
    03050       }
    03051       break;
    03052
    03053     case TRANSPORT_WATER:
    03054       /* buoy is coded as a station, it is always on open water */
    03055       if (IsBuoy(tile)) {
    03056         trackbits = TRACK_BIT_ALL;
    03057         /* remove tracks that connect NE map edge */
    03058         if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
    03059         /* remove tracks that connect NW map edge */
    03060         if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
    03061       }
    03062       break;
    03063
    03064     case TRANSPORT_ROAD:
    03065       if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
    03066         DiagDirection dir = GetRoadStopDir(tile);
    03067         Axis axis = DiagDirToAxis(dir);
    03068
    03069         if (side != INVALID_DIAGDIR) {
    03070           if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
    03071         }
    03072
    03073         trackbits = AxisToTrackBits(axis);
    03074       }
    03075       break;
    03076
    03077     default:
    03078       break;
    03079   }
    03080
    03081   return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
    03082 }
    03083
    03084
    03085 static void TileLoop_Station(TileIndex tile)
    03086 {
    03087   /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
    03088    * hardcoded.....not good */
    03089   switch (GetStationType(tile)) {
    03090     case STATION_AIRPORT:
    03091       AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
    03092       break;
    03093
    03094     case STATION_DOCK:
    03095       if (!IsTileFlat(tile)) break; // only handle water part
    03096       /* FALL THROUGH */
    03097     case STATION_OILRIG: //(station part)
    03098     case STATION_BUOY:
    03099       TileLoop_Water(tile);
    03100       break;
    03101
    03102     default: break;
    03103   }
    03104 }
    03105
    03106
    03107 static void AnimateTile_Station(TileIndex tile)
    03108 {
    03109   if (HasStationRail(tile)) {
    03110     AnimateStationTile(tile);
    03111     return;
    03112   }
    03113
    03114   if (IsAirport(tile)) {
    03115     AnimateAirportTile(tile);
    03116   }
    03117 }
    03118
    03119
    03120 static bool ClickTile_Station(TileIndex tile)
    03121 {
    03122   const BaseStation *bst = BaseStation::GetByTile(tile);
    03123
    03124   if (bst->facilities & FACIL_WAYPOINT) {
    03125     ShowWaypointWindow(Waypoint::From(bst));
    03126   } else if (IsHangar(tile)) {
    03127     const Station *st = Station::From(bst);
    03128     ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
    03129   } else {
    03130     ShowStationViewWindow(bst->index);
    03131   }
    03132   return true;
    03133 }
    03134
    03135 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
    03136 {
    03137   if (v->type == VEH_TRAIN) {
    03138     StationID station_id = GetStationIndex(tile);
    03139     if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
    03140     if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
    03141
    03142     int station_ahead;
    03143     int station_length;
    03144     int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
    03145
    03146     /* Stop whenever that amount of station ahead + the distance from the
    03147      * begin of the platform to the stop location is longer than the length
    03148      * of the platform. Station ahead 'includes' the current tile where the
    03149      * vehicle is on, so we need to subtract that. */
    03150     if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
    03151
    03152     DiagDirection dir = DirToDiagDir(v->direction);
    03153
    03154     x &= 0xF;
    03155     y &= 0xF;
    03156
    03157     if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
    03158     if (y == TILE_SIZE / 2) {
    03159       if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
    03160       stop &= TILE_SIZE - 1;
    03161
    03162       if (x == stop) {
    03163         return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
    03164       } else if (x < stop) {
    03165         v->vehstatus |= VS_TRAIN_SLOWING;
    03166         uint16 spd = max(0, (stop - x) * 20 - 15);
    03167         if (spd < v->cur_speed) v->cur_speed = spd;
    03168       }
    03169     }
    03170   } else if (v->type == VEH_ROAD) {
    03171     RoadVehicle *rv = RoadVehicle::From(v);
    03172     if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
    03173       if (IsRoadStop(tile) && rv->IsFrontEngine()) {
    03174         /* Attempt to allocate a parking bay in a road stop */
    03175         return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
    03176       }
    03177     }
    03178   }
    03179
    03180   return VETSB_CONTINUE;
    03181 }
    03182
    03187 void TriggerWatchedCargoCallbacks(Station *st)
    03188 {
    03189   /* Collect cargoes accepted since the last big tick. */
    03190   uint cargoes = 0;
    03191   for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
    03192     if (HasBit(st->goods[cid].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
    03193   }
    03194
    03195   /* Anything to do? */
    03196   if (cargoes == 0) return;
    03197
    03198   /* Loop over all houses in the catchment. */
    03199   Rect r = st->GetCatchmentRect();
    03200   TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
    03201   TILE_AREA_LOOP(tile, ta) {
    03202     if (IsTileType(tile, MP_HOUSE)) {
    03203       WatchedCargoCallback(tile, cargoes);
    03204     }
    03205   }
    03206 }
    03207
    03214 static bool StationHandleBigTick(BaseStation *st)
    03215 {
    03216   if (!st->IsInUse()) {
    03217     if (++st->delete_ctr >= 8) delete st;
    03218     return false;
    03219   }
    03220
    03221   if (Station::IsExpected(st)) {
    03222     TriggerWatchedCargoCallbacks(Station::From(st));
    03223
    03224     for (CargoID i = 0; i < NUM_CARGO; i++) {
    03225       ClrBit(Station::From(st)->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
    03226     }
    03227   }
    03228
    03229
    03230   if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
    03231
    03232   return true;
    03233 }
    03234
    03235 static inline void byte_inc_sat(byte *p)
    03236 {
    03237   byte b = *p + 1;
    03238   if (b != 0) *p = b;
    03239 }
    03240
    03241 static void UpdateStationRating(Station *st)
    03242 {
    03243   bool waiting_changed = false;
    03244
    03245   byte_inc_sat(&st->time_since_load);
    03246   byte_inc_sat(&st->time_since_unload);
    03247
    03248   const CargoSpec *cs;
    03249   FOR_ALL_CARGOSPECS(cs) {
    03250     GoodsEntry *ge = &st->goods[cs->Index()];
    03251     /* Slowly increase the rating back to his original level in the case we
    03252      *  didn't deliver cargo yet to this station. This happens when a bribe
    03253      *  failed while you didn't moved that cargo yet to a station. */
    03254     if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
    03255       ge->rating++;
    03256     }
    03257
    03258     /* Only change the rating if we are moving this cargo */
    03259     if (ge->HasRating()) {
    03260       byte_inc_sat(&ge->time_since_pickup);
    03261
    03262       bool skip = false;
    03263       int rating = 0;
    03264       uint waiting = ge->cargo.TotalCount();
    03265
    03266       /* num_dests is at least 1 if there is any cargo as
    03267        * INVALID_STATION is also a destination.
    03268        */
    03269       uint num_dests = (uint)ge->cargo.Packets()->MapSize();
    03270
    03271       /* Average amount of cargo per next hop, but prefer solitary stations
    03272        * with only one or two next hops. They are allowed to have more
    03273        * cargo waiting per next hop.
    03274        * With manual cargo distribution waiting_avg = waiting / 2 as then
    03275        * INVALID_STATION is the only destination.
    03276        */
    03277       uint waiting_avg = waiting / (num_dests + 1);
    03278
    03279       if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
    03280         /* Perform custom station rating. If it succeeds the speed, days in transit and
    03281          * waiting cargo ratings must not be executed. */
    03282
    03283         /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
    03284         uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
    03285
    03286         uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
    03287         /* Convert to the 'old' vehicle types */
    03288         uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
    03289         uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
    03290         if (callback != CALLBACK_FAILED) {
    03291           skip = true;
    03292           rating = GB(callback, 0, 14);
    03293
    03294           /* Simulate a 15 bit signed value */
    03295           if (HasBit(callback, 14)) rating -= 0x4000;
    03296         }
    03297       }
    03298
    03299       if (!skip) {
    03300         int b = ge->last_speed - 85;
    03301         if (b >= 0) rating += b >> 2;
    03302
    03303         byte waittime = ge->time_since_pickup;
    03304         if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
    03305         (waittime > 21) ||
    03306         (rating += 25, waittime > 12) ||
    03307         (rating += 25, waittime > 6) ||
    03308         (rating += 45, waittime > 3) ||
    03309         (rating += 35, true);
    03310
    03311         (rating -= 90, ge->max_waiting_cargo > 1500) ||
    03312         (rating += 55, ge->max_waiting_cargo > 1000) ||
    03313         (rating += 35, ge->max_waiting_cargo > 600) ||
    03314         (rating += 10, ge->max_waiting_cargo > 300) ||
    03315         (rating += 20, ge->max_waiting_cargo > 100) ||
    03316         (rating += 10, true);
    03317       }
    03318
    03319       if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
    03320
    03321       byte age = ge->last_age;
    03322       (age >= 3) ||
    03323       (rating += 10, age >= 2) ||
    03324       (rating += 10, age >= 1) ||
    03325       (rating += 13, true);
    03326
    03327       {
    03328         int or_ = ge->rating; // old rating
    03329
    03330         /* only modify rating in steps of -2, -1, 0, 1 or 2 */
    03331         ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
    03332
    03333         /* if rating is <= 64 and more than 100 items waiting on average per destination,
    03334          * remove some random amount of goods from the station */
    03335         if (rating <= 64 && waiting_avg >= 100) {
    03336           int dec = Random() & 0x1F;
    03337           if (waiting_avg < 200) dec &= 7;
    03338           waiting -= (dec + 1) * num_dests;
    03339           waiting_changed = true;
    03340         }
    03341
    03342         /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
    03343         if (rating <= 127 && waiting != 0) {
    03344           uint32 r = Random();
    03345           if (rating <= (int)GB(r, 0, 7)) {
    03346             /* Need to have int, otherwise it will just overflow etc. */
    03347             waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
    03348             waiting_changed = true;
    03349           }
    03350         }
    03351
    03352         /* At some point we really must cap the cargo. Previously this
    03353          * was a strict 4095, but now we'll have a less strict, but
    03354          * increasingly aggressive truncation of the amount of cargo. */
    03355         static const uint WAITING_CARGO_THRESHOLD  = 1 << 12;
    03356         static const uint WAITING_CARGO_CUT_FACTOR = 1 <<  6;
    03357         static const uint MAX_WAITING_CARGO        = 1 << 15;
    03358
    03359         if (waiting > WAITING_CARGO_THRESHOLD) {
    03360           uint difference = waiting - WAITING_CARGO_THRESHOLD;
    03361           waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
    03362
    03363           waiting = min(waiting, MAX_WAITING_CARGO);
    03364           waiting_changed = true;
    03365         }
    03366
    03367         /* We can't truncate cargo that's already reserved for loading.
    03368          * Thus StoredCount() here. */
    03369         if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
    03370           /* Feed back the exact own waiting cargo at this station for the
    03371            * next rating calculation. */
    03372           ge->max_waiting_cargo = 0;
    03373
    03374           /* If truncating also punish the source stations' ratings to
    03375            * decrease the flow of incoming cargo. */
    03376
    03377           StationCargoAmountMap waiting_per_source;
    03378           ge->cargo.Truncate(ge->cargo.AvailableCount() - waiting, &waiting_per_source);
    03379           for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
    03380             Station *source_station = Station::GetIfValid(i->first);
    03381             if (source_station == NULL) continue;
    03382
    03383             GoodsEntry &source_ge = source_station->goods[cs->Index()];
    03384             source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
    03385           }
    03386         } else {
    03387           /* If the average number per next hop is low, be more forgiving. */
    03388           ge->max_waiting_cargo = waiting_avg;
    03389         }
    03390       }
    03391     }
    03392   }
    03393
    03394   StationID index = st->index;
    03395   if (waiting_changed) {
    03396     SetWindowDirty(WC_STATION_VIEW, index); // update whole window
    03397   } else {
    03398     SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
    03399   }
    03400 }
    03401
    03410 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
    03411 {
    03412   GoodsEntry &ge = st->goods[c];
    03413
    03414   /* Reroute cargo in station. */
    03415   ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
    03416
    03417   /* Reroute cargo staged to be transfered. */
    03418   for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
    03419     for (Vehicle *v = *it; v != NULL; v = v->Next()) {
    03420       if (v->cargo_type != c) continue;
    03421       v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
    03422     }
    03423   }
    03424 }
    03425
    03434 void DeleteStaleLinks(Station *from)
    03435 {
    03436   for (CargoID c = 0; c < NUM_CARGO; ++c) {
    03437     GoodsEntry &ge = from->goods[c];
    03438     LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
    03439     if (lg == NULL) continue;
    03440     Node node = (*lg)[ge.node];
    03441     for (EdgeIterator it(node.Begin()); it != node.End();) {
    03442       Edge edge = it->second;
    03443       Station *to = Station::Get((*lg)[it->first].Station());
    03444       assert(to->goods[c].node == it->first);
    03445       ++it; // Do that before removing the edge. Anything else may crash.
    03446       assert(_date >= edge.LastUpdate());
    03447       uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
    03448       if ((uint)(_date - edge.LastUpdate()) > timeout) {
    03449         /* Have all vehicles refresh their next hops before deciding to
    03450          * remove the node. */
    03451         bool updated = false;
    03452         OrderList *l;
    03453         FOR_ALL_ORDER_LISTS(l) {
    03454           bool found_from = false;
    03455           bool found_to = false;
    03456           for (Order *order = l->GetFirstOrder(); order != NULL; order = order->next) {
    03457             if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
    03458             if (order->GetDestination() == from->index) {
    03459               found_from = true;
    03460               if (found_to) break;
    03461             } else if (order->GetDestination() == to->index) {
    03462               found_to = true;
    03463               if (found_from) break;
    03464             }
    03465           }
    03466           if (!found_to || !found_from) continue;
    03467           for (Vehicle *v = l->GetFirstSharedVehicle(); !updated && v != NULL; v = v->NextShared()) {
    03468             /* There is potential for optimization here:
    03469              * - Usually consists of the same order list are the same. It's probably better to
    03470              *   first check the first of each list, then the second of each list and so on.
    03471              * - We could try to figure out if we've seen a consist with the same cargo on the
    03472              *   same list already and if the consist can actually carry the cargo we're looking
    03473              *   for. With conditional and refit orders this is not quite trivial, though. */
    03474             LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
    03475             if (edge.LastUpdate() == _date) updated = true;
    03476           }
    03477           if (updated) break;
    03478         }
    03479         if (!updated) {
    03480           /* If it's still considered dead remove it. */
    03481           node.RemoveEdge(to->goods[c].node);
    03482           ge.flows.DeleteFlows(to->index);
    03483           RerouteCargo(from, c, to->index, from->index);
    03484         }
    03485       } else if (edge.LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastUnrestrictedUpdate()) > timeout) {
    03486         edge.Restrict();
    03487         ge.flows.RestrictFlows(to->index);
    03488         RerouteCargo(from, c, to->index, from->index);
    03489       } else if (edge.LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastRestrictedUpdate()) > timeout) {
    03490         edge.Release();
    03491       }
    03492     }
    03493     assert(_date >= lg->LastCompression());
    03494     if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
    03495       lg->Compress();
    03496     }
    03497   }
    03498 }
    03499
    03508 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage)
    03509 {
    03510   GoodsEntry &ge1 = st->goods[cargo];
    03511   Station *st2 = Station::Get(next_station_id);
    03512   GoodsEntry &ge2 = st2->goods[cargo];
    03513   LinkGraph *lg = NULL;
    03514   if (ge1.link_graph == INVALID_LINK_GRAPH) {
    03515     if (ge2.link_graph == INVALID_LINK_GRAPH) {
    03516       if (LinkGraph::CanAllocateItem()) {
    03517         lg = new LinkGraph(cargo);
    03518         LinkGraphSchedule::Instance()->Queue(lg);
    03519         ge2.link_graph = lg->index;
    03520         ge2.node = lg->AddNode(st2);
    03521       } else {
    03522         DEBUG(misc, 0, "Can't allocate link graph");
    03523       }
    03524     } else {
    03525       lg = LinkGraph::Get(ge2.link_graph);
    03526     }
    03527     if (lg) {
    03528       ge1.link_graph = lg->index;
    03529       ge1.node = lg->AddNode(st);
    03530     }
    03531   } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
    03532     lg = LinkGraph::Get(ge1.link_graph);
    03533     ge2.link_graph = lg->index;
    03534     ge2.node = lg->AddNode(st2);
    03535   } else {
    03536     lg = LinkGraph::Get(ge1.link_graph);
    03537     if (ge1.link_graph != ge2.link_graph) {
    03538       LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
    03539       if (lg->Size() < lg2->Size()) {
    03540         LinkGraphSchedule::Instance()->Unqueue(lg);
    03541         lg2->Merge(lg); // Updates GoodsEntries of lg
    03542         lg = lg2;
    03543       } else {
    03544         LinkGraphSchedule::Instance()->Unqueue(lg2);
    03545         lg->Merge(lg2); // Updates GoodsEntries of lg2
    03546       }
    03547     }
    03548   }
    03549   if (lg != NULL) {
    03550     (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage);
    03551   }
    03552 }
    03553
    03560 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
    03561 {
    03562   for (const Vehicle *v = front; v != NULL; v = v->Next()) {
    03563     if (v->refit_cap > 0) {
    03564       /* The cargo count can indeed be higher than the refit_cap if
    03565        * wagons have been auto-replaced and subsequently auto-
    03566        * refitted to a higher capacity. The cargo gets redistributed
    03567        * among the wagons in that case.
    03568        * As usage is not such an important figure anyway we just
    03569        * ignore the additional cargo then.*/
    03570       IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
    03571         min(v->refit_cap, v->cargo.StoredCount()));
    03572     }
    03573   }
    03574 }
    03575
    03576 /* called for every station each tick */
    03577 static void StationHandleSmallTick(BaseStation *st)
    03578 {
    03579   if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
    03580
    03581   byte b = st->delete_ctr + 1;
    03582   if (b >= STATION_RATING_TICKS) b = 0;
    03583   st->delete_ctr = b;
    03584
    03585   if (b == 0) UpdateStationRating(Station::From(st));
    03586 }
    03587
    03588 void OnTick_Station()
    03589 {
    03590   if (_game_mode == GM_EDITOR) return;
    03591
    03592   BaseStation *st;
    03593   FOR_ALL_BASE_STATIONS(st) {
    03594     StationHandleSmallTick(st);
    03595
    03596     /* Clean up the link graph about once a week. */
    03597     if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
    03598       DeleteStaleLinks(Station::From(st));
    03599     };
    03600
    03601     /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
    03602      * Station index is included so that triggers are not all done
    03603      * at the same time. */
    03604     if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
    03605       /* Stop processing this station if it was deleted */
    03606       if (!StationHandleBigTick(st)) continue;
    03607       TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
    03608       if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
    03609     }
    03610   }
    03611 }
    03612
    03614 void StationMonthlyLoop()
    03615 {
    03616   Station *st;
    03617
    03618   FOR_ALL_STATIONS(st) {
    03619     for (CargoID i = 0; i < NUM_CARGO; i++) {
    03620       GoodsEntry *ge = &st->goods[i];
    03621       SB(ge->acceptance_pickup, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH, 1));
    03622       ClrBit(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
    03623     }
    03624   }
    03625 }
    03626
    03627
    03628 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
    03629 {
    03630   Station *st;
    03631
    03632   FOR_ALL_STATIONS(st) {
    03633     if (st->owner == owner &&
    03634         DistanceManhattan(tile, st->xy) <= radius) {
    03635       for (CargoID i = 0; i < NUM_CARGO; i++) {
    03636         GoodsEntry *ge = &st->goods[i];
    03637
    03638         if (ge->acceptance_pickup != 0) {
    03639           ge->rating = Clamp(ge->rating + amount, 0, 255);
    03640         }
    03641       }
    03642     }
    03643   }
    03644 }
    03645
    03646 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
    03647 {
    03648   /* We can't allocate a CargoPacket? Then don't do anything
    03649    * at all; i.e. just discard the incoming cargo. */
    03650   if (!CargoPacket::CanAllocateItem()) return 0;
    03651
    03652   GoodsEntry &ge = st->goods[type];
    03653   amount += ge.amount_fract;
    03654   ge.amount_fract = GB(amount, 0, 8);
    03655
    03656   amount >>= 8;
    03657   /* No new "real" cargo item yet. */
    03658   if (amount == 0) return 0;
    03659
    03660   StationID next = ge.GetVia(st->index);
    03661   ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
    03662   LinkGraph *lg = NULL;
    03663   if (ge.link_graph == INVALID_LINK_GRAPH) {
    03664     if (LinkGraph::CanAllocateItem()) {
    03665       lg = new LinkGraph(type);
    03666       LinkGraphSchedule::Instance()->Queue(lg);
    03667       ge.link_graph = lg->index;
    03668       ge.node = lg->AddNode(st);
    03669     } else {
    03670       DEBUG(misc, 0, "Can't allocate link graph");
    03671     }
    03672   } else {
    03673     lg = LinkGraph::Get(ge.link_graph);
    03674   }
    03675   if (lg != NULL) (*lg)[ge.node].UpdateSupply(amount);
    03676
    03677   if (!ge.HasRating()) {
    03678     InvalidateWindowData(WC_STATION_LIST, st->index);
    03679     SetBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP);
    03680   }
    03681
    03682   TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
    03683   TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
    03684   AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
    03685
    03686   SetWindowDirty(WC_STATION_VIEW, st->index);
    03687   st->MarkTilesDirty(true);
    03688   return amount;
    03689 }
    03690
    03691 static bool IsUniqueStationName(const char *name)
    03692 {
    03693   const Station *st;
    03694
    03695   FOR_ALL_STATIONS(st) {
    03696     if (st->name != NULL && strcmp(st->name, name) == 0) return false;
    03697   }
    03698
    03699   return true;
    03700 }
    03701
    03711 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    03712 {
    03713   Station *st = Station::GetIfValid(p1);
    03714   if (st == NULL) return CMD_ERROR;
    03715
    03716   CommandCost ret = CheckOwnership(st->owner);
    03717   if (ret.Failed()) return ret;
    03718
    03719   bool reset = StrEmpty(text);
    03720
    03721   if (!reset) {
    03722     if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
    03723     if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    03724   }
    03725
    03726   if (flags & DC_EXEC) {
    03727     free(st->name);
    03728     st->name = reset ? NULL : strdup(text);
    03729
    03730     st->UpdateVirtCoord();
    03731     InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
    03732   }
    03733
    03734   return CommandCost();
    03735 }
    03736
    03743 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
    03744 {
    03745   /* area to search = producer plus station catchment radius */
    03746   uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
    03747
    03748   uint x = TileX(location.tile);
    03749   uint y = TileY(location.tile);
    03750
    03751   uint min_x = (x > max_rad) ? x - max_rad : 0;
    03752   uint max_x = x + location.w + max_rad;
    03753   uint min_y = (y > max_rad) ? y - max_rad : 0;
    03754   uint max_y = y + location.h + max_rad;
    03755
    03756   if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
    03757   if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
    03758   if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
    03759   if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
    03760
    03761   for (uint cy = min_y; cy < max_y; cy++) {
    03762     for (uint cx = min_x; cx < max_x; cx++) {
    03763       TileIndex cur_tile = TileXY(cx, cy);
    03764       if (!IsTileType(cur_tile, MP_STATION)) continue;
    03765
    03766       Station *st = Station::GetByTile(cur_tile);
    03767       /* st can be NULL in case of waypoints */
    03768       if (st == NULL) continue;
    03769
    03770       if (_settings_game.station.modified_catchment) {
    03771         int rad = st->GetCatchmentRadius();
    03772         int rad_x = cx - x;
    03773         int rad_y = cy - y;
    03774
    03775         if (rad_x < -rad || rad_x >= rad + location.w) continue;
    03776         if (rad_y < -rad || rad_y >= rad + location.h) continue;
    03777       }
    03778
    03779       /* Insert the station in the set. This will fail if it has
    03780        * already been added.
    03781        */
    03782       stations->Include(st);
    03783     }
    03784   }
    03785 }
    03786
    03791 const StationList *StationFinder::GetStations()
    03792 {
    03793   if (this->tile != INVALID_TILE) {
    03794     FindStationsAroundTiles(*this, &this->stations);
    03795     this->tile = INVALID_TILE;
    03796   }
    03797   return &this->stations;
    03798 }
    03799
    03800 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
    03801 {
    03802   /* Return if nothing to do. Also the rounding below fails for 0. */
    03803   if (amount == 0) return 0;
    03804
    03805   Station *st1 = NULL;   // Station with best rating
    03806   Station *st2 = NULL;   // Second best station
    03807   uint best_rating1 = 0; // rating of st1
    03808   uint best_rating2 = 0; // rating of st2
    03809
    03810   for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
    03811     Station *st = *st_iter;
    03812
    03813     /* Is the station reserved exclusively for somebody else? */
    03814     if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
    03815
    03816     if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
    03817
    03818     if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
    03819
    03820     if (IsCargoInClass(type, CC_PASSENGERS)) {
    03821       if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
    03822     } else {
    03823       if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
    03824     }
    03825
    03826     /* This station can be used, add it to st1/st2 */
    03827     if (st1 == NULL || st->goods[type].rating >= best_rating1) {
    03828       st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
    03829     } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
    03830       st2 = st; best_rating2 = st->goods[type].rating;
    03831     }
    03832   }
    03833
    03834   /* no stations around at all? */
    03835   if (st1 == NULL) return 0;
    03836
    03837   /* From now we'll calculate with fractal cargo amounts.
    03838    * First determine how much cargo we really have. */
    03839   amount *= best_rating1 + 1;
    03840
    03841   if (st2 == NULL) {
    03842     /* only one station around */
    03843     return UpdateStationWaiting(st1, type, amount, source_type, source_id);
    03844   }
    03845
    03846   /* several stations around, the best two (highest rating) are in st1 and st2 */
    03847   assert(st1 != NULL);
    03848   assert(st2 != NULL);
    03849   assert(best_rating1 != 0 || best_rating2 != 0);
    03850
    03851   /* Then determine the amount the worst station gets. We do it this way as the
    03852    * best should get a bonus, which in this case is the rounding difference from
    03853    * this calculation. In reality that will mean the bonus will be pretty low.
    03854    * Nevertheless, the best station should always get the most cargo regardless
    03855    * of rounding issues. */
    03856   uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
    03857   assert(worst_cargo <= (amount - worst_cargo));
    03858
    03859   /* And then send the cargo to the stations! */
    03860   uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
    03861   /* These two UpdateStationWaiting's can't be in the statement as then the order
    03862    * of execution would be undefined and that could cause desyncs with callbacks. */
    03863   return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
    03864 }
    03865
    03866 void BuildOilRig(TileIndex tile)
    03867 {
    03868   if (!Station::CanAllocateItem()) {
    03869     DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
    03870     return;
    03871   }
    03872
    03873   Station *st = new Station(tile);
    03874   st->town = ClosestTownFromTile(tile, UINT_MAX);
    03875
    03876   st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
    03877
    03878   assert(IsTileType(tile, MP_INDUSTRY));
    03879   DeleteAnimatedTile(tile);
    03880   MakeOilrig(tile, st->index, GetWaterClass(tile));
    03881
    03882   st->owner = OWNER_NONE;
    03883   st->airport.type = AT_OILRIG;
    03884   st->airport.Add(tile);
    03885   st->dock_tile = tile;
    03886   st->facilities = FACIL_AIRPORT | FACIL_DOCK;
    03887   st->build_date = _date;
    03888
    03889   st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
    03890
    03891   st->UpdateVirtCoord();
    03892   UpdateStationAcceptance(st, false);
    03893   st->RecomputeIndustriesNear();
    03894 }
    03895
    03896 void DeleteOilRig(TileIndex tile)
    03897 {
    03898   Station *st = Station::GetByTile(tile);
    03899
    03900   MakeWaterKeepingClass(tile, OWNER_NONE);
    03901
    03902   st->dock_tile = INVALID_TILE;
    03903   st->airport.Clear();
    03904   st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
    03905   st->airport.flags = 0;
    03906
    03907   st->rect.AfterRemoveTile(st, tile);
    03908
    03909   st->UpdateVirtCoord();
    03910   st->RecomputeIndustriesNear();
    03911   if (!st->IsInUse()) delete st;
    03912 }
    03913
    03914 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
    03915 {
    03916   if (IsRoadStopTile(tile)) {
    03917     for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
    03918       /* Update all roadtypes, no matter if they are present */
    03919       if (GetRoadOwner(tile, rt) == old_owner) {
    03920         if (HasTileRoadType(tile, rt)) {
    03921           /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
    03922           Company::Get(old_owner)->infrastructure.road[rt] -= 2;
    03923           if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
    03924         }
    03925         SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
    03926       }
    03927     }
    03928   }
    03929
    03930   if (!IsTileOwner(tile, old_owner)) return;
    03931
    03932   if (new_owner != INVALID_OWNER) {
    03933     /* Update company infrastructure counts. Only do it here
    03934      * if the new owner is valid as otherwise the clear
    03935      * command will do it for us. No need to dirty windows
    03936      * here, we'll redraw the whole screen anyway.*/
    03937     Company *old_company = Company::Get(old_owner);
    03938     Company *new_company = Company::Get(new_owner);
    03939
    03940     /* Update counts for underlying infrastructure. */
    03941     switch (GetStationType(tile)) {
    03942       case STATION_RAIL:
    03943       case STATION_WAYPOINT:
    03944         if (!IsStationTileBlocked(tile)) {
    03945           old_company->infrastructure.rail[GetRailType(tile)]--;
    03946           new_company->infrastructure.rail[GetRailType(tile)]++;
    03947         }
    03948         break;
    03949
    03950       case STATION_BUS:
    03951       case STATION_TRUCK:
    03952         /* Road stops were already handled above. */
    03953         break;
    03954
    03955       case STATION_BUOY:
    03956       case STATION_DOCK:
    03957         if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
    03958           old_company->infrastructure.water--;
    03959           new_company->infrastructure.water++;
    03960         }
    03961         break;
    03962
    03963       default:
    03964         break;
    03965     }
    03966
    03967     /* Update station tile count. */
    03968     if (!IsBuoy(tile) && !IsAirport(tile)) {
    03969       old_company->infrastructure.station--;
    03970       new_company->infrastructure.station++;
    03971     }
    03972
    03973     /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
    03974     SetTileOwner(tile, new_owner);
    03975     InvalidateWindowClassesData(WC_STATION_LIST, 0);
    03976   } else {
    03977     if (IsDriveThroughStopTile(tile)) {
    03978       /* Remove the drive-through road stop */
    03979       DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
    03980       assert(IsTileType(tile, MP_ROAD));
    03981       /* Change owner of tile and all roadtypes */
    03982       ChangeTileOwner(tile, old_owner, new_owner);
    03983     } else {
    03984       DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
    03985       /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
    03986        * Update owner of buoy if it was not removed (was in orders).
    03987        * Do not update when owned by OWNER_WATER (sea and rivers). */
    03988       if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
    03989     }
    03990   }
    03991 }
    03992
    04001 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
    04002 {
    04003   /* Yeah... water can always remove stops, right? */
    04004   if (_current_company == OWNER_WATER) return true;
    04005
    04006   RoadTypes rts = GetRoadTypes(tile);
    04007   if (HasBit(rts, ROADTYPE_TRAM)) {
    04008     Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
    04009     if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
    04010   }
    04011   if (HasBit(rts, ROADTYPE_ROAD)) {
    04012     Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    04013     if (road_owner != OWNER_TOWN) {
    04014       if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
    04015     } else {
    04016       if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
    04017     }
    04018   }
    04019
    04020   return true;
    04021 }
    04022
    04029 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
    04030 {
    04031   if (flags & DC_AUTO) {
    04032     switch (GetStationType(tile)) {
    04033       default: break;
    04034       case STATION_RAIL:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
    04035       case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
    04036       case STATION_AIRPORT:  return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
    04037       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);
    04038       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);
    04039       case STATION_BUOY:     return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
    04040       case STATION_DOCK:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
    04041       case STATION_OILRIG:
    04042         SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
    04043         return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
    04044     }
    04045   }
    04046
    04047   switch (GetStationType(tile)) {
    04048     case STATION_RAIL:     return RemoveRailStation(tile, flags);
    04049     case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
    04050     case STATION_AIRPORT:  return RemoveAirport(tile, flags);
    04051     case STATION_TRUCK:
    04052       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
    04053         return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
    04054       }
    04055       return RemoveRoadStop(tile, flags);
    04056     case STATION_BUS:
    04057       if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
    04058         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
    04059       }
    04060       return RemoveRoadStop(tile, flags);
    04061     case STATION_BUOY:     return RemoveBuoy(tile, flags);
    04062     case STATION_DOCK:     return RemoveDock(tile, flags);
    04063     default: break;
    04064   }
    04065
    04066   return CMD_ERROR;
    04067 }
    04068
    04069 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
    04070 {
    04071   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
    04072     /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
    04073      *       TTDP does not call it.
    04074      */
    04075     if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
    04076       switch (GetStationType(tile)) {
    04077         case STATION_WAYPOINT:
    04078         case STATION_RAIL: {
    04079           DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
    04080           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
    04081           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
    04082           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    04083         }
    04084
    04085         case STATION_AIRPORT:
    04086           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    04087
    04088         case STATION_TRUCK:
    04089         case STATION_BUS: {
    04090           DiagDirection direction = GetRoadStopDir(tile);
    04091           if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
    04092           if (IsDriveThroughStopTile(tile)) {
    04093             if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
    04094           }
    04095           return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    04096         }
    04097
    04098         default: break;
    04099       }
    04100     }
    04101   }
    04102   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    04103 }
    04104
    04110 uint FlowStat::GetShare(StationID st) const
    04111 {
    04112   uint32 prev = 0;
    04113   for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
    04114     if (it->second == st) {
    04115       return it->first - prev;
    04116     } else {
    04117       prev = it->first;
    04118     }
    04119   }
    04120   return 0;
    04121 }
    04122
    04129 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
    04130 {
    04131   if (this->unrestricted == 0) return INVALID_STATION;
    04132   assert(!this->shares.empty());
    04133   SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
    04134   assert(it != this->shares.end() && it->first <= this->unrestricted);
    04135   if (it->second != excluded && it->second != excluded2) return it->second;
    04136
    04137   /* We've hit one of the excluded stations.
    04138    * Draw another share, from outside its range. */
    04139
    04140   uint end = it->first;
    04141   uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
    04142   uint interval = end - begin;
    04143   if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
    04144   uint new_max = this->unrestricted - interval;
    04145   uint rand = RandomRange(new_max);
    04146   SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
    04147       this->shares.upper_bound(rand + interval);
    04148   assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
    04149   if (it2->second != excluded && it2->second != excluded2) return it2->second;
    04150
    04151   /* We've hit the second excluded station.
    04152    * Same as before, only a bit more complicated. */
    04153
    04154   uint end2 = it2->first;
    04155   uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
    04156   uint interval2 = end2 - begin2;
    04157   if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
    04158   new_max -= interval2;
    04159   if (begin > begin2) {
    04160     Swap(begin, begin2);
    04161     Swap(end, end2);
    04162     Swap(interval, interval2);
    04163   }
    04164   rand = RandomRange(new_max);
    04165   SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
    04166   if (rand < begin) {
    04167     it3 = this->shares.upper_bound(rand);
    04168   } else if (rand < begin2 - interval) {
    04169     it3 = this->shares.upper_bound(rand + interval);
    04170   } else {
    04171     it3 = this->shares.upper_bound(rand + interval + interval2);
    04172   }
    04173   assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
    04174   return it3->second;
    04175 }
    04176
    04182 void FlowStat::Invalidate()
    04183 {
    04184   assert(!this->shares.empty());
    04185   SharesMap new_shares;
    04186   uint i = 0;
    04187   for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
    04188     new_shares[++i] = it->second;
    04189     if (it->first == this->unrestricted) this->unrestricted = i;
    04190   }
    04191   this->shares.swap(new_shares);
    04192   assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
    04193 }
    04194
    04201 void FlowStat::ChangeShare(StationID st, int flow)
    04202 {
    04203   /* We assert only before changing as afterwards the shares can actually
    04204    * be empty. In that case the whole flow stat must be deleted then. */
    04205   assert(!this->shares.empty());
    04206
    04207   uint removed_shares = 0;
    04208   uint added_shares = 0;
    04209   uint last_share = 0;
    04210   SharesMap new_shares;
    04211   for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
    04212     if (it->second == st) {
    04213       if (flow < 0) {
    04214         uint share = it->first - last_share;
    04215         if (flow == INT_MIN || (uint)(-flow) >= share) {
    04216           removed_shares += share;
    04217           if (it->first <= this->unrestricted) this->unrestricted -= share;
    04218           if (flow != INT_MIN) flow += share;
    04219           last_share = it->first;
    04220           continue; // remove the whole share
    04221         }
    04222         removed_shares += (uint)(-flow);
    04223       } else {
    04224         added_shares += (uint)(flow);
    04225       }
    04226       if (it->first <= this->unrestricted) this->unrestricted += flow;
    04227
    04228       /* If we don't continue above the whole flow has been added or
    04229        * removed. */
    04230       flow = 0;
    04231     }
    04232     new_shares[it->first + added_shares - removed_shares] = it->second;
    04233     last_share = it->first;
    04234   }
    04235   if (flow > 0) {
    04236     new_shares[last_share + (uint)flow] = st;
    04237     if (this->unrestricted < last_share) {
    04238       this->ReleaseShare(st);
    04239     } else {
    04240       this->unrestricted += flow;
    04241     }
    04242   }
    04243   this->shares.swap(new_shares);
    04244 }
    04245
    04251 void FlowStat::RestrictShare(StationID st)
    04252 {
    04253   assert(!this->shares.empty());
    04254   uint flow = 0;
    04255   uint last_share = 0;
    04256   SharesMap new_shares;
    04257   for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
    04258     if (flow == 0) {
    04259       if (it->first > this->unrestricted) return; // Not present or already restricted.
    04260       if (it->second == st) {
    04261         flow = it->first - last_share;
    04262         this->unrestricted -= flow;
    04263       } else {
    04264         new_shares[it->first] = it->second;
    04265       }
    04266     } else {
    04267       new_shares[it->first - flow] = it->second;
    04268     }
    04269     last_share = it->first;
    04270   }
    04271   if (flow == 0) return;
    04272   new_shares[last_share + flow] = st;
    04273   this->shares.swap(new_shares);
    04274   assert(!this->shares.empty());
    04275 }
    04276
    04282 void FlowStat::ReleaseShare(StationID st)
    04283 {
    04284   assert(!this->shares.empty());
    04285   uint flow = 0;
    04286   uint next_share = 0;
    04287   bool found = false;
    04288   for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
    04289     if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
    04290     if (found) {
    04291       flow = next_share - it->first;
    04292       this->unrestricted += flow;
    04293       break;
    04294     } else {
    04295       if (it->first == this->unrestricted) return; // !found -> Limit not hit.
    04296       if (it->second == st) found = true;
    04297     }
    04298     next_share = it->first;
    04299   }
    04300   if (flow == 0) return;
    04301   SharesMap new_shares;
    04302   new_shares[flow] = st;
    04303   for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
    04304     if (it->second != st) {
    04305       new_shares[flow + it->first] = it->second;
    04306     } else {
    04307       flow = 0;
    04308     }
    04309   }
    04310   this->shares.swap(new_shares);
    04311   assert(!this->shares.empty());
    04312 }
    04313
    04318 void FlowStat::ScaleToMonthly(uint runtime)
    04319 {
    04320   SharesMap new_shares;
    04321   uint share = 0;
    04322   for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
    04323     share = max(share + 1, i->first * 30 / runtime);
    04324     new_shares[share] = i->second;
    04325     if (this->unrestricted == i->first) this->unrestricted = share;
    04326   }
    04327   this->shares.swap(new_shares);
    04328 }
    04329
    04336 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
    04337 {
    04338   FlowStatMap::iterator origin_it = this->find(origin);
    04339   if (origin_it == this->end()) {
    04340     this->insert(std::make_pair(origin, FlowStat(via, flow)));
    04341   } else {
    04342     origin_it->second.ChangeShare(via, flow);
    04343     assert(!origin_it->second.GetShares()->empty());
    04344   }
    04345 }
    04346
    04355 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
    04356 {
    04357   FlowStatMap::iterator prev_it = this->find(origin);
    04358   if (prev_it == this->end()) {
    04359     FlowStat fs(via, flow);
    04360     fs.AppendShare(INVALID_STATION, flow);
    04361     this->insert(std::make_pair(origin, fs));
    04362   } else {
    04363     prev_it->second.ChangeShare(via, flow);
    04364     prev_it->second.ChangeShare(INVALID_STATION, flow);
    04365     assert(!prev_it->second.GetShares()->empty());
    04366   }
    04367 }
    04368
    04373 void FlowStatMap::FinalizeLocalConsumption(StationID self)
    04374 {
    04375   for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
    04376     FlowStat &fs = i->second;
    04377     uint local = fs.GetShare(INVALID_STATION);
    04378     if (local > INT_MAX) { // make sure it fits in an int
    04379       fs.ChangeShare(self, -INT_MAX);
    04380       fs.ChangeShare(INVALID_STATION, -INT_MAX);
    04381       local -= INT_MAX;
    04382     }
    04383     fs.ChangeShare(self, -(int)local);
    04384     fs.ChangeShare(INVALID_STATION, -(int)local);
    04385
    04386     /* If the local share is used up there must be a share for some
    04387      * remote station. */
    04388     assert(!fs.GetShares()->empty());
    04389   }
    04390 }
    04391
    04398 StationIDStack FlowStatMap::DeleteFlows(StationID via)
    04399 {
    04400   StationIDStack ret;
    04401   for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
    04402     FlowStat &s_flows = f_it->second;
    04403     s_flows.ChangeShare(via, INT_MIN);
    04404     if (s_flows.GetShares()->empty()) {
    04405       ret.Push(f_it->first);
    04406       this->erase(f_it++);
    04407     } else {
    04408       ++f_it;
    04409     }
    04410   }
    04411   return ret;
    04412 }
    04413
    04418 void FlowStatMap::RestrictFlows(StationID via)
    04419 {
    04420   for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
    04421     it->second.RestrictShare(via);
    04422   }
    04423 }
    04424
    04429 void FlowStatMap::ReleaseFlows(StationID via)
    04430 {
    04431   for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
    04432     it->second.ReleaseShare(via);
    04433   }
    04434 }
    04435
    04441 uint GoodsEntry::GetSumFlowVia(StationID via) const
    04442 {
    04443   uint ret = 0;
    04444   for (FlowStatMap::const_iterator i = this->flows.begin(); i != this->flows.end(); ++i) {
    04445     ret += i->second.GetShare(via);
    04446   }
    04447   return ret;
    04448 }
    04449
    04450 extern const TileTypeProcs _tile_type_station_procs = {
    04451   DrawTile_Station,           // draw_tile_proc
    04452   GetSlopePixelZ_Station,     // get_slope_z_proc
    04453   ClearTile_Station,          // clear_tile_proc
    04454   NULL,                       // add_accepted_cargo_proc
    04455   GetTileDesc_Station,        // get_tile_desc_proc
    04456   GetTileTrackStatus_Station, // get_tile_track_status_proc
    04457   ClickTile_Station,          // click_tile_proc
    04458   AnimateTile_Station,        // animate_tile_proc
    04459   TileLoop_Station,           // tile_loop_proc
    04460   ChangeTileOwner_Station,    // change_tile_owner_proc
    04461   NULL,                       // add_produced_cargo_proc
    04462   VehicleEnter_Station,       // vehicle_enter_tile_proc
    04463   GetFoundation_Station,      // get_foundation_proc
    04464   TerraformTile_Station,      // terraform_tile_proc
    04465 };