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"
25 #include "dock_base.h"
27 #include "core/random_func.hpp"
28 #include "overlay_cmd.h"
29 #include "linkgraph/linkgraph.h"
30 #include "linkgraph/linkgraphschedule.h"
31 #include "tracerestrict.h"
33 #include "table/strings.h"
35 #include "safeguards.h"
37 /** The pool of stations. */
38 StationPool
_station_pool("Station");
39 INSTANTIATE_POOL_METHODS(Station
)
41 typedef StationIDStack::SmallStackPool StationIDStackPool
;
42 template<> StationIDStackPool
StationIDStack::_pool
= StationIDStackPool();
44 BaseStation::~BaseStation()
49 if (CleaningPool()) return;
51 DeleteWindowById(WC_TRAINS_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_TRAIN
, this->owner
, this->index
).Pack());
52 DeleteWindowById(WC_ROADVEH_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_ROAD
, this->owner
, this->index
).Pack());
53 DeleteWindowById(WC_SHIPS_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_SHIP
, this->owner
, this->index
).Pack());
54 DeleteWindowById(WC_AIRCRAFT_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_AIRCRAFT
, this->owner
, this->index
).Pack());
55 DeleteWindowById(WC_DEPARTURES_BOARD
, this->index
);
57 this->sign
.MarkDirty();
60 Station::Station(TileIndex tile
) :
61 SpecializedStation
<Station
, false>(tile
),
62 bus_station(INVALID_TILE
, 0, 0),
63 truck_station(INVALID_TILE
, 0, 0),
64 dock_station(INVALID_TILE
, 0, 0),
67 time_since_unload(255),
68 last_vehicle_type(VEH_INVALID
)
70 /* this->random_bits is set in Station::AddFacility() */
74 * Clean up a station by clearing vehicle orders, invalidating windows and
75 * removing link stats.
76 * Aircraft-Hangar orders need special treatment here, as the hangars are
77 * actually part of a station (tiletype is STATION), but the order type
83 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
84 this->goods
[c
].cargo
.OnCleanPool();
89 while (!this->loading_vehicles
.empty()) {
90 this->loading_vehicles
.front()->LeaveStation();
95 if (!a
->IsNormalAircraft()) continue;
96 if (a
->targetairport
== this->index
) a
->targetairport
= INVALID_STATION
;
99 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
100 LinkGraph
*lg
= LinkGraph::GetIfValid(this->goods
[c
].link_graph
);
101 if (lg
== NULL
) continue;
103 for (NodeID node
= 0; node
< lg
->Size(); ++node
) {
104 Station
*st
= Station::Get((*lg
)[node
].Station());
105 st
->goods
[c
].flows
.erase(this->index
);
106 if ((*lg
)[node
][this->goods
[c
].node
].LastUpdate() != INVALID_DATE
) {
107 st
->goods
[c
].flows
.DeleteFlows(this->index
);
108 RerouteCargo(st
, c
, this->index
, st
->index
);
111 lg
->RemoveNode(this->goods
[c
].node
);
112 if (lg
->Size() == 0) {
113 LinkGraphSchedule::instance
.Unqueue(lg
);
119 FOR_ALL_VEHICLES(v
) {
120 /* Forget about this station if this station is removed */
121 if (v
->last_station_visited
== this->index
) {
122 v
->last_station_visited
= INVALID_STATION
;
124 if (v
->last_loading_station
== this->index
) {
125 v
->last_loading_station
= INVALID_STATION
;
129 /* Clear the persistent storage. */
130 delete this->airport
.psa
;
132 if (this->owner
== OWNER_NONE
) {
133 /* Invalidate all in case of oil rigs. */
134 InvalidateWindowClassesData(WC_STATION_LIST
, 0);
136 InvalidateWindowData(WC_STATION_LIST
, this->owner
, 0);
139 if (Overlays::Instance()->HasStation(Station::Get(this->index
))) {
140 Overlays::Instance()->ToggleStation(Station::Get(this->index
));
143 DeleteWindowById(WC_STATION_VIEW
, index
);
145 /* Now delete all orders that go to the station */
146 RemoveOrderFromAllVehicles(OT_GOTO_STATION
, this->index
);
148 TraceRestrictRemoveDestinationID(TROCAF_STATION
, this->index
);
150 /* Remove all news items */
151 DeleteStationNews(this->index
);
153 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
154 this->goods
[c
].cargo
.Truncate();
157 CargoPacket::InvalidateAllFrom(this->index
);
161 * Evaluate if a tile is in station catchment area.
162 * @param ti the tile info
163 * @param type the catchment type of the station
164 * @return true/false if the tile is in catchment
166 bool Station::IsTileInCatchmentArea(const TileInfo
* ti
, CatchmentType type
) const
170 return this->rect
.PtInExtendedRect(TileX(ti
->tile
),TileY(ti
->tile
),this->GetCatchmentRadius());
172 return this->catchment
.IsTileInCatchment(ti
->tile
);
182 * Invalidating of the JoinStation window has to be done
183 * after removing item from the pool.
184 * @param index index of deleted item
186 void BaseStation::PostDestructor(size_t index
)
188 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
192 * Get the primary road stop (the first road stop) that the given vehicle can load/unload.
193 * @param v the vehicle to get the first road stop for
194 * @return the first roadstop that this vehicle can load at
196 RoadStop
*Station::GetPrimaryRoadStop(const RoadVehicle
*v
) const
198 RoadStop
*rs
= this->GetPrimaryRoadStop(v
->IsBus() ? ROADSTOP_BUS
: ROADSTOP_TRUCK
);
200 for (; rs
!= NULL
; rs
= rs
->next
) {
201 /* The vehicle cannot go to this roadstop (different roadtype) */
202 if ((GetRoadTypes(rs
->xy
) & v
->compatible_roadtypes
) == ROADTYPES_NONE
) continue;
203 /* The vehicle is articulated and can therefore not go to a standard road stop. */
204 if (IsStandardRoadStopTile(rs
->xy
) && v
->HasArticulatedPart()) continue;
206 /* The vehicle can actually go to this road stop. So, return it! */
214 * Called when new facility is built on the station. If it is the first facility
215 * it initializes also 'xy' and 'random_bits' members
217 void Station::AddFacility(StationFacility new_facility_bit
, TileIndex facil_xy
)
219 if (this->facilities
== FACIL_NONE
) {
221 this->random_bits
= Random();
223 this->facilities
|= new_facility_bit
;
224 this->owner
= _current_company
;
225 this->build_date
= _date
;
229 * Marks the tiles of the station as dirty.
233 void Station::MarkTilesDirty(bool cargo_change
) const
235 TileIndex tile
= this->train_station
.tile
;
238 if (tile
== INVALID_TILE
) return;
240 /* cargo_change is set if we're refreshing the tiles due to cargo moving
243 /* Don't waste time updating if there are no custom station graphics
244 * that might change. Even if there are custom graphics, they might
245 * not change. Unfortunately we have no way of telling. */
246 if (this->num_specs
== 0) return;
249 for (h
= 0; h
< train_station
.h
; h
++) {
250 for (w
= 0; w
< train_station
.w
; w
++) {
251 if (this->TileBelongsToRailStation(tile
)) {
252 MarkTileDirtyByTile(tile
, ZOOM_LVL_DRAW_MAP
);
254 tile
+= TileDiffXY(1, 0);
256 tile
+= TileDiffXY(-w
, 1);
261 * Marks the acceptance tiles of the station as dirty.
265 void Station::MarkAcceptanceTilesDirty() const
267 Rect rec
= this->GetCatchmentRect();
268 TileIndex top_left
= TileXY(rec
.left
, rec
.top
);
269 int width
= rec
.right
- rec
.left
+ 1;
270 int height
= rec
.bottom
- rec
.top
+ 1;
272 TILE_AREA_LOOP(tile
, TileArea(top_left
, width
, height
) ) {
273 MarkTileDirtyByTile(tile
);
277 /* virtual */ uint
Station::GetPlatformLength(TileIndex tile
) const
279 assert(this->TileBelongsToRailStation(tile
));
281 TileIndexDiff delta
= (GetRailStationAxis(tile
) == AXIS_X
? TileDiffXY(1, 0) : TileDiffXY(0, 1));
288 } while (IsCompatibleTrainStationTile(t
, tile
));
294 } while (IsCompatibleTrainStationTile(t
, tile
));
299 /* virtual */ uint
Station::GetPlatformLength(TileIndex tile
, DiagDirection dir
) const
301 TileIndex start_tile
= tile
;
303 assert(IsRailStationTile(tile
));
304 assert(dir
< DIAGDIR_END
);
308 tile
+= TileOffsByDiagDir(dir
);
309 } while (IsCompatibleTrainStationTile(tile
, start_tile
));
315 * Determines the catchment radius of the station
318 uint
Station::GetCatchmentRadius() const
322 if (_settings_game
.station
.modified_catchment
) {
323 if (this->bus_stops
!= NULL
) ret
= max
<uint
>(ret
, CA_BUS
);
324 if (this->truck_stops
!= NULL
) ret
= max
<uint
>(ret
, CA_TRUCK
);
325 if (this->train_station
.tile
!= INVALID_TILE
) ret
= max
<uint
>(ret
, CA_TRAIN
);
326 if (this->docks
!= NULL
) ret
= max
<uint
>(ret
, CA_DOCK
);
327 if (this->airport
.tile
!= INVALID_TILE
) ret
= max
<uint
>(ret
, this->airport
.GetSpec()->catchment
);
329 if (this->bus_stops
!= NULL
|| this->truck_stops
!= NULL
|| this->train_station
.tile
!= INVALID_TILE
|| this->docks
!= NULL
|| this->airport
.tile
!= INVALID_TILE
) {
338 * Determines catchment rectangle of this station
339 * @return clamped catchment rectangle
341 Rect
Station::GetCatchmentRectUsingRadius(uint catchment_radius
) const
343 assert(!this->rect
.IsEmpty());
345 /* Compute acceptance rectangle */
347 max
<int>(this->rect
.left
- catchment_radius
, 0),
348 max
<int>(this->rect
.top
- catchment_radius
, 0),
349 min
<int>(this->rect
.right
+ catchment_radius
, MapMaxX()),
350 min
<int>(this->rect
.bottom
+ catchment_radius
, MapMaxY())
356 bool Station::IsDockingTile(TileIndex tile
) const
358 for (const Dock
*d
= this->docks
; d
!= NULL
; d
= d
->next
) {
359 if (tile
== d
->GetDockingTile()) return true;
364 /** Rect and pointer to IndustryVector */
365 struct RectAndIndustryVector
{
366 Rect rect
; ///< The rectangle to search the industries in.
367 IndustryVector
*industries_near
; ///< The nearby industries.
371 * Callback function for Station::RecomputeIndustriesNear()
372 * Tests whether tile is an industry and possibly adds
373 * the industry to station's industries_near list.
374 * @param ind_tile tile to check
375 * @param user_data pointer to RectAndIndustryVector
376 * @return always false, we want to search all tiles
378 static bool FindIndustryToDeliver(TileIndex ind_tile
, void *user_data
)
380 /* Only process industry tiles */
381 if (!IsTileType(ind_tile
, MP_INDUSTRY
)) return false;
383 RectAndIndustryVector
*riv
= (RectAndIndustryVector
*)user_data
;
384 Industry
*ind
= Industry::GetByTile(ind_tile
);
386 /* Don't check further if this industry is already in the list */
387 if (riv
->industries_near
->Contains(ind
)) return false;
389 /* Only process tiles in the station acceptance rectangle */
390 int x
= TileX(ind_tile
);
391 int y
= TileY(ind_tile
);
392 if (x
< riv
->rect
.left
|| x
> riv
->rect
.right
|| y
< riv
->rect
.top
|| y
> riv
->rect
.bottom
) return false;
394 /* Include only industries that can accept cargo */
396 for (cargo_index
= 0; cargo_index
< lengthof(ind
->accepts_cargo
); cargo_index
++) {
397 if (ind
->accepts_cargo
[cargo_index
] != CT_INVALID
) break;
399 if (cargo_index
>= lengthof(ind
->accepts_cargo
)) return false;
401 *riv
->industries_near
->Append() = ind
;
407 * Recomputes Station::industries_near, list of industries possibly
408 * accepting cargo in station's catchment radius
410 void Station::RecomputeIndustriesNear()
412 this->industries_near
.Clear();
413 if (this->rect
.IsEmpty()) return;
415 RectAndIndustryVector riv
= {
416 this->GetCatchmentRect(),
417 &this->industries_near
420 /* Compute maximum extent of acceptance rectangle wrt. station sign */
421 TileIndex start_tile
= this->xy
;
422 uint max_radius
= max(
423 max(DistanceManhattan(start_tile
, TileXY(riv
.rect
.left
, riv
.rect
.top
)), DistanceManhattan(start_tile
, TileXY(riv
.rect
.left
, riv
.rect
.bottom
))),
424 max(DistanceManhattan(start_tile
, TileXY(riv
.rect
.right
, riv
.rect
.top
)), DistanceManhattan(start_tile
, TileXY(riv
.rect
.right
, riv
.rect
.bottom
)))
427 CircularTileSearch(&start_tile
, 2 * max_radius
+ 1, &FindIndustryToDeliver
, &riv
);
431 * Recomputes Station::industries_near for all stations
433 /* static */ void Station::RecomputeIndustriesNearForAll()
436 FOR_ALL_STATIONS(st
) st
->RecomputeIndustriesNear();
439 /************************************************************************/
440 /* StationRect implementation */
441 /************************************************************************/
443 StationRect::StationRect()
448 void StationRect::MakeEmpty()
450 this->left
= this->top
= this->right
= this->bottom
= 0;
454 * Determines whether a given point (x, y) is within a certain distance of
455 * the station rectangle.
456 * @note x and y are in Tile coordinates
457 * @param x X coordinate
458 * @param y Y coordinate
459 * @param distance The maximum distance a point may have (L1 norm)
460 * @return true if the point is within distance tiles of the station rectangle
462 bool StationRect::PtInExtendedRect(int x
, int y
, int distance
) const
464 return this->left
- distance
<= x
&& x
<= this->right
+ distance
&&
465 this->top
- distance
<= y
&& y
<= this->bottom
+ distance
;
468 bool StationRect::IsEmpty() const
470 return this->left
== 0 || this->left
> this->right
|| this->top
> this->bottom
;
473 CommandCost
StationRect::BeforeAddTile(TileIndex tile
, StationRectMode mode
)
477 if (this->IsEmpty()) {
478 /* we are adding the first station tile */
479 if (mode
!= ADD_TEST
) {
480 this->left
= this->right
= x
;
481 this->top
= this->bottom
= y
;
483 } else if (!this->PtInExtendedRect(x
, y
)) {
484 /* current rect is not empty and new point is outside this rect
485 * make new spread-out rectangle */
486 Rect new_rect
= {min(x
, this->left
), min(y
, this->top
), max(x
, this->right
), max(y
, this->bottom
)};
488 /* check new rect dimensions against preset max */
489 int w
= new_rect
.right
- new_rect
.left
+ 1;
490 int h
= new_rect
.bottom
- new_rect
.top
+ 1;
491 if (mode
!= ADD_FORCE
&& (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
)) {
492 assert(mode
!= ADD_TRY
);
493 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
496 /* spread-out ok, return true */
497 if (mode
!= ADD_TEST
) {
498 /* we should update the station rect */
502 ; // new point is inside the rect, we don't need to do anything
504 return CommandCost();
507 CommandCost
StationRect::BeforeAddRect(TileIndex tile
, int w
, int h
, StationRectMode mode
)
509 if (mode
== ADD_FORCE
|| (w
<= _settings_game
.station
.station_spread
&& h
<= _settings_game
.station
.station_spread
)) {
510 /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
511 CommandCost ret
= this->BeforeAddTile(tile
, mode
);
512 if (ret
.Succeeded()) ret
= this->BeforeAddTile(TILE_ADDXY(tile
, w
- 1, h
- 1), mode
);
515 return CommandCost();
519 * Check whether station tiles of the given station id exist in the given rectangle
520 * @param st_id Station ID to look for in the rectangle
521 * @param left_a Minimal tile X edge of the rectangle
522 * @param top_a Minimal tile Y edge of the rectangle
523 * @param right_a Maximal tile X edge of the rectangle (inclusive)
524 * @param bottom_a Maximal tile Y edge of the rectangle (inclusive)
525 * @return \c true if a station tile with the given \a st_id exists in the rectangle, \c false otherwise
527 /* static */ bool StationRect::ScanForStationTiles(StationID st_id
, int left_a
, int top_a
, int right_a
, int bottom_a
)
529 TileArea
ta(TileXY(left_a
, top_a
), TileXY(right_a
, bottom_a
));
530 TILE_AREA_LOOP(tile
, ta
) {
531 if (IsTileType(tile
, MP_STATION
) && GetStationIndex(tile
) == st_id
) return true;
537 bool StationRect::AfterRemoveTile(BaseStation
*st
, TileIndex tile
)
542 /* look if removed tile was on the bounding rect edge
543 * and try to reduce the rect by this edge
544 * do it until we have empty rect or nothing to do */
546 /* check if removed tile is on rect edge */
547 bool left_edge
= (x
== this->left
);
548 bool right_edge
= (x
== this->right
);
549 bool top_edge
= (y
== this->top
);
550 bool bottom_edge
= (y
== this->bottom
);
552 /* can we reduce the rect in either direction? */
553 bool reduce_x
= ((left_edge
|| right_edge
) && !ScanForStationTiles(st
->index
, x
, this->top
, x
, this->bottom
));
554 bool reduce_y
= ((top_edge
|| bottom_edge
) && !ScanForStationTiles(st
->index
, this->left
, y
, this->right
, y
));
555 if (!(reduce_x
|| reduce_y
)) break; // nothing to do (can't reduce)
558 /* reduce horizontally */
560 /* move left edge right */
561 this->left
= x
= x
+ 1;
563 /* move right edge left */
564 this->right
= x
= x
- 1;
568 /* reduce vertically */
570 /* move top edge down */
571 this->top
= y
= y
+ 1;
573 /* move bottom edge up */
574 this->bottom
= y
= y
- 1;
578 if (left
> right
|| top
> bottom
) {
579 /* can't continue, if the remaining rectangle is empty */
581 return true; // empty remaining rect
584 return false; // non-empty remaining rect
587 bool StationRect::AfterRemoveRect(BaseStation
*st
, TileArea ta
)
589 assert(this->PtInExtendedRect(TileX(ta
.tile
), TileY(ta
.tile
)));
590 assert(this->PtInExtendedRect(TileX(ta
.tile
) + ta
.w
- 1, TileY(ta
.tile
) + ta
.h
- 1));
592 bool empty
= this->AfterRemoveTile(st
, ta
.tile
);
593 if (ta
.w
!= 1 || ta
.h
!= 1) empty
= empty
|| this->AfterRemoveTile(st
, TILE_ADDXY(ta
.tile
, ta
.w
- 1, ta
.h
- 1));
597 StationRect
& StationRect::operator = (const Rect
&src
)
599 this->left
= src
.left
;
601 this->right
= src
.right
;
602 this->bottom
= src
.bottom
;
607 * Calculates the maintenance cost of all airports of a company.
608 * @param owner Company.
609 * @return Total cost.
611 Money
AirportMaintenanceCost(Owner owner
)
613 Money total_cost
= 0;
616 FOR_ALL_STATIONS(st
) {
617 if (st
->owner
== owner
&& (st
->facilities
& FACIL_AIRPORT
)) {
618 total_cost
+= _price
[PR_INFRASTRUCTURE_AIRPORT
] * st
->airport
.GetSpec()->maintenance_cost
;
621 /* 3 bits fraction for the maintenance cost factor. */
622 return total_cost
>> 3;
625 /************************************************************************/
626 /* StationCatchment implementation */
627 /************************************************************************/
629 StationCatchment::StationCatchment()
634 * Determines whether a given point (x, y) is within the station catchment area
635 * @param tile TileIndex to test
636 * @return true if the point is within the station catchment area
638 bool StationCatchment::IsTileInCatchment(TileIndex tile
) const
640 return this->catchmentTiles
.find(tile
) != this->catchmentTiles
.end();
643 bool StationCatchment::IsEmpty() const
645 return this->catchmentTiles
.empty();
648 void StationCatchment::BeforeAddTile(TileIndex tile
, uint catchmentRadius
)
652 TileIndex top_left
= TileXY(max
<int>(x
- catchmentRadius
,0),max
<int>(y
- catchmentRadius
, 0));
653 int w
= min
<int>(x
+ catchmentRadius
, MapMaxX()) - TileX(top_left
) + 1;
654 int h
= min
<int>(y
+ catchmentRadius
, MapMaxY()) - TileY(top_left
) + 1;
656 /* we are adding the first station tile */
657 TILE_AREA_LOOP(t
, TileArea(top_left
, w
, h
) ) {
658 std::set
<TileIndex
> fromSet
;
659 fromSet
.insert(tile
);
660 this->catchmentTiles
[t
] = fromSet
;
663 TILE_AREA_LOOP(t
, TileArea(top_left
, w
, h
) ) {
664 std::map
<TileIndex
, std::set
<TileIndex
> >::iterator found
= this->catchmentTiles
.find(t
);
665 if ( found
== this->catchmentTiles
.end()) {
666 std::set
<TileIndex
> fromSet
;
667 fromSet
.insert(tile
);
668 this->catchmentTiles
[t
] = fromSet
;
669 } else if ((*found
).second
.find(tile
) == (*found
).second
.end()) {
670 (*found
).second
.insert(tile
);
676 void StationCatchment::BeforeAddRect(TileIndex tile
, int w
, int h
, uint catchmentRadius
)
678 TILE_AREA_LOOP(t
, TileArea(tile
, w
, h
) ) {
679 this->BeforeAddTile(t
, catchmentRadius
);
683 void StationCatchment::AfterRemoveTile(TileIndex tile
, uint catchmentRadius
)
687 TileIndex top_left
= TileXY(max
<int>(x
- catchmentRadius
,0),max
<int>(y
- catchmentRadius
, 0));
688 int w
= min
<int>(x
+ catchmentRadius
, MapMaxX()) - TileX(top_left
) + 1;
689 int h
= min
<int>(y
+ catchmentRadius
, MapMaxY()) - TileY(top_left
) + 1;
690 TILE_AREA_LOOP(t
, TileArea(top_left
, w
, h
)) {
691 std::map
<TileIndex
, std::set
<TileIndex
> >::iterator found
= this->catchmentTiles
.find(t
);
692 assert(found
!= this->catchmentTiles
.end());
693 std::set
<TileIndex
>::iterator stTileIter
= (*found
).second
.find(tile
);
694 assert(stTileIter
!= (*found
).second
.end());
695 (*found
).second
.erase(stTileIter
);
696 if ((*found
).second
.empty()) {
697 // tile t is no longer in StationCatchment
698 this->catchmentTiles
.erase(found
);
703 void StationCatchment::AfterRemoveRect(TileIndex tile
, int w
, int h
, uint catchmentRadius
)
705 TILE_AREA_LOOP(t
, TileArea(tile
, w
, h
)) {
706 this->AfterRemoveTile(t
, catchmentRadius
);