Add ScriptStoryPageElementList to get the contents of a page
[openttd/fttd.git] / src / station.cpp
blobd174aa90404d744dd008d7d3900290b7463a6f0c
1 /* $Id$ */
3 /*
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/>.
8 */
10 /** @file station.cpp Implementation of the station base class. */
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "company_base.h"
15 #include "roadveh.h"
16 #include "viewport_func.h"
17 #include "date_func.h"
18 #include "command_func.h"
19 #include "news_func.h"
20 #include "aircraft.h"
21 #include "vehiclelist.h"
22 #include "core/pool_func.hpp"
23 #include "station_base.h"
24 #include "roadstop_base.h"
25 #include "industry.h"
26 #include "core/random_func.hpp"
27 #include "linkgraph/linkgraph.h"
28 #include "linkgraph/linkgraphschedule.h"
29 #include "map/road.h"
31 #include "table/strings.h"
33 /** The pool of stations. */
34 StationPool _station_pool("Station");
35 INSTANTIATE_POOL_METHODS(Station)
37 typedef StationIDStack::SmallStackPool StationIDStackPool;
38 template<> StationIDStackPool StationIDStack::_pool("StationIDStack");
39 INSTANTIATE_POOL_METHODS(StationIDStack)
41 BaseStation::~BaseStation()
43 free(this->name);
44 free(this->speclist);
46 if (CleaningPool()) return;
48 Owner owner = this->owner;
49 if (!Company::IsValidID(owner)) owner = _local_company;
50 if (!Company::IsValidID(owner)) return; // Spectators
51 DeleteWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, owner, this->index).Pack());
52 DeleteWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, owner, this->index).Pack());
53 DeleteWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, owner, this->index).Pack());
54 DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->index).Pack());
56 this->sign.MarkDirty();
59 Station::Station(TileIndex tile) :
60 SpecializedStation<Station, false>(tile),
61 bus_station(INVALID_TILE, 0, 0),
62 truck_station(INVALID_TILE, 0, 0),
63 dock_area(INVALID_TILE, 0, 0),
64 indtype(IT_INVALID),
65 time_since_load(255),
66 time_since_unload(255),
67 last_vehicle_type(VEH_INVALID)
69 /* this->random_bits is set in Station::AddFacility() */
72 /**
73 * Clean up a station by clearing vehicle orders, invalidating windows and
74 * removing link stats.
75 * Aircraft-Hangar orders need special treatment here, as the hangars are
76 * actually part of a station (tiletype is STATION), but the order type
77 * is OT_GOTO_DEPOT.
79 Station::~Station()
81 if (CleaningPool()) {
82 for (CargoID c = 0; c < NUM_CARGO; c++) {
83 this->goods[c].cargo.OnCleanPool();
85 return;
88 while (!this->loading_vehicles.empty()) {
89 this->loading_vehicles.front()->LeaveStation();
92 Aircraft *a;
93 FOR_ALL_AIRCRAFT(a) {
94 if (!a->IsNormalAircraft()) continue;
95 if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
98 for (CargoID c = 0; c < NUM_CARGO; ++c) {
99 LinkGraph *lg = LinkGraph::GetIfValid(this->goods[c].link_graph);
100 if (lg == NULL) continue;
102 for (NodeID node = 0; node < lg->Size(); ++node) {
103 Station *st = Station::Get((*lg)[node].Station());
104 st->goods[c].flows.erase(this->index);
105 if ((*lg)[node][this->goods[c].node].LastUpdate() != INVALID_DATE) {
106 st->goods[c].flows.DeleteFlows(this->index);
107 RerouteCargo(st, c, this->index, st->index);
110 lg->RemoveNode(this->goods[c].node);
111 if (lg->Size() == 0) {
112 LinkGraphSchedule::Instance()->Unqueue(lg);
113 delete lg;
117 Vehicle *v;
118 FOR_ALL_VEHICLES(v) {
119 /* Forget about this station if this station is removed */
120 if (v->last_station_visited == this->index) {
121 v->last_station_visited = INVALID_STATION;
123 if (v->last_loading_station == this->index) {
124 v->last_loading_station = INVALID_STATION;
128 /* Clear the persistent storage. */
129 delete this->airport.psa;
131 if (this->owner == OWNER_NONE) {
132 /* Invalidate all in case of oil rigs. */
133 InvalidateWindowClassesData(WC_STATION_LIST, 0);
134 } else {
135 InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
138 DeleteWindowById(WC_STATION_VIEW, index);
140 /* Now delete all orders that go to the station */
141 RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
143 /* Remove all news items */
144 DeleteStationNews(this->index);
146 for (CargoID c = 0; c < NUM_CARGO; c++) {
147 this->goods[c].cargo.Truncate();
150 CargoPacket::InvalidateAllFrom(this->index);
155 * Invalidating of the JoinStation window has to be done
156 * after removing item from the pool.
157 * @param index index of deleted item
159 void BaseStation::PostDestructor(size_t index)
161 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
165 * Get the primary road stop (the first road stop) that the given vehicle can load/unload.
166 * @param v the vehicle to get the first road stop for
167 * @return the first roadstop that this vehicle can load at
169 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
171 RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
173 for (; rs != NULL; rs = rs->next) {
174 /* The vehicle cannot go to this roadstop (different roadtype) */
175 if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
176 /* The vehicle is articulated and can therefore not go to a standard road stop. */
177 if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
179 /* The vehicle can actually go to this road stop. So, return it! */
180 break;
183 return rs;
187 * Called when new facility is built on the station. If it is the first facility
188 * it initializes also 'xy' and 'random_bits' members
190 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
192 if (this->facilities == FACIL_NONE) {
193 this->xy = facil_xy;
194 this->random_bits = Random();
196 this->facilities |= new_facility_bit;
197 this->owner = _current_company;
198 this->build_date = _date;
202 * Marks the tiles of the station as dirty.
204 * @ingroup dirty
206 void Station::MarkTilesDirty(bool cargo_change) const
208 TileIndex tile = this->train_station.tile;
209 int w, h;
211 if (tile == INVALID_TILE) return;
213 /* cargo_change is set if we're refreshing the tiles due to cargo moving
214 * around. */
215 if (cargo_change) {
216 /* Don't waste time updating if there are no custom station graphics
217 * that might change. Even if there are custom graphics, they might
218 * not change. Unfortunately we have no way of telling. */
219 if (this->num_specs == 0) return;
222 for (h = 0; h < train_station.h; h++) {
223 for (w = 0; w < train_station.w; w++) {
224 if (this->TileBelongsToRailStation(tile)) {
225 MarkTileDirtyByTile(tile);
227 tile += TileDiffXY(1, 0);
229 tile += TileDiffXY(-w, 1);
233 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
235 assert(this->TileBelongsToRailStation(tile));
237 TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
239 TileIndex t = tile;
240 uint len = 0;
241 do {
242 t -= delta;
243 len++;
244 } while (IsCompatibleTrainStationTile(t, tile));
246 t = tile;
247 do {
248 t += delta;
249 len++;
250 } while (IsCompatibleTrainStationTile(t, tile));
252 return len - 1;
255 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
257 TileIndex start_tile = tile;
258 uint length = 0;
259 assert(IsRailStationTile(tile));
260 assert(dir < DIAGDIR_END);
262 do {
263 length++;
264 tile += TileOffsByDiagDir(dir);
265 } while (IsCompatibleTrainStationTile(tile, start_tile));
267 return length;
271 * Determines the catchment radius of the station
272 * @return The radius
274 uint Station::GetCatchmentRadius() const
276 uint ret = CA_NONE;
278 if (_settings_game.station.modified_catchment) {
279 if (this->bus_stops != NULL) ret = max<uint>(ret, CA_BUS);
280 if (this->truck_stops != NULL) ret = max<uint>(ret, CA_TRUCK);
281 if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
282 if (this->docks != NULL) ret = max<uint>(ret, CA_DOCK);
283 if (this->airport.tile != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
284 } else {
285 if (this->bus_stops != NULL || this->truck_stops != NULL || this->train_station.tile != INVALID_TILE || this->docks != NULL || this->airport.tile != INVALID_TILE) {
286 ret = CA_UNMODIFIED;
290 return ret;
294 * Determines catchment rectangle of this station
295 * @return clamped catchment rectangle
297 Rect Station::GetCatchmentRect() const
299 assert(!this->rect.IsEmpty());
301 /* Compute acceptance rectangle */
302 int catchment_radius = this->GetCatchmentRadius();
304 Rect ret = {
305 max<int>(this->rect.left - catchment_radius, 0),
306 max<int>(this->rect.top - catchment_radius, 0),
307 min<int>(this->rect.right + catchment_radius, MapMaxX()),
308 min<int>(this->rect.bottom + catchment_radius, MapMaxY())
311 return ret;
314 /** Rect and pointer to IndustryVector */
315 struct RectAndIndustryVector {
316 Rect rect; ///< The rectangle to search the industries in.
317 IndustryVector *industries_near; ///< The nearby industries.
321 * Callback function for Station::RecomputeIndustriesNear()
322 * Tests whether tile is an industry and possibly adds
323 * the industry to station's industries_near list.
324 * @param ind_tile tile to check
325 * @param user_data pointer to RectAndIndustryVector
326 * @return always false, we want to search all tiles
328 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
330 /* Only process industry tiles */
331 if (!IsIndustryTile(ind_tile)) return false;
333 RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
334 Industry *ind = Industry::GetByTile(ind_tile);
336 /* Don't check further if this industry is already in the list */
337 if (riv->industries_near->Contains(ind)) return false;
339 /* Only process tiles in the station acceptance rectangle */
340 int x = TileX(ind_tile);
341 int y = TileY(ind_tile);
342 if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
344 /* Include only industries that can accept cargo */
345 uint cargo_index;
346 for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
347 if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
349 if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
351 *riv->industries_near->Append() = ind;
353 return false;
357 * Recomputes Station::industries_near, list of industries possibly
358 * accepting cargo in station's catchment radius
360 void Station::RecomputeIndustriesNear()
362 this->industries_near.Clear();
363 if (this->rect.IsEmpty()) return;
365 RectAndIndustryVector riv = {
366 this->GetCatchmentRect(),
367 &this->industries_near
370 /* Compute maximum extent of acceptance rectangle wrt. station sign */
371 TileIndex start_tile = this->xy;
372 uint max_radius = max(
373 max(DistanceManhattan(start_tile, TileXY(riv.rect.left, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left, riv.rect.bottom))),
374 max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
377 CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
381 * Recomputes Station::industries_near for all stations
383 /* static */ void Station::RecomputeIndustriesNearForAll()
385 Station *st;
386 FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
389 /************************************************************************/
390 /* StationRect implementation */
391 /************************************************************************/
393 StationRect::StationRect()
395 this->MakeEmpty();
398 void StationRect::MakeEmpty()
400 this->left = this->top = this->right = this->bottom = 0;
404 * Determines whether a given point (x, y) is within a certain distance of
405 * the station rectangle.
406 * @note x and y are in Tile coordinates
407 * @param x X coordinate
408 * @param y Y coordinate
409 * @param distance The maximum distance a point may have (L1 norm)
410 * @return true if the point is within distance tiles of the station rectangle
412 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
414 return this->left - distance <= x && x <= this->right + distance &&
415 this->top - distance <= y && y <= this->bottom + distance;
418 bool StationRect::IsEmpty() const
420 return this->left == 0 || this->left > this->right || this->top > this->bottom;
423 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
425 int x = TileX(tile);
426 int y = TileY(tile);
427 if (this->IsEmpty()) {
428 /* we are adding the first station tile */
429 if (mode != ADD_TEST) {
430 this->left = this->right = x;
431 this->top = this->bottom = y;
433 } else if (!this->PtInExtendedRect(x, y)) {
434 /* current rect is not empty and new point is outside this rect
435 * make new spread-out rectangle */
436 Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
438 /* check new rect dimensions against preset max */
439 int w = new_rect.right - new_rect.left + 1;
440 int h = new_rect.bottom - new_rect.top + 1;
441 if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
442 assert(mode != ADD_TRY);
443 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
446 /* spread-out ok, return true */
447 if (mode != ADD_TEST) {
448 /* we should update the station rect */
449 *this = new_rect;
451 } else {
452 ; // new point is inside the rect, we don't need to do anything
454 return CommandCost();
457 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
459 if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
460 /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
461 CommandCost ret = this->BeforeAddTile(tile, mode);
462 if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
463 return ret;
465 return CommandCost();
469 * Check whether station tiles of the given station id exist in the given rectangle
470 * @param st_id Station ID to look for in the rectangle
471 * @param left_a Minimal tile X edge of the rectangle
472 * @param top_a Minimal tile Y edge of the rectangle
473 * @param right_a Maximal tile X edge of the rectangle (inclusive)
474 * @param bottom_a Maximal tile Y edge of the rectangle (inclusive)
475 * @return \c true if a station tile with the given \a st_id exists in the rectangle, \c false otherwise
477 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
479 TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
480 TILE_AREA_LOOP(tile, ta) {
481 if (IsStationTile(tile) && GetStationIndex(tile) == st_id) return true;
484 return false;
487 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
489 int x = TileX(tile);
490 int y = TileY(tile);
492 /* look if removed tile was on the bounding rect edge
493 * and try to reduce the rect by this edge
494 * do it until we have empty rect or nothing to do */
495 for (;;) {
496 /* check if removed tile is on rect edge */
497 bool left_edge = (x == this->left);
498 bool right_edge = (x == this->right);
499 bool top_edge = (y == this->top);
500 bool bottom_edge = (y == this->bottom);
502 /* can we reduce the rect in either direction? */
503 bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
504 bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
505 if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
507 if (reduce_x) {
508 /* reduce horizontally */
509 if (left_edge) {
510 /* move left edge right */
511 this->left = x = x + 1;
512 } else {
513 /* move right edge left */
514 this->right = x = x - 1;
517 if (reduce_y) {
518 /* reduce vertically */
519 if (top_edge) {
520 /* move top edge down */
521 this->top = y = y + 1;
522 } else {
523 /* move bottom edge up */
524 this->bottom = y = y - 1;
528 if (left > right || top > bottom) {
529 /* can't continue, if the remaining rectangle is empty */
530 this->MakeEmpty();
531 return true; // empty remaining rect
534 return false; // non-empty remaining rect
537 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
539 assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
540 assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
542 bool empty = this->AfterRemoveTile(st, ta.tile);
543 if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
544 return empty;
547 StationRect& StationRect::operator = (const Rect &src)
549 this->left = src.left;
550 this->top = src.top;
551 this->right = src.right;
552 this->bottom = src.bottom;
553 return *this;
556 /** The pool of docks. */
557 DockPool _dock_pool("Dock");
558 INSTANTIATE_POOL_METHODS(Dock)
561 * Calculates the maintenance cost of all airports of a company.
562 * @param owner Company.
563 * @return Total cost.
565 Money AirportMaintenanceCost(Owner owner)
567 Money total_cost = 0;
569 const Station *st;
570 FOR_ALL_STATIONS(st) {
571 if (st->owner == owner && (st->facilities & FACIL_AIRPORT)) {
572 total_cost += _price[PR_INFRASTRUCTURE_AIRPORT] * st->airport.GetSpec()->maintenance_cost;
575 /* 3 bits fraction for the maintenance cost factor. */
576 return total_cost >> 3;