station.cpp

Go to the documentation of this file.
00001 /* $Id: station.cpp 26286 2014-01-29 19:55:29Z fonsinchen $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "company_func.h"
00014 #include "company_base.h"
00015 #include "roadveh.h"
00016 #include "viewport_func.h"
00017 #include "date_func.h"
00018 #include "command_func.h"
00019 #include "news_func.h"
00020 #include "aircraft.h"
00021 #include "vehiclelist.h"
00022 #include "core/pool_func.hpp"
00023 #include "station_base.h"
00024 #include "roadstop_base.h"
00025 #include "industry.h"
00026 #include "core/random_func.hpp"
00027 #include "linkgraph/linkgraph.h"
00028 #include "linkgraph/linkgraphschedule.h"
00029 
00030 #include "table/strings.h"
00031 
00033 StationPool _station_pool("Station");
00034 INSTANTIATE_POOL_METHODS(Station)
00035 
00036 typedef StationIDStack::SmallStackPool StationIDStackPool;
00037 template<> StationIDStackPool StationIDStack::_pool("StationIDStack");
00038 INSTANTIATE_POOL_METHODS(StationIDStack)
00039 
00040 BaseStation::~BaseStation()
00041 {
00042   free(this->name);
00043   free(this->speclist);
00044 
00045   if (CleaningPool()) return;
00046 
00047   Owner owner = this->owner;
00048   if (!Company::IsValidID(owner)) owner = _local_company;
00049   if (!Company::IsValidID(owner)) return; // Spectators
00050   DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->index).Pack());
00051   DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->index).Pack());
00052   DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->index).Pack());
00053   DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->index).Pack());
00054 
00055   this->sign.MarkDirty();
00056 }
00057 
00058 Station::Station(TileIndex tile) :
00059   SpecializedStation<Station, false>(tile),
00060   bus_station(INVALID_TILE, 0, 0),
00061   truck_station(INVALID_TILE, 0, 0),
00062   dock_tile(INVALID_TILE),
00063   indtype(IT_INVALID),
00064   time_since_load(255),
00065   time_since_unload(255),
00066   last_vehicle_type(VEH_INVALID)
00067 {
00068   /* this->random_bits is set in Station::AddFacility() */
00069 }
00070 
00078 Station::~Station()
00079 {
00080   if (CleaningPool()) {
00081     for (CargoID c = 0; c < NUM_CARGO; c++) {
00082       this->goods[c].cargo.OnCleanPool();
00083     }
00084     return;
00085   }
00086 
00087   while (!this->loading_vehicles.empty()) {
00088     this->loading_vehicles.front()->LeaveStation();
00089   }
00090 
00091   Aircraft *a;
00092   FOR_ALL_AIRCRAFT(a) {
00093     if (!a->IsNormalAircraft()) continue;
00094     if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
00095   }
00096 
00097   for (CargoID c = 0; c < NUM_CARGO; ++c) {
00098     LinkGraph *lg = LinkGraph::GetIfValid(this->goods[c].link_graph);
00099     if (lg == NULL) continue;
00100 
00101     for (NodeID node = 0; node < lg->Size(); ++node) {
00102       Station *st = Station::Get((*lg)[node].Station());
00103       st->goods[c].flows.erase(this->index);
00104       if ((*lg)[node][this->goods[c].node].LastUpdate() != INVALID_DATE) {
00105         st->goods[c].flows.DeleteFlows(this->index);
00106         RerouteCargo(st, c, this->index, st->index);
00107       }
00108     }
00109     lg->RemoveNode(this->goods[c].node);
00110     if (lg->Size() == 0) {
00111       LinkGraphSchedule::Instance()->Unqueue(lg);
00112       delete lg;
00113     }
00114   }
00115 
00116   Vehicle *v;
00117   FOR_ALL_VEHICLES(v) {
00118     /* Forget about this station if this station is removed */
00119     if (v->last_station_visited == this->index) {
00120       v->last_station_visited = INVALID_STATION;
00121     }
00122     if (v->last_loading_station == this->index) {
00123       v->last_loading_station = INVALID_STATION;
00124     }
00125   }
00126 
00127   /* Clear the persistent storage. */
00128   delete this->airport.psa;
00129 
00130   if (this->owner == OWNER_NONE) {
00131     /* Invalidate all in case of oil rigs. */
00132     InvalidateWindowClassesData(WC_STATION_LIST, 0);
00133   } else {
00134     InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
00135   }
00136 
00137   DeleteWindowById(WC_STATION_VIEW, index);
00138 
00139   /* Now delete all orders that go to the station */
00140   RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
00141 
00142   /* Remove all news items */
00143   DeleteStationNews(this->index);
00144 
00145   for (CargoID c = 0; c < NUM_CARGO; c++) {
00146     this->goods[c].cargo.Truncate();
00147   }
00148 
00149   CargoPacket::InvalidateAllFrom(this->index);
00150 }
00151 
00152 
00158 void BaseStation::PostDestructor(size_t index)
00159 {
00160   InvalidateWindowData(WC_SELECT_STATION, 0, 0);
00161 }
00162 
00168 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
00169 {
00170   RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
00171 
00172   for (; rs != NULL; rs = rs->next) {
00173     /* The vehicle cannot go to this roadstop (different roadtype) */
00174     if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
00175     /* The vehicle is articulated and can therefore not go to a standard road stop. */
00176     if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
00177 
00178     /* The vehicle can actually go to this road stop. So, return it! */
00179     break;
00180   }
00181 
00182   return rs;
00183 }
00184 
00189 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
00190 {
00191   if (this->facilities == FACIL_NONE) {
00192     this->xy = facil_xy;
00193     this->random_bits = Random();
00194   }
00195   this->facilities |= new_facility_bit;
00196   this->owner = _current_company;
00197   this->build_date = _date;
00198 }
00199 
00205 void Station::MarkTilesDirty(bool cargo_change) const
00206 {
00207   TileIndex tile = this->train_station.tile;
00208   int w, h;
00209 
00210   if (tile == INVALID_TILE) return;
00211 
00212   /* cargo_change is set if we're refreshing the tiles due to cargo moving
00213    * around. */
00214   if (cargo_change) {
00215     /* Don't waste time updating if there are no custom station graphics
00216      * that might change. Even if there are custom graphics, they might
00217      * not change. Unfortunately we have no way of telling. */
00218     if (this->num_specs == 0) return;
00219   }
00220 
00221   for (h = 0; h < train_station.h; h++) {
00222     for (w = 0; w < train_station.w; w++) {
00223       if (this->TileBelongsToRailStation(tile)) {
00224         MarkTileDirtyByTile(tile);
00225       }
00226       tile += TileDiffXY(1, 0);
00227     }
00228     tile += TileDiffXY(-w, 1);
00229   }
00230 }
00231 
00232 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
00233 {
00234   assert(this->TileBelongsToRailStation(tile));
00235 
00236   TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00237 
00238   TileIndex t = tile;
00239   uint len = 0;
00240   do {
00241     t -= delta;
00242     len++;
00243   } while (IsCompatibleTrainStationTile(t, tile));
00244 
00245   t = tile;
00246   do {
00247     t += delta;
00248     len++;
00249   } while (IsCompatibleTrainStationTile(t, tile));
00250 
00251   return len - 1;
00252 }
00253 
00254 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
00255 {
00256   TileIndex start_tile = tile;
00257   uint length = 0;
00258   assert(IsRailStationTile(tile));
00259   assert(dir < DIAGDIR_END);
00260 
00261   do {
00262     length++;
00263     tile += TileOffsByDiagDir(dir);
00264   } while (IsCompatibleTrainStationTile(tile, start_tile));
00265 
00266   return length;
00267 }
00268 
00273 uint Station::GetCatchmentRadius() const
00274 {
00275   uint ret = CA_NONE;
00276 
00277   if (_settings_game.station.modified_catchment) {
00278     if (this->bus_stops          != NULL)         ret = max<uint>(ret, CA_BUS);
00279     if (this->truck_stops        != NULL)         ret = max<uint>(ret, CA_TRUCK);
00280     if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
00281     if (this->dock_tile          != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
00282     if (this->airport.tile       != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
00283   } else {
00284     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) {
00285       ret = CA_UNMODIFIED;
00286     }
00287   }
00288 
00289   return ret;
00290 }
00291 
00296 Rect Station::GetCatchmentRect() const
00297 {
00298   assert(!this->rect.IsEmpty());
00299 
00300   /* Compute acceptance rectangle */
00301   int catchment_radius = this->GetCatchmentRadius();
00302 
00303   Rect ret = {
00304     max<int>(this->rect.left   - catchment_radius, 0),
00305     max<int>(this->rect.top    - catchment_radius, 0),
00306     min<int>(this->rect.right  + catchment_radius, MapMaxX()),
00307     min<int>(this->rect.bottom + catchment_radius, MapMaxY())
00308   };
00309 
00310   return ret;
00311 }
00312 
00314 struct RectAndIndustryVector {
00315   Rect rect;                       
00316   IndustryVector *industries_near; 
00317 };
00318 
00327 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
00328 {
00329   /* Only process industry tiles */
00330   if (!IsTileType(ind_tile, MP_INDUSTRY)) return false;
00331 
00332   RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
00333   Industry *ind = Industry::GetByTile(ind_tile);
00334 
00335   /* Don't check further if this industry is already in the list */
00336   if (riv->industries_near->Contains(ind)) return false;
00337 
00338   /* Only process tiles in the station acceptance rectangle */
00339   int x = TileX(ind_tile);
00340   int y = TileY(ind_tile);
00341   if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
00342 
00343   /* Include only industries that can accept cargo */
00344   uint cargo_index;
00345   for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
00346     if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
00347   }
00348   if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
00349 
00350   *riv->industries_near->Append() = ind;
00351 
00352   return false;
00353 }
00354 
00359 void Station::RecomputeIndustriesNear()
00360 {
00361   this->industries_near.Clear();
00362   if (this->rect.IsEmpty()) return;
00363 
00364   RectAndIndustryVector riv = {
00365     this->GetCatchmentRect(),
00366     &this->industries_near
00367   };
00368 
00369   /* Compute maximum extent of acceptance rectangle wrt. station sign */
00370   TileIndex start_tile = this->xy;
00371   uint max_radius = max(
00372     max(DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.bottom))),
00373     max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
00374   );
00375 
00376   CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
00377 }
00378 
00382 /* static */ void Station::RecomputeIndustriesNearForAll()
00383 {
00384   Station *st;
00385   FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
00386 }
00387 
00388 /************************************************************************/
00389 /*                     StationRect implementation                       */
00390 /************************************************************************/
00391 
00392 StationRect::StationRect()
00393 {
00394   this->MakeEmpty();
00395 }
00396 
00397 void StationRect::MakeEmpty()
00398 {
00399   this->left = this->top = this->right = this->bottom = 0;
00400 }
00401 
00411 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
00412 {
00413   return this->left - distance <= x && x <= this->right + distance &&
00414       this->top - distance <= y && y <= this->bottom + distance;
00415 }
00416 
00417 bool StationRect::IsEmpty() const
00418 {
00419   return this->left == 0 || this->left > this->right || this->top > this->bottom;
00420 }
00421 
00422 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
00423 {
00424   int x = TileX(tile);
00425   int y = TileY(tile);
00426   if (this->IsEmpty()) {
00427     /* we are adding the first station tile */
00428     if (mode != ADD_TEST) {
00429       this->left = this->right = x;
00430       this->top = this->bottom = y;
00431     }
00432   } else if (!this->PtInExtendedRect(x, y)) {
00433     /* current rect is not empty and new point is outside this rect
00434      * make new spread-out rectangle */
00435     Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
00436 
00437     /* check new rect dimensions against preset max */
00438     int w = new_rect.right - new_rect.left + 1;
00439     int h = new_rect.bottom - new_rect.top + 1;
00440     if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
00441       assert(mode != ADD_TRY);
00442       return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00443     }
00444 
00445     /* spread-out ok, return true */
00446     if (mode != ADD_TEST) {
00447       /* we should update the station rect */
00448       *this = new_rect;
00449     }
00450   } else {
00451     ; // new point is inside the rect, we don't need to do anything
00452   }
00453   return CommandCost();
00454 }
00455 
00456 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
00457 {
00458   if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
00459     /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
00460     CommandCost ret = this->BeforeAddTile(tile, mode);
00461     if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
00462     return ret;
00463   }
00464   return CommandCost();
00465 }
00466 
00476 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
00477 {
00478   TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
00479   TILE_AREA_LOOP(tile, ta) {
00480     if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
00481   }
00482 
00483   return false;
00484 }
00485 
00486 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
00487 {
00488   int x = TileX(tile);
00489   int y = TileY(tile);
00490 
00491   /* look if removed tile was on the bounding rect edge
00492    * and try to reduce the rect by this edge
00493    * do it until we have empty rect or nothing to do */
00494   for (;;) {
00495     /* check if removed tile is on rect edge */
00496     bool left_edge = (x == this->left);
00497     bool right_edge = (x == this->right);
00498     bool top_edge = (y == this->top);
00499     bool bottom_edge = (y == this->bottom);
00500 
00501     /* can we reduce the rect in either direction? */
00502     bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
00503     bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
00504     if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
00505 
00506     if (reduce_x) {
00507       /* reduce horizontally */
00508       if (left_edge) {
00509         /* move left edge right */
00510         this->left = x = x + 1;
00511       } else {
00512         /* move right edge left */
00513         this->right = x = x - 1;
00514       }
00515     }
00516     if (reduce_y) {
00517       /* reduce vertically */
00518       if (top_edge) {
00519         /* move top edge down */
00520         this->top = y = y + 1;
00521       } else {
00522         /* move bottom edge up */
00523         this->bottom = y = y - 1;
00524       }
00525     }
00526 
00527     if (left > right || top > bottom) {
00528       /* can't continue, if the remaining rectangle is empty */
00529       this->MakeEmpty();
00530       return true; // empty remaining rect
00531     }
00532   }
00533   return false; // non-empty remaining rect
00534 }
00535 
00536 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
00537 {
00538   assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
00539   assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
00540 
00541   bool empty = this->AfterRemoveTile(st, ta.tile);
00542   if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
00543   return empty;
00544 }
00545 
00546 StationRect& StationRect::operator = (const Rect &src)
00547 {
00548   this->left = src.left;
00549   this->top = src.top;
00550   this->right = src.right;
00551   this->bottom = src.bottom;
00552   return *this;
00553 }
00554 
00560 Money AirportMaintenanceCost(Owner owner)
00561 {
00562   Money total_cost = 0;
00563 
00564   const Station *st;
00565   FOR_ALL_STATIONS(st) {
00566     if (st->owner == owner && (st->facilities & FACIL_AIRPORT)) {
00567       total_cost += _price[PR_INFRASTRUCTURE_AIRPORT] * st->airport.GetSpec()->maintenance_cost;
00568     }
00569   }
00570   /* 3 bits fraction for the maintenance cost factor. */
00571   return total_cost >> 3;
00572 }