# station_cmd.cpp

Go to the documentation of this file.

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