# 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 "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
    00028 #include "table/strings.h"
    00029
    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   /* has to be done like this as we can't give arguments when constructing an array */
    00065   for (CargoID i = 0; i < NUM_CARGO; ++i) {
    00066     this->goods[i].cargo.AssignTo(this, i);
    00067   }
    00068 }
    00069
    00077 Station::~Station()
    00078 {
    00079   if (CleaningPool()) {
    00080     for (CargoID c = 0; c < NUM_CARGO; c++) {
    00081       this->goods[c].cargo.OnCleanPool();
    00082     }
    00083     return;
    00084   }
    00085
    00086   while (!this->loading_vehicles.empty()) {
    00087     this->loading_vehicles.front()->LeaveStation();
    00088   }
    00089
    00090   Aircraft *a;
    00091   FOR_ALL_AIRCRAFT(a) {
    00092     if (!a->IsNormalAircraft()) continue;
    00093     if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
    00094   }
    00095
    00096   Station *st;
    00097   FOR_ALL_STATIONS(st) {
    00098     for (CargoID c = 0; c < NUM_CARGO; ++c) {
    00099       GoodsEntry &ge = st->goods[c];
    00100       ge.link_stats.erase(this->index);
    00101       DeleteStaleFlows(st->index, c, this->index);
    00102       ge.cargo.RerouteStalePackets(this->index);
    00103     }
    00104   }
    00105
    00106   Vehicle *v;
    00107   FOR_ALL_VEHICLES(v) {
    00108     /* Forget about this station if this station is removed */
    00109     if (v->last_station_visited == this->index) {
    00110       v->last_station_visited = INVALID_STATION;
    00111     }
    00112     if (v->last_loading_station == this->index) {
    00113       v->last_loading_station = INVALID_STATION;
    00114     }
    00115   }
    00116
    00117   /* Clear the persistent storage. */
    00118   delete this->airport.psa;
    00119
    00120   if (this->owner == OWNER_NONE) {
    00121     /* Invalidate all in case of oil rigs. */
    00122     InvalidateWindowClassesData(WC_STATION_LIST, 0);
    00123   } else {
    00124     InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
    00125   }
    00126
    00127   DeleteWindowById(WC_STATION_VIEW, index);
    00128
    00129   /* Now delete all orders that go to the station */
    00130   RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
    00131
    00132   /* Remove all news items */
    00133   DeleteStationNews(this->index);
    00134
    00135   for (CargoID c = 0; c < NUM_CARGO; c++) {
    00136     this->goods[c].cargo.Truncate(0);
    00137   }
    00138
    00139   CargoPacket::InvalidateAllFrom(this->index);
    00140 }
    00141
    00142
    00148 void BaseStation::PostDestructor(size_t index)
    00149 {
    00150   InvalidateWindowData(WC_SELECT_STATION, 0, 0);
    00151 }
    00152
    00158 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
    00159 {
    00160   RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
    00161
    00162   for (; rs != NULL; rs = rs->next) {
    00163     /* The vehicle cannot go to this roadstop (different roadtype) */
    00164     if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
    00165     /* The vehicle is articulated and can therefor not go the a standard road stop */
    00166     if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
    00167
    00168     /* The vehicle can actually go to this road stop. So, return it! */
    00169     break;
    00170   }
    00171
    00172   return rs;
    00173 }
    00174
    00179 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
    00180 {
    00181   if (this->facilities == FACIL_NONE) {
    00182     this->xy = facil_xy;
    00183     this->random_bits = Random();
    00184   }
    00185   this->facilities |= new_facility_bit;
    00186   this->owner = _current_company;
    00187   this->build_date = _date;
    00188 }
    00189
    00195 void Station::MarkTilesDirty(bool cargo_change) const
    00196 {
    00197   TileIndex tile = this->train_station.tile;
    00198   int w, h;
    00199
    00200   if (tile == INVALID_TILE) return;
    00201
    00202   /* cargo_change is set if we're refreshing the tiles due to cargo moving
    00203    * around. */
    00204   if (cargo_change) {
    00205     /* Don't waste time updating if there are no custom station graphics
    00206      * that might change. Even if there are custom graphics, they might
    00207      * not change. Unfortunately we have no way of telling. */
    00208     if (this->num_specs == 0) return;
    00209   }
    00210
    00211   for (h = 0; h < train_station.h; h++) {
    00212     for (w = 0; w < train_station.w; w++) {
    00213       if (this->TileBelongsToRailStation(tile)) {
    00214         MarkTileDirtyByTile(tile);
    00215       }
    00216       tile += TileDiffXY(1, 0);
    00217     }
    00218     tile += TileDiffXY(-w, 1);
    00219   }
    00220 }
    00221
    00222 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
    00223 {
    00224   assert(this->TileBelongsToRailStation(tile));
    00225
    00226   TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
    00227
    00228   TileIndex t = tile;
    00229   uint len = 0;
    00230   do {
    00231     t -= delta;
    00232     len++;
    00233   } while (IsCompatibleTrainStationTile(t, tile));
    00234
    00235   t = tile;
    00236   do {
    00237     t += delta;
    00238     len++;
    00239   } while (IsCompatibleTrainStationTile(t, tile));
    00240
    00241   return len - 1;
    00242 }
    00243
    00244 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
    00245 {
    00246   TileIndex start_tile = tile;
    00247   uint length = 0;
    00248   assert(IsRailStationTile(tile));
    00249   assert(dir < DIAGDIR_END);
    00250
    00251   do {
    00252     length++;
    00253     tile += TileOffsByDiagDir(dir);
    00254   } while (IsCompatibleTrainStationTile(tile, start_tile));
    00255
    00256   return length;
    00257 }
    00258
    00263 uint Station::GetCatchmentRadius() const
    00264 {
    00265   uint ret = CA_NONE;
    00266
    00267   if (_settings_game.station.modified_catchment) {
    00268     if (this->bus_stops          != NULL)         ret = max<uint>(ret, CA_BUS);
    00269     if (this->truck_stops        != NULL)         ret = max<uint>(ret, CA_TRUCK);
    00270     if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
    00271     if (this->dock_tile          != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
    00272     if (this->airport.tile       != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
    00273   } else {
    00274     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) {
    00275       ret = CA_UNMODIFIED;
    00276     }
    00277   }
    00278
    00279   return ret;
    00280 }
    00281
    00286 Rect Station::GetCatchmentRect() const
    00287 {
    00288   assert(!this->rect.IsEmpty());
    00289
    00290   /* Compute acceptance rectangle */
    00291   int catchment_radius = this->GetCatchmentRadius();
    00292
    00293   Rect ret = {
    00294     max<int>(this->rect.left   - catchment_radius, 0),
    00295     max<int>(this->rect.top    - catchment_radius, 0),
    00296     min<int>(this->rect.right  + catchment_radius, MapMaxX()),
    00297     min<int>(this->rect.bottom + catchment_radius, MapMaxY())
    00298   };
    00299
    00300   return ret;
    00301 }
    00302
    00304 struct RectAndIndustryVector {
    00305   Rect rect;
    00306   IndustryVector *industries_near;
    00307 };
    00308
    00317 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
    00318 {
    00319   /* Only process industry tiles */
    00320   if (!IsTileType(ind_tile, MP_INDUSTRY)) return false;
    00321
    00322   RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
    00323   Industry *ind = Industry::GetByTile(ind_tile);
    00324
    00325   /* Don't check further if this industry is already in the list */
    00326   if (riv->industries_near->Contains(ind)) return false;
    00327
    00328   /* Only process tiles in the station acceptance rectangle */
    00329   int x = TileX(ind_tile);
    00330   int y = TileY(ind_tile);
    00331   if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
    00332
    00333   /* Include only industries that can accept cargo */
    00334   uint cargo_index;
    00335   for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
    00336     if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
    00337   }
    00338   if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
    00339
    00340   *riv->industries_near->Append() = ind;
    00341
    00342   return false;
    00343 }
    00344
    00349 void Station::RecomputeIndustriesNear()
    00350 {
    00351   this->industries_near.Clear();
    00352   if (this->rect.IsEmpty()) return;
    00353
    00354   RectAndIndustryVector riv = {
    00355     this->GetCatchmentRect(),
    00356     &this->industries_near
    00357   };
    00358
    00359   /* Compute maximum extent of acceptance rectangle wrt. station sign */
    00360   TileIndex start_tile = this->xy;
    00361   uint max_radius = max(
    00362     max(DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left,  riv.rect.bottom))),
    00363     max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
    00364   );
    00365
    00366   CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
    00367 }
    00368
    00372 /* static */ void Station::RecomputeIndustriesNearForAll()
    00373 {
    00374   Station *st;
    00375   FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
    00376 }
    00377
    00378 /************************************************************************/
    00379 /*                     StationRect implementation                       */
    00380 /************************************************************************/
    00381
    00382 StationRect::StationRect()
    00383 {
    00384   this->MakeEmpty();
    00385 }
    00386
    00387 void StationRect::MakeEmpty()
    00388 {
    00389   this->left = this->top = this->right = this->bottom = 0;
    00390 }
    00391
    00401 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
    00402 {
    00403   return this->left - distance <= x && x <= this->right + distance &&
    00404       this->top - distance <= y && y <= this->bottom + distance;
    00405 }
    00406
    00407 bool StationRect::IsEmpty() const
    00408 {
    00409   return this->left == 0 || this->left > this->right || this->top > this->bottom;
    00410 }
    00411
    00412 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
    00413 {
    00414   int x = TileX(tile);
    00415   int y = TileY(tile);
    00416   if (this->IsEmpty()) {
    00417     /* we are adding the first station tile */
    00418     if (mode != ADD_TEST) {
    00419       this->left = this->right = x;
    00420       this->top = this->bottom = y;
    00421     }
    00422   } else if (!this->PtInExtendedRect(x, y)) {
    00423     /* current rect is not empty and new point is outside this rect
    00424      * make new spread-out rectangle */
    00425     Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
    00426
    00427     /* check new rect dimensions against preset max */
    00428     int w = new_rect.right - new_rect.left + 1;
    00429     int h = new_rect.bottom - new_rect.top + 1;
    00430     if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
    00431       assert(mode != ADD_TRY);
    00432       return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
    00433     }
    00434
    00435     /* spread-out ok, return true */
    00436     if (mode != ADD_TEST) {
    00437       /* we should update the station rect */
    00438       *this = new_rect;
    00439     }
    00440   } else {
    00441     ; // new point is inside the rect, we don't need to do anything
    00442   }
    00443   return CommandCost();
    00444 }
    00445
    00446 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
    00447 {
    00448   if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
    00449     /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
    00450     CommandCost ret = this->BeforeAddTile(tile, mode);
    00451     if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
    00452     return ret;
    00453   }
    00454   return CommandCost();
    00455 }
    00456
    00466 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
    00467 {
    00468   TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
    00469   TILE_AREA_LOOP(tile, ta) {
    00470     if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
    00471   }
    00472
    00473   return false;
    00474 }
    00475
    00476 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
    00477 {
    00478   int x = TileX(tile);
    00479   int y = TileY(tile);
    00480
    00481   /* look if removed tile was on the bounding rect edge
    00482    * and try to reduce the rect by this edge
    00483    * do it until we have empty rect or nothing to do */
    00484   for (;;) {
    00485     /* check if removed tile is on rect edge */
    00486     bool left_edge = (x == this->left);
    00487     bool right_edge = (x == this->right);
    00488     bool top_edge = (y == this->top);
    00489     bool bottom_edge = (y == this->bottom);
    00490
    00491     /* can we reduce the rect in either direction? */
    00492     bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
    00493     bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
    00494     if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
    00495
    00496     if (reduce_x) {
    00497       /* reduce horizontally */
    00498       if (left_edge) {
    00499         /* move left edge right */
    00500         this->left = x = x + 1;
    00501       } else {
    00502         /* move right edge left */
    00503         this->right = x = x - 1;
    00504       }
    00505     }
    00506     if (reduce_y) {
    00507       /* reduce vertically */
    00508       if (top_edge) {
    00509         /* move top edge down */
    00510         this->top = y = y + 1;
    00511       } else {
    00512         /* move bottom edge up */
    00513         this->bottom = y = y - 1;
    00514       }
    00515     }
    00516
    00517     if (left > right || top > bottom) {
    00518       /* can't continue, if the remaining rectangle is empty */
    00519       this->MakeEmpty();
    00520       return true; // empty remaining rect
    00521     }
    00522   }
    00523   return false; // non-empty remaining rect
    00524 }
    00525
    00526 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
    00527 {
    00528   assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
    00529   assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
    00530
    00531   bool empty = this->AfterRemoveTile(st, ta.tile);
    00532   if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
    00533   return empty;
    00534 }
    00535
    00536 StationRect& StationRect::operator = (const Rect &src)
    00537 {
    00538   this->left = src.left;
    00539   this->top = src.top;
    00540   this->right = src.right;
    00541   this->bottom = src.bottom;
    00542   return *this;
    00543 }
    00544
    00550 Money AirportMaintenanceCost(Owner owner)
    00551 {
    00552   Money total_cost = 0;
    00553
    00554   const Station *st;
    00555   FOR_ALL_STATIONS(st) {
    00556     if (st->owner == owner && (st->facilities & FACIL_AIRPORT)) {
    00557       total_cost += _price[PR_INFRASTRUCTURE_AIRPORT] * st->airport.GetSpec()->maintenance_cost;
    00558     }
    00559   }
    00560   /* 3 bits fraction for the maintenance cost factor. */
    00561   return total_cost >> 3;
    00562 }