(svn r23005) -Fix (r23004): Of course there's still the 16-sprite version for shore...
[openttd/fttd.git] / src / station.cpp
bloba0b72e7c6d2f595cca95fc2d83b4a3a9a4b8b455
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 "window_func.h"
18 #include "date_func.h"
19 #include "command_func.h"
20 #include "news_func.h"
21 #include "aircraft.h"
22 #include "vehiclelist.h"
23 #include "core/pool_func.hpp"
24 #include "station_base.h"
25 #include "roadstop_base.h"
26 #include "industry.h"
27 #include "core/random_func.hpp"
29 #include "table/strings.h"
31 /** The pool of stations. */
32 StationPool _station_pool("Station");
33 INSTANTIATE_POOL_METHODS(Station)
35 BaseStation::~BaseStation()
37 free(this->name);
38 free(this->speclist);
40 if (CleaningPool()) return;
42 Owner owner = this->owner;
43 if (!Company::IsValidID(owner)) owner = _local_company;
44 if (!Company::IsValidID(owner)) return; // Spectators
45 DeleteWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, owner, this->index).Pack());
46 DeleteWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, owner, this->index).Pack());
47 DeleteWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, owner, this->index).Pack());
48 DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->index).Pack());
50 this->sign.MarkDirty();
53 Station::Station(TileIndex tile) :
54 SpecializedStation<Station, false>(tile),
55 bus_station(INVALID_TILE, 0, 0),
56 truck_station(INVALID_TILE, 0, 0),
57 dock_tile(INVALID_TILE),
58 indtype(IT_INVALID),
59 time_since_load(255),
60 time_since_unload(255),
61 last_vehicle_type(VEH_INVALID)
63 /* this->random_bits is set in Station::AddFacility() */
66 /**
67 * Clean up a station by clearing vehicle orders and invalidating windows.
68 * Aircraft-Hangar orders need special treatment here, as the hangars are
69 * actually part of a station (tiletype is STATION), but the order type
70 * is OT_GOTO_DEPOT.
72 Station::~Station()
74 if (CleaningPool()) {
75 for (CargoID c = 0; c < NUM_CARGO; c++) {
76 this->goods[c].cargo.OnCleanPool();
78 return;
81 while (!this->loading_vehicles.empty()) {
82 this->loading_vehicles.front()->LeaveStation();
85 Aircraft *a;
86 FOR_ALL_AIRCRAFT(a) {
87 if (!a->IsNormalAircraft()) continue;
88 if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
91 Vehicle *v;
92 FOR_ALL_VEHICLES(v) {
93 /* Forget about this station if this station is removed */
94 if (v->last_station_visited == this->index) {
95 v->last_station_visited = INVALID_STATION;
99 /* Clear the persistent storage. */
100 delete this->airport.psa;
103 InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
105 DeleteWindowById(WC_STATION_VIEW, index);
107 /* Now delete all orders that go to the station */
108 RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
110 /* Remove all news items */
111 DeleteStationNews(this->index);
113 for (CargoID c = 0; c < NUM_CARGO; c++) {
114 this->goods[c].cargo.Truncate(0);
117 CargoPacket::InvalidateAllFrom(this->index);
122 * Invalidating of the JoinStation window has to be done
123 * after removing item from the pool.
124 * @param index index of deleted item
126 void BaseStation::PostDestructor(size_t index)
128 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
132 * Get the primary road stop (the first road stop) that the given vehicle can load/unload.
133 * @param v the vehicle to get the first road stop for
134 * @return the first roadstop that this vehicle can load at
136 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
138 RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
140 for (; rs != NULL; rs = rs->next) {
141 /* The vehicle cannot go to this roadstop (different roadtype) */
142 if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
143 /* The vehicle is articulated and can therefor not go the a standard road stop */
144 if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
146 /* The vehicle can actually go to this road stop. So, return it! */
147 break;
150 return rs;
154 * Called when new facility is built on the station. If it is the first facility
155 * it initializes also 'xy' and 'random_bits' members
157 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
159 if (this->facilities == FACIL_NONE) {
160 this->xy = facil_xy;
161 this->random_bits = Random();
163 this->facilities |= new_facility_bit;
164 this->owner = _current_company;
165 this->build_date = _date;
169 * Marks the tiles of the station as dirty.
171 * @ingroup dirty
173 void Station::MarkTilesDirty(bool cargo_change) const
175 TileIndex tile = this->train_station.tile;
176 int w, h;
178 if (tile == INVALID_TILE) return;
180 /* cargo_change is set if we're refreshing the tiles due to cargo moving
181 * around. */
182 if (cargo_change) {
183 /* Don't waste time updating if there are no custom station graphics
184 * that might change. Even if there are custom graphics, they might
185 * not change. Unfortunately we have no way of telling. */
186 if (this->num_specs == 0) return;
189 for (h = 0; h < train_station.h; h++) {
190 for (w = 0; w < train_station.w; w++) {
191 if (this->TileBelongsToRailStation(tile)) {
192 MarkTileDirtyByTile(tile);
194 tile += TileDiffXY(1, 0);
196 tile += TileDiffXY(-w, 1);
200 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
202 assert(this->TileBelongsToRailStation(tile));
204 TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
206 TileIndex t = tile;
207 uint len = 0;
208 do {
209 t -= delta;
210 len++;
211 } while (IsCompatibleTrainStationTile(t, tile));
213 t = tile;
214 do {
215 t += delta;
216 len++;
217 } while (IsCompatibleTrainStationTile(t, tile));
219 return len - 1;
222 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
224 TileIndex start_tile = tile;
225 uint length = 0;
226 assert(IsRailStationTile(tile));
227 assert(dir < DIAGDIR_END);
229 do {
230 length++;
231 tile += TileOffsByDiagDir(dir);
232 } while (IsCompatibleTrainStationTile(tile, start_tile));
234 return length;
238 * Determines the catchment radius of the station
239 * @return The radius
241 uint Station::GetCatchmentRadius() const
243 uint ret = CA_NONE;
245 if (_settings_game.station.modified_catchment) {
246 if (this->bus_stops != NULL) ret = max<uint>(ret, CA_BUS);
247 if (this->truck_stops != NULL) ret = max<uint>(ret, CA_TRUCK);
248 if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
249 if (this->dock_tile != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
250 if (this->airport.tile != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
251 } else {
252 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) {
253 ret = CA_UNMODIFIED;
257 return ret;
261 * Determines catchment rectangle of this station
262 * @return clamped catchment rectangle
264 Rect Station::GetCatchmentRect() const
266 assert(!this->rect.IsEmpty());
268 /* Compute acceptance rectangle */
269 int catchment_radius = this->GetCatchmentRadius();
271 Rect ret = {
272 max<int>(this->rect.left - catchment_radius, 0),
273 max<int>(this->rect.top - catchment_radius, 0),
274 min<int>(this->rect.right + catchment_radius, MapMaxX()),
275 min<int>(this->rect.bottom + catchment_radius, MapMaxY())
278 return ret;
281 /** Rect and pointer to IndustryVector */
282 struct RectAndIndustryVector {
283 Rect rect; ///< The rectangle to search the industries in.
284 IndustryVector *industries_near; ///< The nearby industries.
288 * Callback function for Station::RecomputeIndustriesNear()
289 * Tests whether tile is an industry and possibly adds
290 * the industry to station's industries_near list.
291 * @param ind_tile tile to check
292 * @param user_data pointer to RectAndIndustryVector
293 * @return always false, we want to search all tiles
295 static bool FindIndustryToDeliver(TileIndex ind_tile, void *user_data)
297 /* Only process industry tiles */
298 if (!IsTileType(ind_tile, MP_INDUSTRY)) return false;
300 RectAndIndustryVector *riv = (RectAndIndustryVector *)user_data;
301 Industry *ind = Industry::GetByTile(ind_tile);
303 /* Don't check further if this industry is already in the list */
304 if (riv->industries_near->Contains(ind)) return false;
306 /* Only process tiles in the station acceptance rectangle */
307 int x = TileX(ind_tile);
308 int y = TileY(ind_tile);
309 if (x < riv->rect.left || x > riv->rect.right || y < riv->rect.top || y > riv->rect.bottom) return false;
311 /* Include only industries that can accept cargo */
312 uint cargo_index;
313 for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
314 if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
316 if (cargo_index >= lengthof(ind->accepts_cargo)) return false;
318 *riv->industries_near->Append() = ind;
320 return false;
324 * Recomputes Station::industries_near, list of industries possibly
325 * accepting cargo in station's catchment radius
327 void Station::RecomputeIndustriesNear()
329 this->industries_near.Clear();
330 if (this->rect.IsEmpty()) return;
332 RectAndIndustryVector riv = {
333 this->GetCatchmentRect(),
334 &this->industries_near
337 /* Compute maximum extent of acceptance rectangle wrt. station sign */
338 TileIndex start_tile = this->xy;
339 uint max_radius = max(
340 max(DistanceManhattan(start_tile, TileXY(riv.rect.left, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.left, riv.rect.bottom))),
341 max(DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.top)), DistanceManhattan(start_tile, TileXY(riv.rect.right, riv.rect.bottom)))
344 CircularTileSearch(&start_tile, 2 * max_radius + 1, &FindIndustryToDeliver, &riv);
348 * Recomputes Station::industries_near for all stations
350 /* static */ void Station::RecomputeIndustriesNearForAll()
352 Station *st;
353 FOR_ALL_STATIONS(st) st->RecomputeIndustriesNear();
356 /************************************************************************/
357 /* StationRect implementation */
358 /************************************************************************/
360 StationRect::StationRect()
362 this->MakeEmpty();
365 void StationRect::MakeEmpty()
367 this->left = this->top = this->right = this->bottom = 0;
371 * Determines whether a given point (x, y) is within a certain distance of
372 * the station rectangle.
373 * @note x and y are in Tile coordinates
374 * @param x X coordinate
375 * @param y Y coordinate
376 * @param distance The maxmium distance a point may have (L1 norm)
377 * @return true if the point is within distance tiles of the station rectangle
379 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
381 return this->left - distance <= x && x <= this->right + distance &&
382 this->top - distance <= y && y <= this->bottom + distance;
385 bool StationRect::IsEmpty() const
387 return this->left == 0 || this->left > this->right || this->top > this->bottom;
390 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
392 int x = TileX(tile);
393 int y = TileY(tile);
394 if (this->IsEmpty()) {
395 /* we are adding the first station tile */
396 if (mode != ADD_TEST) {
397 this->left = this->right = x;
398 this->top = this->bottom = y;
400 } else if (!this->PtInExtendedRect(x, y)) {
401 /* current rect is not empty and new point is outside this rect
402 * make new spread-out rectangle */
403 Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
405 /* check new rect dimensions against preset max */
406 int w = new_rect.right - new_rect.left + 1;
407 int h = new_rect.bottom - new_rect.top + 1;
408 if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
409 assert(mode != ADD_TRY);
410 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
413 /* spread-out ok, return true */
414 if (mode != ADD_TEST) {
415 /* we should update the station rect */
416 *this = new_rect;
418 } else {
419 ; // new point is inside the rect, we don't need to do anything
421 return CommandCost();
424 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
426 if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
427 /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
428 CommandCost ret = this->BeforeAddTile(tile, mode);
429 if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
430 return ret;
432 return CommandCost();
436 * Check whether station tiles of the given station id exist in the given rectangle
437 * @param st_id Station ID to look for in the rectangle
438 * @param left_a Minimal tile X edge of the rectangle
439 * @param top_a Minimal tile Y edge of the rectangle
440 * @param right_a Maximal tile X edge of the rectangle (inclusive)
441 * @param bottom_a Maximal tile Y edge of the rectangle (inclusive)
442 * @return \c true if a station tile with the given \a st_id exists in the rectangle, \c false otherwise
444 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
446 TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
447 TILE_AREA_LOOP(tile, ta) {
448 if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
451 return false;
454 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
456 int x = TileX(tile);
457 int y = TileY(tile);
459 /* look if removed tile was on the bounding rect edge
460 * and try to reduce the rect by this edge
461 * do it until we have empty rect or nothing to do */
462 for (;;) {
463 /* check if removed tile is on rect edge */
464 bool left_edge = (x == this->left);
465 bool right_edge = (x == this->right);
466 bool top_edge = (y == this->top);
467 bool bottom_edge = (y == this->bottom);
469 /* can we reduce the rect in either direction? */
470 bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
471 bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
472 if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
474 if (reduce_x) {
475 /* reduce horizontally */
476 if (left_edge) {
477 /* move left edge right */
478 this->left = x = x + 1;
479 } else {
480 /* move right edge left */
481 this->right = x = x - 1;
484 if (reduce_y) {
485 /* reduce vertically */
486 if (top_edge) {
487 /* move top edge down */
488 this->top = y = y + 1;
489 } else {
490 /* move bottom edge up */
491 this->bottom = y = y - 1;
495 if (left > right || top > bottom) {
496 /* can't continue, if the remaining rectangle is empty */
497 this->MakeEmpty();
498 return true; // empty remaining rect
501 return false; // non-empty remaining rect
504 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
506 assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
507 assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
509 bool empty = this->AfterRemoveTile(st, ta.tile);
510 if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
511 return empty;
514 StationRect& StationRect::operator = (const Rect &src)
516 this->left = src.left;
517 this->top = src.top;
518 this->right = src.right;
519 this->bottom = src.bottom;
520 return *this;