4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file station.cpp Implementation of the station base class. */
13 #include "company_func.h"
14 #include "company_base.h"
16 #include "viewport_func.h"
17 #include "date_func.h"
18 #include "command_func.h"
19 #include "news_func.h"
21 #include "vehiclelist.h"
22 #include "core/pool_func.hpp"
23 #include "station_base.h"
24 #include "roadstop_base.h"
26 #include "core/random_func.hpp"
27 #include "linkgraph/linkgraph.h"
28 #include "linkgraph/linkgraphschedule.h"
30 #include "table/strings.h"
32 #include "safeguards.h"
34 /** The pool of stations. */
35 StationPool
_station_pool("Station");
36 INSTANTIATE_POOL_METHODS(Station
)
38 typedef StationIDStack::SmallStackPool StationIDStackPool
;
39 template<> StationIDStackPool
StationIDStack::_pool
= StationIDStackPool();
41 BaseStation::~BaseStation()
46 if (CleaningPool()) return;
48 DeleteWindowById(WC_TRAINS_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_TRAIN
, this->owner
, this->index
).Pack());
49 DeleteWindowById(WC_ROADVEH_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_ROAD
, this->owner
, this->index
).Pack());
50 DeleteWindowById(WC_SHIPS_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_SHIP
, this->owner
, this->index
).Pack());
51 DeleteWindowById(WC_AIRCRAFT_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_AIRCRAFT
, this->owner
, this->index
).Pack());
53 this->sign
.MarkDirty();
56 Station::Station(TileIndex tile
) :
57 SpecializedStation
<Station
, false>(tile
),
58 bus_station(INVALID_TILE
, 0, 0),
59 truck_station(INVALID_TILE
, 0, 0),
60 dock_tile(INVALID_TILE
),
63 time_since_unload(255),
64 last_vehicle_type(VEH_INVALID
)
66 /* this->random_bits is set in Station::AddFacility() */
70 * Clean up a station by clearing vehicle orders, invalidating windows and
71 * removing link stats.
72 * Aircraft-Hangar orders need special treatment here, as the hangars are
73 * actually part of a station (tiletype is STATION), but the order type
79 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
80 this->goods
[c
].cargo
.OnCleanPool();
85 while (!this->loading_vehicles
.empty()) {
86 this->loading_vehicles
.front()->LeaveStation();
91 if (!a
->IsNormalAircraft()) continue;
92 if (a
->targetairport
== this->index
) a
->targetairport
= INVALID_STATION
;
95 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
96 LinkGraph
*lg
= LinkGraph::GetIfValid(this->goods
[c
].link_graph
);
97 if (lg
== NULL
) continue;
99 for (NodeID node
= 0; node
< lg
->Size(); ++node
) {
100 Station
*st
= Station::Get((*lg
)[node
].Station());
101 st
->goods
[c
].flows
.erase(this->index
);
102 if ((*lg
)[node
][this->goods
[c
].node
].LastUpdate() != INVALID_DATE
) {
103 st
->goods
[c
].flows
.DeleteFlows(this->index
);
104 RerouteCargo(st
, c
, this->index
, st
->index
);
107 lg
->RemoveNode(this->goods
[c
].node
);
108 if (lg
->Size() == 0) {
109 LinkGraphSchedule::instance
.Unqueue(lg
);
115 FOR_ALL_VEHICLES(v
) {
116 /* Forget about this station if this station is removed */
117 if (v
->last_station_visited
== this->index
) {
118 v
->last_station_visited
= INVALID_STATION
;
120 if (v
->last_loading_station
== this->index
) {
121 v
->last_loading_station
= INVALID_STATION
;
125 /* Clear the persistent storage. */
126 delete this->airport
.psa
;
128 if (this->owner
== OWNER_NONE
) {
129 /* Invalidate all in case of oil rigs. */
130 InvalidateWindowClassesData(WC_STATION_LIST
, 0);
132 InvalidateWindowData(WC_STATION_LIST
, this->owner
, 0);
135 DeleteWindowById(WC_STATION_VIEW
, index
);
137 /* Now delete all orders that go to the station */
138 RemoveOrderFromAllVehicles(OT_GOTO_STATION
, this->index
);
140 /* Remove all news items */
141 DeleteStationNews(this->index
);
143 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
144 this->goods
[c
].cargo
.Truncate();
147 CargoPacket::InvalidateAllFrom(this->index
);
152 * Invalidating of the JoinStation window has to be done
153 * after removing item from the pool.
154 * @param index index of deleted item
156 void BaseStation::PostDestructor(size_t index
)
158 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
162 * Get the primary road stop (the first road stop) that the given vehicle can load/unload.
163 * @param v the vehicle to get the first road stop for
164 * @return the first roadstop that this vehicle can load at
166 RoadStop
*Station::GetPrimaryRoadStop(const RoadVehicle
*v
) const
168 RoadStop
*rs
= this->GetPrimaryRoadStop(v
->IsBus() ? ROADSTOP_BUS
: ROADSTOP_TRUCK
);
170 for (; rs
!= NULL
; rs
= rs
->next
) {
171 /* The vehicle cannot go to this roadstop (different roadtype) */
172 if ((GetRoadTypes(rs
->xy
) & v
->compatible_roadtypes
) == ROADTYPES_NONE
) continue;
173 /* The vehicle is articulated and can therefore not go to a standard road stop. */
174 if (IsStandardRoadStopTile(rs
->xy
) && v
->HasArticulatedPart()) continue;
176 /* The vehicle can actually go to this road stop. So, return it! */
184 * Called when new facility is built on the station. If it is the first facility
185 * it initializes also 'xy' and 'random_bits' members
187 void Station::AddFacility(StationFacility new_facility_bit
, TileIndex facil_xy
)
189 if (this->facilities
== FACIL_NONE
) {
191 this->random_bits
= Random();
193 this->facilities
|= new_facility_bit
;
194 this->owner
= _current_company
;
195 this->build_date
= _date
;
199 * Marks the tiles of the station as dirty.
203 void Station::MarkTilesDirty(bool cargo_change
) const
205 TileIndex tile
= this->train_station
.tile
;
208 if (tile
== INVALID_TILE
) return;
210 /* cargo_change is set if we're refreshing the tiles due to cargo moving
213 /* Don't waste time updating if there are no custom station graphics
214 * that might change. Even if there are custom graphics, they might
215 * not change. Unfortunately we have no way of telling. */
216 if (this->num_specs
== 0) return;
219 for (h
= 0; h
< train_station
.h
; h
++) {
220 for (w
= 0; w
< train_station
.w
; w
++) {
221 if (this->TileBelongsToRailStation(tile
)) {
222 MarkTileDirtyByTile(tile
);
224 tile
+= TileDiffXY(1, 0);
226 tile
+= TileDiffXY(-w
, 1);
230 /* virtual */ uint
Station::GetPlatformLength(TileIndex tile
) const
232 assert(this->TileBelongsToRailStation(tile
));
234 TileIndexDiff delta
= (GetRailStationAxis(tile
) == AXIS_X
? TileDiffXY(1, 0) : TileDiffXY(0, 1));
241 } while (IsCompatibleTrainStationTile(t
, tile
));
247 } while (IsCompatibleTrainStationTile(t
, tile
));
252 /* virtual */ uint
Station::GetPlatformLength(TileIndex tile
, DiagDirection dir
) const
254 TileIndex start_tile
= tile
;
256 assert(IsRailStationTile(tile
));
257 assert(dir
< DIAGDIR_END
);
261 tile
+= TileOffsByDiagDir(dir
);
262 } while (IsCompatibleTrainStationTile(tile
, start_tile
));
268 * Determines the catchment radius of the station
271 uint
Station::GetCatchmentRadius() const
275 if (_settings_game
.station
.modified_catchment
) {
276 if (this->bus_stops
!= NULL
) ret
= max
<uint
>(ret
, CA_BUS
);
277 if (this->truck_stops
!= NULL
) ret
= max
<uint
>(ret
, CA_TRUCK
);
278 if (this->train_station
.tile
!= INVALID_TILE
) ret
= max
<uint
>(ret
, CA_TRAIN
);
279 if (this->dock_tile
!= INVALID_TILE
) ret
= max
<uint
>(ret
, CA_DOCK
);
280 if (this->airport
.tile
!= INVALID_TILE
) ret
= max
<uint
>(ret
, this->airport
.GetSpec()->catchment
);
282 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
) {
291 * Determines catchment rectangle of this station
292 * @return clamped catchment rectangle
294 Rect
Station::GetCatchmentRect() const
296 assert(!this->rect
.IsEmpty());
298 /* Compute acceptance rectangle */
299 int catchment_radius
= this->GetCatchmentRadius();
302 max
<int>(this->rect
.left
- catchment_radius
, 0),
303 max
<int>(this->rect
.top
- catchment_radius
, 0),
304 min
<int>(this->rect
.right
+ catchment_radius
, MapMaxX()),
305 min
<int>(this->rect
.bottom
+ catchment_radius
, MapMaxY())
311 /** Rect and pointer to IndustryVector */
312 struct RectAndIndustryVector
{
313 Rect rect
; ///< The rectangle to search the industries in.
314 IndustryVector
*industries_near
; ///< The nearby industries.
318 * Callback function for Station::RecomputeIndustriesNear()
319 * Tests whether tile is an industry and possibly adds
320 * the industry to station's industries_near list.
321 * @param ind_tile tile to check
322 * @param user_data pointer to RectAndIndustryVector
323 * @return always false, we want to search all tiles
325 static bool FindIndustryToDeliver(TileIndex ind_tile
, void *user_data
)
327 /* Only process industry tiles */
328 if (!IsTileType(ind_tile
, MP_INDUSTRY
)) return false;
330 RectAndIndustryVector
*riv
= (RectAndIndustryVector
*)user_data
;
331 Industry
*ind
= Industry::GetByTile(ind_tile
);
333 /* Don't check further if this industry is already in the list */
334 if (riv
->industries_near
->Contains(ind
)) return false;
336 /* Only process tiles in the station acceptance rectangle */
337 int x
= TileX(ind_tile
);
338 int y
= TileY(ind_tile
);
339 if (x
< riv
->rect
.left
|| x
> riv
->rect
.right
|| y
< riv
->rect
.top
|| y
> riv
->rect
.bottom
) return false;
341 /* Include only industries that can accept cargo */
343 for (cargo_index
= 0; cargo_index
< lengthof(ind
->accepts_cargo
); cargo_index
++) {
344 if (ind
->accepts_cargo
[cargo_index
] != CT_INVALID
) break;
346 if (cargo_index
>= lengthof(ind
->accepts_cargo
)) return false;
348 *riv
->industries_near
->Append() = ind
;
354 * Recomputes Station::industries_near, list of industries possibly
355 * accepting cargo in station's catchment radius
357 void Station::RecomputeIndustriesNear()
359 this->industries_near
.Clear();
360 if (this->rect
.IsEmpty()) return;
362 RectAndIndustryVector riv
= {
363 this->GetCatchmentRect(),
364 &this->industries_near
367 /* Compute maximum extent of acceptance rectangle wrt. station sign */
368 TileIndex start_tile
= this->xy
;
369 uint max_radius
= max(
370 max(DistanceManhattan(start_tile
, TileXY(riv
.rect
.left
, riv
.rect
.top
)), DistanceManhattan(start_tile
, TileXY(riv
.rect
.left
, riv
.rect
.bottom
))),
371 max(DistanceManhattan(start_tile
, TileXY(riv
.rect
.right
, riv
.rect
.top
)), DistanceManhattan(start_tile
, TileXY(riv
.rect
.right
, riv
.rect
.bottom
)))
374 CircularTileSearch(&start_tile
, 2 * max_radius
+ 1, &FindIndustryToDeliver
, &riv
);
378 * Recomputes Station::industries_near for all stations
380 /* static */ void Station::RecomputeIndustriesNearForAll()
383 FOR_ALL_STATIONS(st
) st
->RecomputeIndustriesNear();
386 /************************************************************************/
387 /* StationRect implementation */
388 /************************************************************************/
390 StationRect::StationRect()
395 void StationRect::MakeEmpty()
397 this->left
= this->top
= this->right
= this->bottom
= 0;
401 * Determines whether a given point (x, y) is within a certain distance of
402 * the station rectangle.
403 * @note x and y are in Tile coordinates
404 * @param x X coordinate
405 * @param y Y coordinate
406 * @param distance The maximum distance a point may have (L1 norm)
407 * @return true if the point is within distance tiles of the station rectangle
409 bool StationRect::PtInExtendedRect(int x
, int y
, int distance
) const
411 return this->left
- distance
<= x
&& x
<= this->right
+ distance
&&
412 this->top
- distance
<= y
&& y
<= this->bottom
+ distance
;
415 bool StationRect::IsEmpty() const
417 return this->left
== 0 || this->left
> this->right
|| this->top
> this->bottom
;
420 CommandCost
StationRect::BeforeAddTile(TileIndex tile
, StationRectMode mode
)
424 if (this->IsEmpty()) {
425 /* we are adding the first station tile */
426 if (mode
!= ADD_TEST
) {
427 this->left
= this->right
= x
;
428 this->top
= this->bottom
= y
;
430 } else if (!this->PtInExtendedRect(x
, y
)) {
431 /* current rect is not empty and new point is outside this rect
432 * make new spread-out rectangle */
433 Rect new_rect
= {min(x
, this->left
), min(y
, this->top
), max(x
, this->right
), max(y
, this->bottom
)};
435 /* check new rect dimensions against preset max */
436 int w
= new_rect
.right
- new_rect
.left
+ 1;
437 int h
= new_rect
.bottom
- new_rect
.top
+ 1;
438 if (mode
!= ADD_FORCE
&& (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
)) {
439 assert(mode
!= ADD_TRY
);
440 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
443 /* spread-out ok, return true */
444 if (mode
!= ADD_TEST
) {
445 /* we should update the station rect */
449 ; // new point is inside the rect, we don't need to do anything
451 return CommandCost();
454 CommandCost
StationRect::BeforeAddRect(TileIndex tile
, int w
, int h
, StationRectMode mode
)
456 if (mode
== ADD_FORCE
|| (w
<= _settings_game
.station
.station_spread
&& h
<= _settings_game
.station
.station_spread
)) {
457 /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
458 CommandCost ret
= this->BeforeAddTile(tile
, mode
);
459 if (ret
.Succeeded()) ret
= this->BeforeAddTile(TILE_ADDXY(tile
, w
- 1, h
- 1), mode
);
462 return CommandCost();
466 * Check whether station tiles of the given station id exist in the given rectangle
467 * @param st_id Station ID to look for in the rectangle
468 * @param left_a Minimal tile X edge of the rectangle
469 * @param top_a Minimal tile Y edge of the rectangle
470 * @param right_a Maximal tile X edge of the rectangle (inclusive)
471 * @param bottom_a Maximal tile Y edge of the rectangle (inclusive)
472 * @return \c true if a station tile with the given \a st_id exists in the rectangle, \c false otherwise
474 /* static */ bool StationRect::ScanForStationTiles(StationID st_id
, int left_a
, int top_a
, int right_a
, int bottom_a
)
476 TileArea
ta(TileXY(left_a
, top_a
), TileXY(right_a
, bottom_a
));
477 TILE_AREA_LOOP(tile
, ta
) {
478 if (IsTileType(tile
, MP_STATION
) && GetStationIndex(tile
) == st_id
) return true;
484 bool StationRect::AfterRemoveTile(BaseStation
*st
, TileIndex tile
)
489 /* look if removed tile was on the bounding rect edge
490 * and try to reduce the rect by this edge
491 * do it until we have empty rect or nothing to do */
493 /* check if removed tile is on rect edge */
494 bool left_edge
= (x
== this->left
);
495 bool right_edge
= (x
== this->right
);
496 bool top_edge
= (y
== this->top
);
497 bool bottom_edge
= (y
== this->bottom
);
499 /* can we reduce the rect in either direction? */
500 bool reduce_x
= ((left_edge
|| right_edge
) && !ScanForStationTiles(st
->index
, x
, this->top
, x
, this->bottom
));
501 bool reduce_y
= ((top_edge
|| bottom_edge
) && !ScanForStationTiles(st
->index
, this->left
, y
, this->right
, y
));
502 if (!(reduce_x
|| reduce_y
)) break; // nothing to do (can't reduce)
505 /* reduce horizontally */
507 /* move left edge right */
508 this->left
= x
= x
+ 1;
510 /* move right edge left */
511 this->right
= x
= x
- 1;
515 /* reduce vertically */
517 /* move top edge down */
518 this->top
= y
= y
+ 1;
520 /* move bottom edge up */
521 this->bottom
= y
= y
- 1;
525 if (left
> right
|| top
> bottom
) {
526 /* can't continue, if the remaining rectangle is empty */
528 return true; // empty remaining rect
531 return false; // non-empty remaining rect
534 bool StationRect::AfterRemoveRect(BaseStation
*st
, TileArea ta
)
536 assert(this->PtInExtendedRect(TileX(ta
.tile
), TileY(ta
.tile
)));
537 assert(this->PtInExtendedRect(TileX(ta
.tile
) + ta
.w
- 1, TileY(ta
.tile
) + ta
.h
- 1));
539 bool empty
= this->AfterRemoveTile(st
, ta
.tile
);
540 if (ta
.w
!= 1 || ta
.h
!= 1) empty
= empty
|| this->AfterRemoveTile(st
, TILE_ADDXY(ta
.tile
, ta
.w
- 1, ta
.h
- 1));
544 StationRect
& StationRect::operator = (const Rect
&src
)
546 this->left
= src
.left
;
548 this->right
= src
.right
;
549 this->bottom
= src
.bottom
;
554 * Calculates the maintenance cost of all airports of a company.
555 * @param owner Company.
556 * @return Total cost.
558 Money
AirportMaintenanceCost(Owner owner
)
560 Money total_cost
= 0;
563 FOR_ALL_STATIONS(st
) {
564 if (st
->owner
== owner
&& (st
->facilities
& FACIL_AIRPORT
)) {
565 total_cost
+= _price
[PR_INFRASTRUCTURE_AIRPORT
] * st
->airport
.GetSpec()->maintenance_cost
;
568 /* 3 bits fraction for the maintenance cost factor. */
569 return total_cost
>> 3;