station.cpp

Go to the documentation of this file.
00001 /* $Id: station.cpp 23257 2011-11-18 21:15:09Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "company_func.h"
00014 #include "company_base.h"
00015 #include "roadveh.h"
00016 #include "viewport_func.h"
00017 #include "window_func.h"
00018 #include "date_func.h"
00019 #include "command_func.h"
00020 #include "news_func.h"
00021 #include "aircraft.h"
00022 #include "vehiclelist.h"
00023 #include "core/pool_func.hpp"
00024 #include "station_base.h"
00025 #include "roadstop_base.h"
00026 #include "industry.h"
00027 #include "core/random_func.hpp"
00028 
00029 #include "table/strings.h"
00030 
00031 StationPool _station_pool("Station");
00032 INSTANTIATE_POOL_METHODS(Station)
00033 
00034 BaseStation::~BaseStation()
00035 {
00036   free(this->name);
00037   free(this->speclist);
00038 
00039   if (CleaningPool()) return;
00040 
00041   Owner owner = this->owner;
00042   if (!Company::IsValidID(owner)) owner = _local_company;
00043   if (!Company::IsValidID(owner)) return; // Spectators
00044   DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->index).Pack());
00045   DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->index).Pack());
00046   DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->index).Pack());
00047   DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->index).Pack());
00048 
00049   this->sign.MarkDirty();
00050 }
00051 
00052 Station::Station(TileIndex tile) :
00053   SpecializedStation<Station, false>(tile),
00054   bus_station(INVALID_TILE, 0, 0),
00055   truck_station(INVALID_TILE, 0, 0),
00056   dock_tile(INVALID_TILE),
00057   indtype(IT_INVALID),
00058   time_since_load(255),
00059   time_since_unload(255),
00060   last_vehicle_type(VEH_INVALID)
00061 {
00062   /* this->random_bits is set in Station::AddFacility() */
00063 }
00064 
00071 Station::~Station()
00072 {
00073   if (CleaningPool()) return;
00074 
00075   while (!this->loading_vehicles.empty()) {
00076     this->loading_vehicles.front()->LeaveStation();
00077   }
00078 
00079   Aircraft *a;
00080   FOR_ALL_AIRCRAFT(a) {
00081     if (!a->IsNormalAircraft()) continue;
00082     if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
00083   }
00084 
00085   Vehicle *v;
00086   FOR_ALL_VEHICLES(v) {
00087     /* Forget about this station if this station is removed */
00088     if (v->last_station_visited == this->index) {
00089       v->last_station_visited = INVALID_STATION;
00090     }
00091   }
00092 
00093   if (this->owner == OWNER_NONE) {
00094     /* Invalidate all in case of oil rigs. */
00095     InvalidateWindowClassesData(WC_STATION_LIST, 0);
00096   } else {
00097     InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
00098   }
00099 
00100   DeleteWindowById(WC_STATION_VIEW, index);
00101 
00102   /* Now delete all orders that go to the station */
00103   RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
00104 
00105   /* Remove all news items */
00106   DeleteStationNews(this->index);
00107 
00108   for (CargoID c = 0; c < NUM_CARGO; c++) {
00109     this->goods[c].cargo.Truncate(0);
00110   }
00111 
00112   CargoPacket::InvalidateAllFrom(this->index);
00113 }
00114 
00115 
00121 void BaseStation::PostDestructor(size_t index)
00122 {
00123   InvalidateWindowData(WC_SELECT_STATION, 0, 0);
00124 }
00125 
00131 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
00132 {
00133   RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
00134 
00135   for (; rs != NULL; rs = rs->next) {
00136     /* The vehicle cannot go to this roadstop (different roadtype) */
00137     if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
00138     /* The vehicle is articulated and can therefor not go the a standard road stop */
00139     if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
00140 
00141     /* The vehicle can actually go to this road stop. So, return it! */
00142     break;
00143   }
00144 
00145   return rs;
00146 }
00147 
00152 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
00153 {
00154   if (this->facilities == FACIL_NONE) {
00155     this->xy = facil_xy;
00156     this->random_bits = Random();
00157   }
00158   this->facilities |= new_facility_bit;
00159   this->owner = _current_company;
00160   this->build_date = _date;
00161 }
00162 
00168 void Station::MarkTilesDirty(bool cargo_change) const
00169 {
00170   TileIndex tile = this->train_station.tile;
00171   int w, h;
00172 
00173   if (tile == INVALID_TILE) return;
00174 
00175   /* cargo_change is set if we're refreshing the tiles due to cargo moving
00176    * around. */
00177   if (cargo_change) {
00178     /* Don't waste time updating if there are no custom station graphics
00179      * that might change. Even if there are custom graphics, they might
00180      * not change. Unfortunately we have no way of telling. */
00181     if (this->num_specs == 0) return;
00182   }
00183 
00184   for (h = 0; h < train_station.h; h++) {
00185     for (w = 0; w < train_station.w; w++) {
00186       if (this->TileBelongsToRailStation(tile)) {
00187         MarkTileDirtyByTile(tile);
00188       }
00189       tile += TileDiffXY(1, 0);
00190     }
00191     tile += TileDiffXY(-w, 1);
00192   }
00193 }
00194 
00195 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
00196 {
00197   assert(this->TileBelongsToRailStation(tile));
00198 
00199   TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00200 
00201   TileIndex t = tile;
00202   uint len = 0;
00203   do {
00204     t -= delta;
00205     len++;
00206   } while (IsCompatibleTrainStationTile(t, tile));
00207 
00208   t = tile;
00209   do {
00210     t += delta;
00211     len++;
00212   } while (IsCompatibleTrainStationTile(t, tile));
00213 
00214   return len - 1;
00215 }
00216 
00217 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
00218 {
00219   TileIndex start_tile = tile;
00220   uint length = 0;
00221   assert(IsRailStationTile(tile));
00222   assert(dir < DIAGDIR_END);
00223 
00224   do {
00225     length++;
00226     tile += TileOffsByDiagDir(dir);
00227   } while (IsCompatibleTrainStationTile(tile, start_tile));
00228 
00229   return length;
00230 }
00231 
00236 uint Station::GetCatchmentRadius() const
00237 {
00238   uint ret = CA_NONE;
00239 
00240   if (_settings_game.station.modified_catchment) {
00241     if (this->bus_stops          != NULL)         ret = max<uint>(ret, CA_BUS);
00242     if (this->truck_stops        != NULL)         ret = max<uint>(ret, CA_TRUCK);
00243     if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
00244     if (this->dock_tile          != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
00245     if (this->airport.tile       != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
00246   } else {
00247     if (this->bus_stops != NULL || this->truck_stops != NULL || this->train_station.tile != INVALID_TILE || this->dock_tile != INVALID_TILE || this->airport.tile != INVALID_TILE) {
00248       ret = CA_UNMODIFIED;
00249     }
00250   }
00251 
00252   return ret;
00253 }
00254 
00259 Rect Station::GetCatchmentRect() const
00260 {
00261   assert(!this->rect.IsEmpty());
00262 
00263   /* Compute acceptance rectangle */
00264   int catchment_radius = this->GetCatchmentRadius();
00265 
00266   Rect ret = {
00267     max<int>(this->rect.left   - catchment_radius, 0),
00268     max<int>(this->rect.top    - catchment_radius, 0),
00269     min<int>(this->rect.right  + catchment_radius, MapMaxX()),
00270     min<int>(this->rect.bottom + catchment_radius, MapMaxY())
00271   };
00272 
00273   return ret;
00274 }
00275 
00277 struct RectAndIndustryVector {
00278   Rect rect;
00279   IndustryVector *industries_near;
00280 };
00281 
00290 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
00291 {
00292   /* Only process industry tiles */
00293   if (!IsTileType(ind_tile, MP_INDUSTRY)) return false;
00294 
00295   RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
00296   Industry *ind = Industry::GetByTile(ind_tile);
00297 
00298   /* Don't check further if this industry is already in the list */
00299   if (riv->industries_near->Contains(ind)) return false;
00300 
00301   /* Only process tiles in the station acceptance rectangle */
00302   int x = TileX(ind_tile);
00303   int y = TileY(ind_tile);
00304   if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
00305 
00306   /* Include only industries that can accept cargo */
00307   uint cargo_index;
00308   for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
00309     if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
00310   }
00311   if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
00312 
00313   *riv->industries_near->Append() = ind;
00314 
00315   return false;
00316 }
00317 
00322 void Station::RecomputeIndustriesNear()
00323 {
00324   this->industries_near.Clear();
00325   if (this->rect.IsEmpty()) return;
00326 
00327   RectAndIndustryVector riv = {
00328     this->GetCatchmentRect(),
00329     &this->industries_near
00330   };
00331 
00332   /* Compute maximum extent of acceptance rectangle wrt. station sign */
00333   TileIndex start_tile = this->xy;
00334   uint max_radius = max(
00335     max(DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.bottom))),
00336     max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
00337   );
00338 
00339   CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
00340 }
00341 
00345 /* static */ void Station::RecomputeIndustriesNearForAll()
00346 {
00347   Station *st;
00348   FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
00349 }
00350 
00351 /************************************************************************/
00352 /*                     StationRect implementation                       */
00353 /************************************************************************/
00354 
00355 StationRect::StationRect()
00356 {
00357   this->MakeEmpty();
00358 }
00359 
00360 void StationRect::MakeEmpty()
00361 {
00362   this->left = this->top = this->right = this->bottom = 0;
00363 }
00364 
00374 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
00375 {
00376   return this->left - distance <= x && x <= this->right + distance &&
00377       this->top - distance <= y && y <= this->bottom + distance;
00378 }
00379 
00380 bool StationRect::IsEmpty() const
00381 {
00382   return this->left == 0 || this->left > this->right || this->top > this->bottom;
00383 }
00384 
00385 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
00386 {
00387   int x = TileX(tile);
00388   int y = TileY(tile);
00389   if (this->IsEmpty()) {
00390     /* we are adding the first station tile */
00391     if (mode != ADD_TEST) {
00392       this->left = this->right = x;
00393       this->top = this->bottom = y;
00394     }
00395   } else if (!this->PtInExtendedRect(x, y)) {
00396     /* current rect is not empty and new point is outside this rect
00397      * make new spread-out rectangle */
00398     Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
00399 
00400     /* check new rect dimensions against preset max */
00401     int w = new_rect.right - new_rect.left + 1;
00402     int h = new_rect.bottom - new_rect.top + 1;
00403     if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
00404       assert(mode != ADD_TRY);
00405       return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00406     }
00407 
00408     /* spread-out ok, return true */
00409     if (mode != ADD_TEST) {
00410       /* we should update the station rect */
00411       *this = new_rect;
00412     }
00413   } else {
00414     ; // new point is inside the rect, we don't need to do anything
00415   }
00416   return CommandCost();
00417 }
00418 
00419 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
00420 {
00421   if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
00422     /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
00423     CommandCost ret = this->BeforeAddTile(tile, mode);
00424     if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
00425     return ret;
00426   }
00427   return CommandCost();
00428 }
00429 
00439 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
00440 {
00441   TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
00442   TILE_AREA_LOOP(tile, ta) {
00443     if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
00444   }
00445 
00446   return false;
00447 }
00448 
00449 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
00450 {
00451   int x = TileX(tile);
00452   int y = TileY(tile);
00453 
00454   /* look if removed tile was on the bounding rect edge
00455    * and try to reduce the rect by this edge
00456    * do it until we have empty rect or nothing to do */
00457   for (;;) {
00458     /* check if removed tile is on rect edge */
00459     bool left_edge = (x == this->left);
00460     bool right_edge = (x == this->right);
00461     bool top_edge = (y == this->top);
00462     bool bottom_edge = (y == this->bottom);
00463 
00464     /* can we reduce the rect in either direction? */
00465     bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
00466     bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
00467     if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
00468 
00469     if (reduce_x) {
00470       /* reduce horizontally */
00471       if (left_edge) {
00472         /* move left edge right */
00473         this->left = x = x + 1;
00474       } else {
00475         /* move right edge left */
00476         this->right = x = x - 1;
00477       }
00478     }
00479     if (reduce_y) {
00480       /* reduce vertically */
00481       if (top_edge) {
00482         /* move top edge down */
00483         this->top = y = y + 1;
00484       } else {
00485         /* move bottom edge up */
00486         this->bottom = y = y - 1;
00487       }
00488     }
00489 
00490     if (left > right || top > bottom) {
00491       /* can't continue, if the remaining rectangle is empty */
00492       this->MakeEmpty();
00493       return true; // empty remaining rect
00494     }
00495   }
00496   return false; // non-empty remaining rect
00497 }
00498 
00499 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
00500 {
00501   assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
00502   assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
00503 
00504   bool empty = this->AfterRemoveTile(st, ta.tile);
00505   if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
00506   return empty;
00507 }
00508 
00509 StationRect& StationRect::operator = (const Rect &src)
00510 {
00511   this->left = src.left;
00512   this->top = src.top;
00513   this->right = src.right;
00514   this->bottom = src.bottom;
00515   return *this;
00516 }
00517 
00518 
00519 void InitializeStations()
00520 {
00521   _station_pool.CleanPool();
00522 }