station.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 "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 #include "cargodest_func.h"
00029 
00030 #include "table/strings.h"
00031 
00033 StationPool _station_pool("Station");
00034 INSTANTIATE_POOL_METHODS(Station)
00035 
00036 BaseStation::~BaseStation()
00037 {
00038   free(this->name);
00039   free(this->speclist);
00040 
00041   if (CleaningPool()) return;
00042 
00043   Owner owner = this->owner;
00044   if (!Company::IsValidID(owner)) owner = _local_company;
00045   if (!Company::IsValidID(owner)) return; // Spectators
00046   DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->index).Pack());
00047   DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->index).Pack());
00048   DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->index).Pack());
00049   DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->index).Pack());
00050 
00051   this->sign.MarkDirty();
00052 }
00053 
00054 Station::Station(TileIndex tile) :
00055   SpecializedStation<Station, false>(tile),
00056   bus_station(INVALID_TILE, 0, 0),
00057   truck_station(INVALID_TILE, 0, 0),
00058   dock_tile(INVALID_TILE),
00059   indtype(IT_INVALID),
00060   time_since_load(255),
00061   time_since_unload(255),
00062   last_vehicle_type(VEH_INVALID)
00063 {
00064   /* this->random_bits is set in Station::AddFacility() */
00065 }
00066 
00073 Station::~Station()
00074 {
00075   if (CleaningPool()) {
00076     for (CargoID c = 0; c < NUM_CARGO; c++) {
00077       this->goods[c].cargo.OnCleanPool();
00078     }
00079     return;
00080   }
00081 
00082   while (!this->loading_vehicles.empty()) {
00083     this->loading_vehicles.front()->LeaveStation();
00084   }
00085 
00086   Aircraft *a;
00087   FOR_ALL_AIRCRAFT(a) {
00088     if (!a->IsNormalAircraft()) continue;
00089     if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
00090   }
00091 
00092   Vehicle *v;
00093   FOR_ALL_VEHICLES(v) {
00094     /* Forget about this station if this station is removed */
00095     if (v->last_station_visited == this->index) {
00096       v->last_station_visited = INVALID_STATION;
00097     }
00098     if (v->last_station_loaded == this->index) {
00099       v->last_station_loaded = INVALID_STATION;
00100     }
00101   }
00102 
00103   InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
00104 
00105   DeleteWindowById(WC_STATION_VIEW, index);
00106 
00107   /* Now delete all orders that go to the station */
00108   RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
00109 
00110   /* Remove all news items */
00111   DeleteStationNews(this->index);
00112 
00113   for (CargoID c = 0; c < NUM_CARGO; c++) {
00114     this->goods[c].cargo.Truncate(0);
00115   }
00116 
00117   CargoPacket::InvalidateAllFrom(this->index);
00118   InvalidateStationRouteLinks(this);
00119 }
00120 
00121 
00127 void BaseStation::PostDestructor(size_t index)
00128 {
00129   InvalidateWindowData(WC_SELECT_STATION, 0, 0);
00130 }
00131 
00137 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
00138 {
00139   RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
00140 
00141   for (; rs != NULL; rs = rs->next) {
00142     /* The vehicle cannot go to this roadstop (different roadtype) */
00143     if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
00144     /* The vehicle is articulated and can therefor not go the a standard road stop */
00145     if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
00146 
00147     /* The vehicle can actually go to this road stop. So, return it! */
00148     break;
00149   }
00150 
00151   return rs;
00152 }
00153 
00158 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
00159 {
00160   if (this->facilities == FACIL_NONE) {
00161     this->xy = facil_xy;
00162     this->random_bits = Random();
00163   }
00164   this->facilities |= new_facility_bit;
00165   this->owner = _current_company;
00166   this->build_date = _date;
00167 }
00168 
00174 void Station::MarkTilesDirty(bool cargo_change) const
00175 {
00176   TileIndex tile = this->train_station.tile;
00177   int w, h;
00178 
00179   if (tile == INVALID_TILE) return;
00180 
00181   /* cargo_change is set if we're refreshing the tiles due to cargo moving
00182    * around. */
00183   if (cargo_change) {
00184     /* Don't waste time updating if there are no custom station graphics
00185      * that might change. Even if there are custom graphics, they might
00186      * not change. Unfortunately we have no way of telling. */
00187     if (this->num_specs == 0) return;
00188   }
00189 
00190   for (h = 0; h < train_station.h; h++) {
00191     for (w = 0; w < train_station.w; w++) {
00192       if (this->TileBelongsToRailStation(tile)) {
00193         MarkTileDirtyByTile(tile);
00194       }
00195       tile += TileDiffXY(1, 0);
00196     }
00197     tile += TileDiffXY(-w, 1);
00198   }
00199 }
00200 
00201 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
00202 {
00203   assert(this->TileBelongsToRailStation(tile));
00204 
00205   TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00206 
00207   TileIndex t = tile;
00208   uint len = 0;
00209   do {
00210     t -= delta;
00211     len++;
00212   } while (IsCompatibleTrainStationTile(t, tile));
00213 
00214   t = tile;
00215   do {
00216     t += delta;
00217     len++;
00218   } while (IsCompatibleTrainStationTile(t, tile));
00219 
00220   return len - 1;
00221 }
00222 
00223 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
00224 {
00225   TileIndex start_tile = tile;
00226   uint length = 0;
00227   assert(IsRailStationTile(tile));
00228   assert(dir < DIAGDIR_END);
00229 
00230   do {
00231     length++;
00232     tile += TileOffsByDiagDir(dir);
00233   } while (IsCompatibleTrainStationTile(tile, start_tile));
00234 
00235   return length;
00236 }
00237 
00242 uint Station::GetCatchmentRadius() const
00243 {
00244   uint ret = CA_NONE;
00245 
00246   if (_settings_game.station.modified_catchment) {
00247     if (this->bus_stops          != NULL)         ret = max<uint>(ret, CA_BUS);
00248     if (this->truck_stops        != NULL)         ret = max<uint>(ret, CA_TRUCK);
00249     if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
00250     if (this->dock_tile          != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
00251     if (this->airport.tile       != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
00252   } else {
00253     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) {
00254       ret = CA_UNMODIFIED;
00255     }
00256   }
00257 
00258   return ret;
00259 }
00260 
00265 Rect Station::GetCatchmentRect() const
00266 {
00267   assert(!this->rect.IsEmpty());
00268 
00269   /* Compute acceptance rectangle */
00270   int catchment_radius = this->GetCatchmentRadius();
00271 
00272   Rect ret = {
00273     max<int>(this->rect.left   - catchment_radius, 0),
00274     max<int>(this->rect.top    - catchment_radius, 0),
00275     min<int>(this->rect.right  + catchment_radius, MapMaxX()),
00276     min<int>(this->rect.bottom + catchment_radius, MapMaxY())
00277   };
00278 
00279   return ret;
00280 }
00281 
00283 struct RectAndIndustryVector {
00284   Rect rect;                       
00285   IndustryVector *industries_near; 
00286 };
00287 
00296 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
00297 {
00298   /* Only process industry tiles */
00299   if (!IsTileType(ind_tile, MP_INDUSTRY)) return false;
00300 
00301   RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
00302   Industry *ind = Industry::GetByTile(ind_tile);
00303 
00304   /* Don't check further if this industry is already in the list */
00305   if (riv->industries_near->Contains(ind)) return false;
00306 
00307   /* Only process tiles in the station acceptance rectangle */
00308   int x = TileX(ind_tile);
00309   int y = TileY(ind_tile);
00310   if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
00311 
00312   /* Include only industries that can accept cargo */
00313   uint cargo_index;
00314   for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
00315     if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
00316   }
00317   if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
00318 
00319   *riv->industries_near->Append() = ind;
00320 
00321   return false;
00322 }
00323 
00328 void Station::RecomputeIndustriesNear()
00329 {
00330   this->industries_near.Clear();
00331   if (this->rect.IsEmpty()) return;
00332 
00333   RectAndIndustryVector riv = {
00334     this->GetCatchmentRect(),
00335     &this->industries_near
00336   };
00337 
00338   /* Compute maximum extent of acceptance rectangle wrt. station sign */
00339   TileIndex start_tile = this->xy;
00340   uint max_radius = max(
00341     max(DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.bottom))),
00342     max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
00343   );
00344 
00345   CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
00346 }
00347 
00351 /* static */ void Station::RecomputeIndustriesNearForAll()
00352 {
00353   Station *st;
00354   FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
00355 }
00356 
00357 /************************************************************************/
00358 /*                     StationRect implementation                       */
00359 /************************************************************************/
00360 
00361 StationRect::StationRect()
00362 {
00363   this->MakeEmpty();
00364 }
00365 
00366 void StationRect::MakeEmpty()
00367 {
00368   this->left = this->top = this->right = this->bottom = 0;
00369 }
00370 
00380 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
00381 {
00382   return this->left - distance <= x && x <= this->right + distance &&
00383       this->top - distance <= y && y <= this->bottom + distance;
00384 }
00385 
00392 bool StationRect::AreaInExtendedRect(const TileArea& area, int distance) const
00393 {
00394   int area_left = TileX(area.tile);
00395   int area_right = area_left + area.w;
00396   int area_top = TileY(area.tile);
00397   int area_bottom = area_top + area.h;
00398 
00399   return this->left - distance <= area_right && area_left <= this->right + distance &&
00400       this->top - distance <= area_bottom && area_top <= this->bottom + distance;
00401 }
00402 
00403 bool StationRect::IsEmpty() const
00404 {
00405   return this->left == 0 || this->left > this->right || this->top > this->bottom;
00406 }
00407 
00408 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
00409 {
00410   int x = TileX(tile);
00411   int y = TileY(tile);
00412   if (this->IsEmpty()) {
00413     /* we are adding the first station tile */
00414     if (mode != ADD_TEST) {
00415       this->left = this->right = x;
00416       this->top = this->bottom = y;
00417     }
00418   } else if (!this->PtInExtendedRect(x, y)) {
00419     /* current rect is not empty and new point is outside this rect
00420      * make new spread-out rectangle */
00421     Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
00422 
00423     /* check new rect dimensions against preset max */
00424     int w = new_rect.right - new_rect.left + 1;
00425     int h = new_rect.bottom - new_rect.top + 1;
00426     if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
00427       assert(mode != ADD_TRY);
00428       return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00429     }
00430 
00431     /* spread-out ok, return true */
00432     if (mode != ADD_TEST) {
00433       /* we should update the station rect */
00434       *this = new_rect;
00435     }
00436   } else {
00437     ; // new point is inside the rect, we don't need to do anything
00438   }
00439   return CommandCost();
00440 }
00441 
00442 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
00443 {
00444   if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
00445     /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
00446     CommandCost ret = this->BeforeAddTile(tile, mode);
00447     if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
00448     return ret;
00449   }
00450   return CommandCost();
00451 }
00452 
00462 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
00463 {
00464   TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
00465   TILE_AREA_LOOP(tile, ta) {
00466     if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
00467   }
00468 
00469   return false;
00470 }
00471 
00472 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
00473 {
00474   int x = TileX(tile);
00475   int y = TileY(tile);
00476 
00477   /* look if removed tile was on the bounding rect edge
00478    * and try to reduce the rect by this edge
00479    * do it until we have empty rect or nothing to do */
00480   for (;;) {
00481     /* check if removed tile is on rect edge */
00482     bool left_edge = (x == this->left);
00483     bool right_edge = (x == this->right);
00484     bool top_edge = (y == this->top);
00485     bool bottom_edge = (y == this->bottom);
00486 
00487     /* can we reduce the rect in either direction? */
00488     bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
00489     bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
00490     if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
00491 
00492     if (reduce_x) {
00493       /* reduce horizontally */
00494       if (left_edge) {
00495         /* move left edge right */
00496         this->left = x = x + 1;
00497       } else {
00498         /* move right edge left */
00499         this->right = x = x - 1;
00500       }
00501     }
00502     if (reduce_y) {
00503       /* reduce vertically */
00504       if (top_edge) {
00505         /* move top edge down */
00506         this->top = y = y + 1;
00507       } else {
00508         /* move bottom edge up */
00509         this->bottom = y = y - 1;
00510       }
00511     }
00512 
00513     if (left > right || top > bottom) {
00514       /* can't continue, if the remaining rectangle is empty */
00515       this->MakeEmpty();
00516       return true; // empty remaining rect
00517     }
00518   }
00519   return false; // non-empty remaining rect
00520 }
00521 
00522 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
00523 {
00524   assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
00525   assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
00526 
00527   bool empty = this->AfterRemoveTile(st, ta.tile);
00528   if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
00529   return empty;
00530 }
00531 
00532 StationRect& StationRect::operator = (const Rect &src)
00533 {
00534   this->left = src.left;
00535   this->top = src.top;
00536   this->right = src.right;
00537   this->bottom = src.bottom;
00538   return *this;
00539 }

Generated on Mon May 9 05:19:00 2011 for OpenTTD by  doxygen 1.6.1