Translations update
[openttd/fttd.git] / src / station_cmd.cpp
blob36c552dd5da5dfee45ce0e6da9655859dd7b7864
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_cmd.cpp Handling of station tiles. */
12 #include "stdafx.h"
14 #include <functional>
16 #include "aircraft.h"
17 #include "cmd_helper.h"
18 #include "viewport_func.h"
19 #include "command_func.h"
20 #include "town.h"
21 #include "news_func.h"
22 #include "train.h"
23 #include "ship.h"
24 #include "roadveh.h"
25 #include "industry.h"
26 #include "newgrf_cargo.h"
27 #include "newgrf_debug.h"
28 #include "newgrf_station.h"
29 #include "newgrf_canal.h" /* For the buoy */
30 #include "pathfinder/yapf/yapf.h"
31 #include "road_internal.h" /* For drawing catenary/checking road removal */
32 #include "autoslope.h"
33 #include "water.h"
34 #include "strings_func.h"
35 #include "clear_func.h"
36 #include "date_func.h"
37 #include "vehicle_func.h"
38 #include "string.h"
39 #include "animated_tile_func.h"
40 #include "elrail_func.h"
41 #include "station_base.h"
42 #include "roadstop_base.h"
43 #include "newgrf_railtype.h"
44 #include "waypoint_base.h"
45 #include "waypoint_func.h"
46 #include "pbs.h"
47 #include "debug.h"
48 #include "core/random_func.hpp"
49 #include "company_base.h"
50 #include "table/airporttile_ids.h"
51 #include "newgrf_airporttiles.h"
52 #include "order_backup.h"
53 #include "newgrf_house.h"
54 #include "company_gui.h"
55 #include "linkgraph/linkgraph.h"
56 #include "linkgraph/linkgraphschedule.h"
57 #include "linkgraph/refresh.h"
58 #include "widgets/station_widget.h"
59 #include "signalbuffer.h"
60 #include "map/zoneheight.h"
61 #include "map/road.h"
63 #include "table/strings.h"
65 /**
66 * Static instance of FlowStat::SharesMap.
67 * Note: This instance is created on task start.
68 * Lazy creation on first usage results in a data race between the CDist threads.
70 /* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
72 /**
73 * Check whether the given tile is a hangar.
74 * @param t the tile to of whether it is a hangar.
75 * @pre IsStationTile(t)
76 * @return true if and only if the tile is a hangar.
78 bool IsHangar(TileIndex t)
80 assert(IsStationTile(t));
82 /* If the tile isn't an airport there's no chance it's a hangar. */
83 if (!IsAirport(t)) return false;
85 const Station *st = Station::GetByTile(t);
86 const AirportSpec *as = st->airport.GetSpec();
88 for (uint i = 0; i < as->nof_depots; i++) {
89 if (st->airport.GetHangarTile(i) == t) return true;
92 return false;
95 /**
96 * Check whether the tile is a mine.
97 * @param tile the tile to investigate.
98 * @return true if and only if the tile is a mine
100 static bool CMSAMine(TileIndex tile)
102 /* No industry */
103 if (!IsIndustryTile(tile)) return false;
105 const Industry *ind = Industry::GetByTile(tile);
107 /* No extractive industry */
108 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
110 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
111 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
112 * Also the production of passengers and mail is ignored. */
113 if (ind->produced_cargo[i] != CT_INVALID &&
114 (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
115 return true;
119 return false;
122 #define M(x) ((x) - STR_SV_STNAME)
124 enum StationNaming {
125 STATIONNAMING_RAIL,
126 STATIONNAMING_ROAD,
127 STATIONNAMING_AIRPORT,
128 STATIONNAMING_OILRIG,
129 STATIONNAMING_DOCK,
130 STATIONNAMING_HELIPORT,
133 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
135 static const uint32 _gen_station_name_bits[] = {
136 0, // STATIONNAMING_RAIL
137 0, // STATIONNAMING_ROAD
138 1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
139 1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
140 1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
141 1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
144 const Town *t = st->town;
145 uint32 free_names = UINT32_MAX;
147 bool indtypes[NUM_INDUSTRYTYPES];
148 memset(indtypes, 0, sizeof(indtypes));
150 const Station *s;
151 FOR_ALL_STATIONS(s) {
152 if (s != st && s->town == t) {
153 if (s->indtype != IT_INVALID) {
154 indtypes[s->indtype] = true;
155 StringID name = GetIndustrySpec(s->indtype)->station_name;
156 if (name != STR_UNDEFINED) {
157 /* Filter for other industrytypes with the same name */
158 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
159 const IndustrySpec *indsp = GetIndustrySpec(it);
160 if (indsp->enabled && indsp->station_name == name) indtypes[it] = true;
163 continue;
165 uint str = M(s->string_id);
166 if (str <= 0x20) {
167 if (str == M(STR_SV_STNAME_FOREST)) {
168 str = M(STR_SV_STNAME_WOODS);
170 ClrBit(free_names, str);
175 CircularTileIterator iter (tile, 7);
176 for (TileIndex indtile = iter; indtile != INVALID_TILE; indtile = ++iter) {
177 if (!IsIndustryTile(indtile)) continue;
179 /* If the station name is undefined it means that it doesn't name a station */
180 const IndustryType indtype = GetIndustryType(indtile);
181 const IndustrySpec *indsp = GetIndustrySpec(indtype);
182 if (indsp->station_name == STR_UNDEFINED) continue;
184 /* In all cases if an industry that provides a name is found
185 * two of the standard names will be disabled. */
186 free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
188 if (!indtypes[indtype]) {
189 /* An industry has been found nearby */
190 /* STR_NULL means it only disables oil rig/mines */
191 if (indsp->station_name != STR_NULL) {
192 st->indtype = indtype;
193 return STR_SV_STNAME_FALLBACK;
195 break;
199 /* check default names */
200 uint32 tmp = free_names & _gen_station_name_bits[name_class];
201 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
203 TileArea around (tile);
204 around.expand (3);
206 /* check mine? */
207 if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
208 uint num = 0;
209 TILE_AREA_LOOP(t, around) {
210 if (CMSAMine(t) && ++num >= 2) {
211 return STR_SV_STNAME_MINES;
216 /* check close enough to town to get central as name? */
217 if (DistanceMax(tile, t->xy) < 8) {
218 if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
220 if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
223 /* Check lakeside */
224 if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
225 DistanceFromEdge(tile) < 20) {
226 uint num = 0;
227 TILE_AREA_LOOP(t, around) {
228 if (IsPlainWaterTile(t) && ++num >= 5) {
229 return STR_SV_STNAME_LAKESIDE;
234 /* Check woods */
235 if (HasBit(free_names, M(STR_SV_STNAME_WOODS))) {
236 uint trees = 0;
237 uint forest = 0;
238 TILE_AREA_LOOP(t, around) {
239 if ((IsTreeTile(t) && ++trees >= 8) || (IsTileForestIndustry(t) && ++forest >= 2)) {
240 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
245 /* check elevation compared to town */
246 int z = GetTileZ(tile);
247 int z2 = GetTileZ(t->xy);
248 if (z < z2) {
249 if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
250 } else if (z > z2) {
251 if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
254 /* check direction compared to town */
255 static const int8 _direction_and_table[] = {
256 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
257 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
258 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
259 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
262 free_names &= _direction_and_table[
263 (TileX(tile) < TileX(t->xy)) +
264 (TileY(tile) < TileY(t->xy)) * 2];
266 tmp = free_names & ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 12) | (1 << 26) | (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30));
267 return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
269 #undef M
272 * Find the closest deleted station of the current company
273 * @param tile the tile to search from.
274 * @return the closest station or NULL if too far.
276 static Station *GetClosestDeletedStation(TileIndex tile)
278 uint threshold = 8;
279 Station *best_station = NULL;
280 Station *st;
282 FOR_ALL_STATIONS(st) {
283 if (!st->IsInUse() && st->owner == _current_company) {
284 uint cur_dist = DistanceManhattan(tile, st->xy);
286 if (cur_dist < threshold) {
287 threshold = cur_dist;
288 best_station = st;
293 return best_station;
297 void Station::GetTileArea(TileArea *ta, StationType type) const
299 switch (type) {
300 case STATION_RAIL:
301 *ta = this->train_station;
302 return;
304 case STATION_AIRPORT:
305 *ta = this->airport;
306 return;
308 case STATION_TRUCK:
309 *ta = this->truck_station;
310 return;
312 case STATION_BUS:
313 *ta = this->bus_station;
314 return;
316 case STATION_DOCK:
317 case STATION_OILRIG:
318 *ta = this->dock_area;
319 return;
321 default: NOT_REACHED();
326 * Update the virtual coords needed to draw the station sign.
328 void Station::UpdateVirtCoord()
330 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
332 pt.y -= 32 * ZOOM_LVL_BASE;
333 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
335 SetDParam(0, this->index);
336 SetDParam(1, this->facilities);
337 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
339 SetWindowDirty(WC_STATION_VIEW, this->index);
342 /** Update the virtual coords needed to draw the station sign for all stations. */
343 void UpdateAllStationVirtCoords()
345 BaseStation *st;
347 FOR_ALL_BASE_STATIONS(st) {
348 st->UpdateVirtCoord();
353 * Get a mask of the cargo types that the station accepts.
354 * @param st Station to query
355 * @return the expected mask
357 static uint GetAcceptanceMask(const Station *st)
359 uint mask = 0;
361 for (CargoID i = 0; i < NUM_CARGO; i++) {
362 if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) mask |= 1 << i;
364 return mask;
368 * Items contains the two cargo names that are to be accepted or rejected.
369 * msg is the string id of the message to display.
371 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
373 for (uint i = 0; i < num_items; i++) {
374 SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
377 SetDParam(0, st->index);
378 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
382 * Get the cargo types being produced around a tile area.
383 * @param area Tile area
384 * @param rad Search radius in addition to the given area
386 CargoArray GetAreaProduction (const TileArea &area, int rad)
388 CargoArray produced;
390 TileArea ta (area);
391 ta.expand (rad);
393 /* Loop over all tiles to get the produced cargo of
394 * everything except industries */
395 TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
397 /* Loop over the industries. They produce cargo for
398 * anything that is within 'rad' from their bounding
399 * box. As such if you have e.g. a oil well the tile
400 * area loop might not hit an industry tile while
401 * the industry would produce cargo for the station.
403 const Industry *i;
404 FOR_ALL_INDUSTRIES(i) {
405 if (!ta.Intersects(i->location)) continue;
407 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
408 CargoID cargo = i->produced_cargo[j];
409 if (cargo != CT_INVALID) produced[cargo]++;
413 return produced;
417 * Get the acceptance of cargoes around a tile area in 1/8.
418 * @param area Tile area
419 * @param rad Search radius in addition to given area
420 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be NULL
422 CargoArray GetAreaAcceptance (const TileArea &area, int rad, uint32 *always_accepted)
424 CargoArray acceptance;
425 if (always_accepted != NULL) *always_accepted = 0;
427 TileArea ta (area);
428 ta.expand (rad);
430 TILE_AREA_LOOP(tile, ta) AddAcceptedCargo(tile, acceptance, always_accepted);
432 return acceptance;
436 * Update the acceptance for a station.
437 * @param st Station to update
438 * @param show_msg controls whether to display a message that acceptance was changed.
440 void UpdateStationAcceptance(Station *st, bool show_msg)
442 /* old accepted goods types */
443 uint old_acc = GetAcceptanceMask(st);
445 /* And retrieve the acceptance. */
446 CargoArray acceptance;
447 if (!st->rect.empty()) {
448 acceptance = GetAreaAcceptance (st->rect,
449 st->GetCatchmentRadius(), &st->always_accepted);
452 /* Adjust in case our station only accepts fewer kinds of goods */
453 for (CargoID i = 0; i < NUM_CARGO; i++) {
454 /* Make sure the station can accept the goods type. */
455 uint amt = st->CanHandleCargo(i) ? acceptance[i] : 0;
457 GoodsEntry &ge = st->goods[i];
458 SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
459 if (LinkGraph::IsValidID(ge.link_graph)) {
460 (*LinkGraph::Get(ge.link_graph))[ge.node]->SetDemand(amt / 8);
464 /* Only show a message in case the acceptance was actually changed. */
465 uint new_acc = GetAcceptanceMask(st);
466 if (old_acc == new_acc) return;
468 /* show a message to report that the acceptance was changed? */
469 if (show_msg && st->owner == _local_company && st->IsInUse()) {
470 /* List of accept and reject strings for different number of
471 * cargo types */
472 static const StringID accept_msg[] = {
473 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
474 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
476 static const StringID reject_msg[] = {
477 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
478 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
481 /* Array of accepted and rejected cargo types */
482 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
483 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
484 uint num_acc = 0;
485 uint num_rej = 0;
487 /* Test each cargo type to see if its acceptance has changed */
488 for (CargoID i = 0; i < NUM_CARGO; i++) {
489 if (HasBit(new_acc, i)) {
490 if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
491 /* New cargo is accepted */
492 accepts[num_acc++] = i;
494 } else {
495 if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
496 /* Old cargo is no longer accepted */
497 rejects[num_rej++] = i;
502 /* Show news message if there are any changes */
503 if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
504 if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
507 /* redraw the station view since acceptance changed */
508 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
511 /** Update the station sign tile and virtual position. */
512 static void UpdateStationSign (BaseStation *st)
514 if (st->rect.empty()) { // no tiles belong to this station
515 st->UpdateVirtCoord();
516 return;
519 /* clamp sign coord to be inside the station rect */
520 st->xy = st->rect.get_closest_tile(st->xy);
521 st->UpdateVirtCoord();
523 if (st->IsWaypoint()) return;
524 Station *full_station = Station::From(st);
525 for (CargoID c = 0; c < NUM_CARGO; ++c) {
526 LinkGraphID lg = full_station->goods[c].link_graph;
527 if (!LinkGraph::IsValidID(lg)) continue;
532 * This is called right after a station was deleted.
533 * It checks if the whole station is free of substations, and if so, the station will be
534 * deleted after a little while.
535 * @param st Station
537 static void DeleteStationIfEmpty(BaseStation *st)
539 if (!st->IsInUse()) {
540 st->delete_ctr = 0;
541 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
545 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
548 * Checks if the given tile is buildable, flat and has a certain height.
549 * @param tile TileIndex to check.
550 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
551 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
552 * @param allow_steep Whether steep slopes are allowed.
553 * @param check_bridge Check for the existence of a bridge.
554 * @return The cost in case of success, or an error code if it failed.
556 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
558 if (check_bridge && HasBridgeAbove(tile)) {
559 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
562 CommandCost ret = EnsureNoVehicleOnGround(tile);
563 if (ret.Failed()) return ret;
565 int z;
566 Slope tileh = GetTileSlope(tile, &z);
568 /* Prohibit building if
569 * 1) The tile is "steep" (i.e. stretches two height levels).
570 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
572 if ((!allow_steep && IsSteepSlope(tileh)) ||
573 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
574 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
577 CommandCost cost(EXPENSES_CONSTRUCTION);
578 int flat_z = z + GetSlopeMaxZ(tileh);
579 if (tileh != SLOPE_FLAT) {
580 /* Forbid building if the tile faces a slope in a invalid direction. */
581 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
582 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
583 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
586 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
589 /* The level of this tile must be equal to allowed_z. */
590 if (allowed_z < 0) {
591 /* First tile. */
592 allowed_z = flat_z;
593 } else if (allowed_z != flat_z) {
594 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
597 return cost;
601 * Tries to clear the given area.
602 * @param tile_area Area to check.
603 * @param flags Operation to perform.
604 * @return The cost in case of success, or an error code if it failed.
606 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
608 CommandCost cost(EXPENSES_CONSTRUCTION);
609 int allowed_z = -1;
611 TILE_AREA_LOOP(tile_cur, tile_area) {
612 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
613 if (ret.Failed()) return ret;
614 cost.AddCost(ret);
616 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
617 if (ret.Failed()) return ret;
618 cost.AddCost(ret);
621 return cost;
625 * Checks if a rail station can be built at the given area.
626 * @param tile_area Area to check.
627 * @param flags Operation to perform.
628 * @param axis Rail station axis.
629 * @param station StationID to be queried and returned if available.
630 * @param rt The rail type to check for (overbuilding rail stations over rail).
631 * @param affected_vehicles List of trains with PBS reservations on the tiles
632 * @param statspec Station spec.
633 * @param plat_len Platform length.
634 * @param numtracks Number of platforms.
635 * @return The cost in case of success, or an error code if it failed.
637 static CommandCost CheckFlatLandRailStation (TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, SmallVector<Train *, 4> &affected_vehicles, const StationSpec *statspec, byte plat_len, byte numtracks)
639 CommandCost cost(EXPENSES_CONSTRUCTION);
640 int allowed_z = -1;
641 uint invalid_dirs = 5 << axis;
643 bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
645 TILE_AREA_LOOP(tile_cur, tile_area) {
646 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
647 if (ret.Failed()) return ret;
648 cost.AddCost(ret);
650 if (slope_cb) {
651 /* Do slope check if requested. */
652 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
653 if (ret.Failed()) return ret;
656 /* if station is set, then we have special handling to allow building on top of already existing stations.
657 * so station points to INVALID_STATION if we can build on any station.
658 * Or it points to a station if we're only allowed to build on exactly that station. */
659 if (station != NULL && IsStationTile(tile_cur)) {
660 if (!IsRailStation(tile_cur)) {
661 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
662 } else {
663 StationID st = GetStationIndex(tile_cur);
664 if (*station == INVALID_STATION) {
665 *station = st;
666 } else if (*station != st) {
667 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
670 } else {
671 /* Rail type is only valid when building a railway station; if station to
672 * build isn't a rail station it's INVALID_RAILTYPE. */
673 if (rt != INVALID_RAILTYPE && IsNormalRailTile(tile_cur) &&
674 HasPowerOnRail(GetRailType(tile_cur), rt)) {
675 /* Allow overbuilding if the tile:
676 * - has rail, but no signals
677 * - it has exactly one track
678 * - the track is in line with the station
679 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
681 Track track = AxisToTrack(axis);
683 if (GetTrackBits(tile_cur) == TrackToTrackBits(track) && !HasSignalOnTrack(tile_cur, track)) {
684 /* Check for trains having a reservation for this tile. */
685 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
686 Train *v = GetTrainForReservation(tile_cur, track);
687 if (v != NULL) {
688 *affected_vehicles.Append() = v;
691 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
692 if (ret.Failed()) return ret;
693 cost.AddCost(ret);
694 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
695 continue;
698 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
699 if (ret.Failed()) return ret;
700 cost.AddCost(ret);
704 return cost;
708 * Checks if a road stop can be built at the given tile.
709 * @param tile_area Area to check.
710 * @param flags Operation to perform.
711 * @param invalid_dirs Prohibited directions (set of DiagDirections).
712 * @param is_drive_through True if trying to build a drive-through station.
713 * @param is_truck_stop True when building a truck stop, false otherwise.
714 * @param axis Axis of a drive-through road stop.
715 * @param station StationID to be queried and returned if available.
716 * @param rts Road types to build.
717 * @return The cost in case of success, or an error code if it failed.
719 static CommandCost CheckFlatLandRoadStop(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadTypes rts)
721 CommandCost cost(EXPENSES_CONSTRUCTION);
722 int allowed_z = -1;
724 TILE_AREA_LOOP(cur_tile, tile_area) {
725 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
726 if (ret.Failed()) return ret;
727 cost.AddCost(ret);
729 /* If station is set, then we have special handling to allow building on top of already existing stations.
730 * Station points to INVALID_STATION if we can build on any station.
731 * Or it points to a station if we're only allowed to build on exactly that station. */
732 if (station != NULL && IsStationTile(cur_tile)) {
733 if (!IsRoadStop(cur_tile)) {
734 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
735 } else {
736 if (is_truck_stop != IsTruckStop(cur_tile) ||
737 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
738 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
740 /* Drive-through station in the wrong direction. */
741 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && GetRoadStopAxis(cur_tile) != axis){
742 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
744 StationID st = GetStationIndex(cur_tile);
745 if (*station == INVALID_STATION) {
746 *station = st;
747 } else if (*station != st) {
748 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
751 } else {
752 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
753 /* Road bits in the wrong direction. */
754 RoadBits rb = IsRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
755 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
756 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
757 switch (CountBits(rb)) {
758 case 1:
759 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
761 case 2:
762 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
763 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
765 default: // 3 or 4
766 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
770 RoadTypes cur_rts = IsRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
771 uint num_roadbits = 0;
772 if (build_over_road) {
773 /* There is a road, check if we can build road+tram stop over it. */
774 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
775 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
776 if (road_owner == OWNER_TOWN) {
777 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
778 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
779 CommandCost ret = CheckOwnership(road_owner);
780 if (ret.Failed()) return ret;
782 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
785 /* There is a tram, check if we can build road+tram stop over it. */
786 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
787 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
788 if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
789 CommandCost ret = CheckOwnership(tram_owner);
790 if (ret.Failed()) return ret;
792 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
795 /* Take into account existing roadbits. */
796 rts |= cur_rts;
797 } else {
798 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
799 if (ret.Failed()) return ret;
800 cost.AddCost(ret);
803 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
804 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
808 return cost;
812 * Checks if an airport can be built at the given area.
813 * @param tile_area Area to check.
814 * @param flags Operation to perform.
815 * @param station StationID of airport allowed in search area.
816 * @return The cost in case of success, or an error code if it failed.
818 static CommandCost CheckFlatLandAirport(TileArea tile_area, DoCommandFlag flags, StationID *station)
820 CommandCost cost(EXPENSES_CONSTRUCTION);
821 int allowed_z = -1;
823 TILE_AREA_LOOP(tile_cur, tile_area) {
824 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
825 if (ret.Failed()) return ret;
826 cost.AddCost(ret);
828 /* if station is set, then allow building on top of an already
829 * existing airport, either the one in *station if it is not
830 * INVALID_STATION, or anyone otherwise and store which one
831 * in *station */
832 if (station != NULL && IsStationTile(tile_cur)) {
833 if (!IsAirport(tile_cur)) {
834 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
835 } else {
836 StationID st = GetStationIndex(tile_cur);
837 if (*station == INVALID_STATION) {
838 *station = st;
839 } else if (*station != st) {
840 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
843 } else {
844 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
845 if (ret.Failed()) return ret;
846 cost.AddCost(ret);
850 return cost;
854 * Check whether we can expand the rail part of the given station.
855 * @param st the station to expand
856 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
857 * @param axis the axis of the newly build rail
858 * @return Succeeded or failed command.
860 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
862 TileArea cur_ta = st->train_station;
864 /* determine new size of train station region.. */
865 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
866 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
867 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
868 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
869 new_ta.tile = TileXY(x, y);
871 /* make sure the final size is not too big. */
872 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
873 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
876 return CommandCost();
879 static inline byte *CreateSingle(byte *layout, int n)
881 int i = n;
882 do *layout++ = 0; while (--i);
883 layout[((n - 1) >> 1) - n] = 2;
884 return layout;
887 static inline byte *CreateMulti(byte *layout, int n, byte b)
889 int i = n;
890 do *layout++ = b; while (--i);
891 if (n > 4) {
892 layout[0 - n] = 0;
893 layout[n - 1 - n] = 0;
895 return layout;
899 * Create the station layout for the given number of tracks and platform length.
900 * @param layout The layout to write to.
901 * @param numtracks The number of tracks to write.
902 * @param plat_len The length of the platforms.
903 * @param statspec The specification of the station to (possibly) get the layout from.
905 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
907 if (statspec != NULL && statspec->lengths >= plat_len &&
908 statspec->platforms[plat_len - 1] >= numtracks &&
909 statspec->layouts[plat_len - 1][numtracks - 1]) {
910 /* Custom layout defined, follow it. */
911 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
912 plat_len * numtracks);
913 return;
916 if (plat_len == 1) {
917 CreateSingle(layout, numtracks);
918 } else {
919 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
920 numtracks >>= 1;
922 while (--numtracks >= 0) {
923 layout = CreateMulti(layout, plat_len, 4);
924 layout = CreateMulti(layout, plat_len, 6);
930 * Find a nearby station that joins this station.
931 * @param pst 'return' pointer for the found station
932 * @param ta the area of the newly built station
933 * @param existing_station an existing station we build over
934 * @param station_to_join the station to join, if adjacent is set
935 * @param adjacent whether adjacent stations are allowed
936 * @param waypoint find waypoints, else stations
937 * @param error_message the error message when building a station on top of others
938 * @return command cost with the error or 'okay'
940 static CommandCost FindJoiningBaseStation (BaseStation **pst, TileArea ta,
941 StationID existing_station, StationID station_to_join, bool adjacent,
942 bool waypoint, StringID error_message)
944 BaseStation *st; // station to join
945 bool need_link; // need an adjacent piece of joined station
946 bool avoid_other; // avoid (other) adjacent stations
948 if (existing_station != INVALID_STATION) {
949 /* we are partially overbuilding a station */
950 if (adjacent && station_to_join != existing_station) {
951 /* you cannot join a different station */
952 return_cmd_error(error_message);
955 assert (BaseStation::IsValidID (existing_station));
956 st = BaseStation::Get (existing_station);
957 assert (st->IsWaypoint() == waypoint);
958 need_link = false;
959 avoid_other = !_settings_game.station.adjacent_stations;
960 } else if (!adjacent) {
961 /* join adjacent station if unique, else error out */
962 st = NULL;
963 need_link = true;
964 avoid_other = true;
965 } else if (station_to_join != INVALID_STATION) {
966 /* not overbuilding, and we want to join a given station */
967 st = BaseStation::GetIfValid (station_to_join);
968 if (st == NULL) return CMD_ERROR;
969 if (st->IsWaypoint() != waypoint) return CMD_ERROR;
970 need_link = st->IsInUse() && !_settings_game.station.distant_join_stations;
971 avoid_other = !_settings_game.station.adjacent_stations;
972 } else {
973 /* not overbuilding, and we want to build a new station */
974 st = NULL;
975 need_link = false;
976 avoid_other = !_settings_game.station.adjacent_stations;
979 if (need_link || avoid_other) {
980 ta.expand (1);
981 TILE_AREA_LOOP(tile_cur, ta) {
982 if (IsStationTile(tile_cur)) {
983 StationID t = GetStationIndex(tile_cur);
984 if (!BaseStation::IsValidID(t)) continue;
985 BaseStation *neighbour = BaseStation::Get(t);
986 if (neighbour->IsWaypoint() != waypoint) continue;
988 /* found an adjacent piece of a station */
989 if (st != NULL) {
990 /* wanted to join a given station */
991 if (t == st->index) {
992 /* found an adjacent piece */
993 need_link = false;
994 if (!avoid_other) break;
995 } else if (avoid_other) {
996 /* found a different station */
997 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
999 } else if (need_link) {
1000 /* wanted to join any station */
1001 st = neighbour;
1002 need_link = false;
1003 if (!avoid_other) break;
1004 } else if (avoid_other) {
1005 /* wanted to build a new station */
1006 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1012 /* tried to join a non-adjacent station but distant join is disabled? */
1013 if (st != NULL && need_link) return CMD_ERROR;
1015 *pst = st;
1017 return CommandCost();
1021 * Find a nearby station that joins this station.
1022 * @tparam T the class to find a station for
1023 * @param pst 'return' pointer for the found station
1024 * @param ta the area of the newly built station
1025 * @param existing_station an existing station we build over
1026 * @param station_to_join the station to join, if adjacent is set
1027 * @param adjacent whether adjacent stations are allowed
1028 * @param error_message the error message when building a station on top of others
1029 * @return command cost with the error or 'okay'
1031 template <class T>
1032 static inline CommandCost FindJoiningBaseStation (T **pst, TileArea ta,
1033 StationID existing_station, StationID station_to_join, bool adjacent,
1034 StringID error_message)
1036 BaseStation *bst;
1037 CommandCost ret = FindJoiningBaseStation (&bst, ta,
1038 existing_station, station_to_join, adjacent,
1039 T::IS_WAYPOINT, error_message);
1040 if (ret.Succeeded()) *pst = bst != NULL ? T::From (bst) : NULL;
1041 return ret;
1045 * Find a nearby waypoint that joins this waypoint.
1046 * @param existing_waypoint an existing waypoint we build over
1047 * @param waypoint_to_join the waypoint to join to
1048 * @param adjacent whether adjacent waypoints are allowed
1049 * @param ta the area of the newly build waypoint
1050 * @param wp 'return' pointer for the found waypoint
1051 * @return command cost with the error or 'okay'
1053 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
1055 return FindJoiningBaseStation<Waypoint> (wp, ta, existing_waypoint,
1056 waypoint_to_join, adjacent,
1057 STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST);
1061 * Common part of building various station parts and possibly attaching them to an existing one.
1062 * @param [out] st Station to attach to
1063 * @param area Area occupied by the new part
1064 * @param existing_station Existing station we build over
1065 * @param station_to_join Station to join, if adjacent is set
1066 * @param adjacent Whether adjacent stations are allowed
1067 * @param error_message Error message when building a station on top of others
1068 * @param flags Command flags
1069 * @param name_class Station naming class to use to generate the new station's name
1070 * @return Command error that occurred, if any
1072 static CommandCost BuildStationPart (Station **st, const TileArea &area,
1073 StationID existing_station, StationID station_to_join, bool adjacent,
1074 StringID error_message, DoCommandFlag flags, StationNaming name_class)
1076 CommandCost ret = FindJoiningBaseStation<Station> (st, area,
1077 existing_station, station_to_join, adjacent, error_message);
1078 if (ret.Failed()) return ret;
1080 /* Find a deleted station close to us */
1081 if (*st == NULL && !adjacent) *st = GetClosestDeletedStation(area.tile);
1083 if (*st != NULL) {
1084 if ((*st)->owner != _current_company) {
1085 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
1088 if (!(*st)->TestAddRect(area)) {
1089 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1091 } else {
1092 /* allocate and initialize new station */
1093 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
1095 if (flags & DC_EXEC) {
1096 *st = new Station(area.tile);
1098 (*st)->town = ClosestTownFromTile(area.tile);
1099 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
1101 if (Company::IsValidID(_current_company)) {
1102 SetBit((*st)->town->have_ratings, _current_company);
1107 return CommandCost();
1111 static void FreeTrainReservation(Train *v)
1113 FreeTrainTrackReservation(v);
1115 const RailPathPos pos = v->GetPos();
1116 if (!pos.in_wormhole() && IsRailStationTile(pos.tile)) SetRailStationPlatformReservation(pos, false);
1118 const RailPathPos rev = v->Last()->GetReversePos();
1119 if (!rev.in_wormhole() && IsRailStationTile(rev.tile)) SetRailStationPlatformReservation(rev, false);
1122 static void RestoreTrainReservation(Train *v)
1124 const RailPathPos pos = v->GetPos();
1125 if (!pos.in_wormhole() && IsRailStationTile(pos.tile)) SetRailStationPlatformReservation(pos, true);
1127 /* Check first if the train can have a reservation (not heading into a depot). */
1128 if (FreeTrainTrackReservation(v)) TryPathReserve(v, true, true);
1130 const RailPathPos rev = v->Last()->GetReversePos();
1131 if (!rev.in_wormhole() && IsRailStationTile(rev.tile)) SetRailStationPlatformReservation(rev, true);
1135 * Build rail station
1136 * @param tile_org northern most position of station dragging/placement
1137 * @param flags operation to perform
1138 * @param p1 various bitstuffed elements
1139 * - p1 = (bit 0- 3) - railtype
1140 * - p1 = (bit 4) - orientation (Axis)
1141 * - p1 = (bit 8-15) - number of tracks
1142 * - p1 = (bit 16-23) - platform length
1143 * - p1 = (bit 24) - allow stations directly adjacent to other stations.
1144 * @param p2 various bitstuffed elements
1145 * - p2 = (bit 0- 7) - custom station class
1146 * - p2 = (bit 8-15) - custom station id
1147 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
1148 * @param text unused
1149 * @return the cost of this operation or an error
1151 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1153 /* Unpack parameters */
1154 RailType rt = Extract<RailType, 0, 4>(p1);
1155 Axis axis = Extract<Axis, 4, 1>(p1);
1156 byte numtracks = GB(p1, 8, 8);
1157 byte plat_len = GB(p1, 16, 8);
1158 bool adjacent = HasBit(p1, 24);
1160 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
1161 byte spec_index = GB(p2, 8, 8);
1162 StationID station_to_join = GB(p2, 16, 16);
1164 /* Does the authority allow this? */
1165 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1166 if (ret.Failed()) return ret;
1168 if (!ValParamRailtype(rt)) return CMD_ERROR;
1170 /* Check if the given station class is valid */
1171 if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
1172 const StationClass *statclass = StationClass::Get(spec_class);
1173 if (spec_index >= statclass->GetSpecCount()) return CMD_ERROR;
1174 const StationSpec *statspec = statclass->GetSpec(spec_index);
1176 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1178 int w_org, h_org;
1179 if (axis == AXIS_X) {
1180 w_org = plat_len;
1181 h_org = numtracks;
1182 } else {
1183 h_org = plat_len;
1184 w_org = numtracks;
1187 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1189 /* these values are those that will be stored in train_tile and station_platforms */
1190 TileArea new_location(tile_org, w_org, h_org);
1192 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1193 StationID est = INVALID_STATION;
1194 SmallVector<Train *, 4> affected_vehicles;
1195 /* Clear the land below the station. */
1196 CommandCost cost = CheckFlatLandRailStation (new_location, flags, axis, &est, rt, affected_vehicles, statspec, plat_len, numtracks);
1197 if (cost.Failed()) return cost;
1198 /* Add construction expenses. */
1199 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
1200 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
1202 Station *st = NULL;
1203 ret = BuildStationPart (&st, new_location, est, station_to_join,
1204 adjacent, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST,
1205 flags, STATIONNAMING_RAIL);
1206 if (ret.Failed()) return ret;
1208 if (st != NULL && st->train_station.tile != INVALID_TILE) {
1209 CommandCost ret = CanExpandRailStation(st, new_location, axis);
1210 if (ret.Failed()) return ret;
1213 /* Check if we can allocate a custom stationspec to this station */
1214 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1215 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1217 if (statspec != NULL) {
1218 /* Perform NewStation checks */
1220 /* Check if the station size is permitted */
1221 if (HasBit(statspec->disallowed_platforms, min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, min(plat_len - 1, 7))) {
1222 return CMD_ERROR;
1225 /* Check if the station is buildable */
1226 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1227 uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
1228 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1232 if (flags & DC_EXEC) {
1233 TileIndexDiff tile_delta;
1234 byte *layout_ptr;
1235 byte numtracks_orig;
1236 Track track;
1238 st->train_station = new_location;
1239 st->AddFacility(FACIL_TRAIN, new_location.tile);
1241 st->rect.Add (TileArea (tile_org, w_org, h_org));
1243 if (statspec != NULL) {
1244 /* Include this station spec's animation trigger bitmask
1245 * in the station's cached copy. */
1246 st->cached_anim_triggers |= statspec->animation.triggers;
1249 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1250 track = AxisToTrack(axis);
1252 layout_ptr = AllocaM(byte, numtracks * plat_len);
1253 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
1255 numtracks_orig = numtracks;
1257 Company *c = Company::Get(st->owner);
1258 TileIndex tile_track = tile_org;
1259 do {
1260 TileIndex tile = tile_track;
1261 int w = plat_len;
1262 do {
1263 byte layout = *layout_ptr++;
1264 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1265 /* Check for trains having a reservation for this tile. */
1266 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1267 if (v != NULL) {
1268 *affected_vehicles.Append() = v;
1269 FreeTrainReservation(v);
1273 /* Railtype can change when overbuilding. */
1274 if (IsRailStationTile(tile)) {
1275 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1276 c->infrastructure.station--;
1279 /* Remove animation if overbuilding */
1280 DeleteAnimatedTile(tile);
1281 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1282 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1283 /* Free the spec if we overbuild something */
1284 DeallocateSpecFromStation(st, old_specindex);
1286 SetCustomStationSpecIndex(tile, specindex);
1287 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1288 SetAnimationFrame(tile, 0);
1290 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1291 c->infrastructure.station++;
1293 if (statspec != NULL) {
1294 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1295 uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1297 /* As the station is not yet completely finished, the station does not yet exist. */
1298 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
1299 if (callback != CALLBACK_FAILED) {
1300 if (callback < 8) {
1301 SetStationGfx(tile, (callback & ~1) + axis);
1302 } else {
1303 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
1307 /* Trigger station animation -- after building? */
1308 TriggerStationAnimation(st, tile, SAT_BUILT);
1311 tile += tile_delta;
1312 } while (--w);
1313 AddTrackToSignalBuffer(tile_track, track, _current_company);
1314 YapfNotifyTrackLayoutChange(tile_track, track);
1315 tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1316 } while (--numtracks);
1318 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
1319 RestoreTrainReservation(affected_vehicles[i]);
1322 /* Check whether we need to expand the reservation of trains already on the station. */
1323 TileArea update_reservation_area;
1324 if (axis == AXIS_X) {
1325 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1326 } else {
1327 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1330 TILE_AREA_LOOP(tile, update_reservation_area) {
1331 /* Don't even try to make eye candy parts reserved. */
1332 if (IsStationTileBlocked(tile)) continue;
1334 DiagDirection dir = AxisToDiagDir(axis);
1335 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1336 TileIndex platform_begin = tile;
1337 TileIndex platform_end = tile;
1339 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1340 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1341 platform_begin = next_tile;
1343 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1344 platform_end = next_tile;
1347 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1348 bool reservation = false;
1349 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1350 reservation = HasStationReservation(t);
1353 if (reservation) {
1354 SetRailStationPlatformReservation(platform_begin, dir, true);
1358 st->MarkTilesDirty(false);
1359 st->UpdateVirtCoord();
1360 UpdateStationAcceptance(st, false);
1361 st->RecomputeIndustriesNear();
1362 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
1363 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
1364 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1365 DirtyCompanyInfrastructureWindows(st->owner);
1368 return cost;
1372 * Remove a number of tiles from any rail station or waypoint within the area.
1373 * @param start tile of station piece to remove
1374 * @param flags operation to perform
1375 * @param p1 start_tile
1376 * @param p2 various bitstuffed elements
1377 * - p2 = bit 0 - if set keep the rail
1378 * @param waypoint remove from waypoints, else from stations
1379 * @return the cost of this operation or an error
1381 static CommandCost RemoveFromRailBaseStation (TileIndex start,
1382 DoCommandFlag flags, uint32 p1, uint32 p2, bool waypoint)
1384 TileIndex end = p1 == 0 ? start : p1;
1385 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1387 bool keep_rail = HasBit(p2, 0);
1389 TileArea ta(start, end);
1390 SmallVector<BaseStation *, 4> affected_stations;
1392 /* Count of the number of tiles removed */
1393 int quantity = 0;
1394 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1395 /* Accumulator for the errors seen during clearing. If no errors happen,
1396 * and the quantity is 0 there is no station. Otherwise it will be one
1397 * of the other error that got accumulated. */
1398 CommandCost error;
1400 /* Do the action for every tile into the area */
1401 TILE_AREA_LOOP(tile, ta) {
1402 /* Make sure the specified tile is a rail station */
1403 if (!HasStationTileRail(tile)) continue;
1405 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1406 CommandCost ret = EnsureNoVehicleOnGround(tile);
1407 error.AddCost(ret);
1408 if (ret.Failed()) continue;
1410 /* Check ownership of station */
1411 BaseStation *st = BaseStation::GetByTile (tile);
1412 if (st == NULL || st->IsWaypoint() != waypoint) continue;
1414 if (_current_company != OWNER_WATER) {
1415 CommandCost ret = CheckOwnership(st->owner);
1416 error.AddCost(ret);
1417 if (ret.Failed()) continue;
1420 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1421 quantity++;
1423 if (keep_rail || IsStationTileBlocked(tile)) {
1424 /* Don't refund the 'steel' of the track when we keep the
1425 * rail, or when the tile didn't have any rail at all. */
1426 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1429 if (flags & DC_EXEC) {
1430 /* read variables before the station tile is removed */
1431 uint specindex = GetCustomStationSpecIndex(tile);
1432 Track track = GetRailStationTrack(tile);
1433 Owner owner = GetTileOwner(tile);
1434 RailType rt = GetRailType(tile);
1435 Train *v = NULL;
1437 if (HasStationReservation(tile)) {
1438 v = GetTrainForReservation(tile, track);
1439 if (v != NULL) FreeTrainReservation(v);
1442 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1443 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1445 DoClearSquare(tile);
1446 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1447 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1448 Company::Get(owner)->infrastructure.station--;
1449 DirtyCompanyInfrastructureWindows(owner);
1451 st->AfterRemoveTile(tile);
1452 AddTrackToSignalBuffer(tile, track, owner);
1453 YapfNotifyTrackLayoutChange(tile, track);
1455 DeallocateSpecFromStation(st, specindex);
1457 affected_stations.Include(st);
1459 if (v != NULL) RestoreTrainReservation(v);
1463 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1465 for (BaseStation **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1466 BaseStation *st = *stp;
1468 /* now we need to make the "spanned" area of the railway station smaller
1469 * if we deleted something at the edges.
1470 * we also need to adjust train_tile. */
1471 st->train_station.shrink_span (std::bind1st (std::mem_fun (&BaseStation::TileBelongsToRailStation), st));
1472 UpdateStationSign (st);
1474 /* if we deleted the whole station, delete the train facility. */
1475 if (st->train_station.tile == INVALID_TILE) {
1476 st->facilities &= ~FACIL_TRAIN;
1477 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1478 DeleteStationIfEmpty(st);
1482 total_cost.AddCost(quantity * _price[waypoint ? PR_CLEAR_WAYPOINT_RAIL : PR_CLEAR_STATION_RAIL]);
1484 if (!waypoint) {
1485 /* Do all station specific functions here. */
1486 for (BaseStation **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1487 Station *st = Station::From(*stp);
1489 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1490 st->MarkTilesDirty(false);
1491 st->RecomputeIndustriesNear();
1495 return total_cost;
1499 * Remove a single tile from a rail station.
1500 * This allows for custom-built station with holes and weird layouts
1501 * @param start tile of station piece to remove
1502 * @param flags operation to perform
1503 * @param p1 start_tile
1504 * @param p2 various bitstuffed elements
1505 * - p2 = bit 0 - if set keep the rail
1506 * @param text unused
1507 * @return the cost of this operation or an error
1509 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1511 return RemoveFromRailBaseStation (start, flags, p1, p2, false);
1515 * Remove a single tile from a waypoint.
1516 * This allows for custom-built waypoint with holes and weird layouts
1517 * @param start tile of waypoint piece to remove
1518 * @param flags operation to perform
1519 * @param p1 start_tile
1520 * @param p2 various bitstuffed elements
1521 * - p2 = bit 0 - if set keep the rail
1522 * @param text unused
1523 * @return the cost of this operation or an error
1525 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1527 return RemoveFromRailBaseStation (start, flags, p1, p2, true);
1532 * Remove a rail station/waypoint
1533 * @param st The station/waypoint to remove the rail part from
1534 * @param flags operation to perform
1535 * @param removal_cost the cost for removing a tile
1536 * @return cost or failure of operation
1538 static CommandCost RemoveRailStation (BaseStation *st, DoCommandFlag flags,
1539 Money removal_cost)
1541 /* Current company owns the station? */
1542 if (_current_company != OWNER_WATER) {
1543 CommandCost ret = CheckOwnership(st->owner);
1544 if (ret.Failed()) return ret;
1547 /* determine width and height of platforms */
1548 TileArea ta = st->train_station;
1550 assert(ta.w != 0 && ta.h != 0);
1552 CommandCost cost(EXPENSES_CONSTRUCTION);
1553 /* clear all areas of the station */
1554 TILE_AREA_LOOP(tile, ta) {
1555 /* only remove tiles that are actually train station tiles */
1556 if (!st->TileBelongsToRailStation(tile)) continue;
1558 CommandCost ret = EnsureNoVehicleOnGround(tile);
1559 if (ret.Failed()) return ret;
1561 cost.AddCost(removal_cost);
1562 if (flags & DC_EXEC) {
1563 /* read variables before the station tile is removed */
1564 Track track = GetRailStationTrack(tile);
1565 Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
1566 Train *v = NULL;
1567 if (HasStationReservation(tile)) {
1568 v = FreeTrainReservation (tile, track);
1570 if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1571 Company::Get(owner)->infrastructure.station--;
1572 DoClearSquare(tile);
1573 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1574 AddTrackToSignalBuffer(tile, track, owner);
1575 YapfNotifyTrackLayoutChange(tile, track);
1576 if (v != NULL) TryPathReserve(v, true);
1580 if (flags & DC_EXEC) {
1581 st->AfterRemoveRect(st->train_station);
1583 st->train_station.Clear();
1585 st->facilities &= ~FACIL_TRAIN;
1587 free(st->speclist);
1588 st->num_specs = 0;
1589 st->speclist = NULL;
1590 st->cached_anim_triggers = 0;
1592 DirtyCompanyInfrastructureWindows(st->owner);
1593 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1594 UpdateStationSign (st);
1595 DeleteStationIfEmpty(st);
1598 return cost;
1602 * Remove a rail station
1603 * @param tile Tile of the station.
1604 * @param flags operation to perform
1605 * @return cost or failure of operation
1607 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1609 /* if there is flooding, remove platforms tile by tile */
1610 if (_current_company == OWNER_WATER) {
1611 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
1614 Station *st = Station::GetByTile(tile);
1615 CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1617 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
1619 return cost;
1623 * Remove a rail waypoint
1624 * @param tile Tile of the waypoint.
1625 * @param flags operation to perform
1626 * @return cost or failure of operation
1628 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1630 /* if there is flooding, remove waypoints tile by tile */
1631 if (_current_company == OWNER_WATER) {
1632 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
1635 return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1640 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1641 * @param st The Station to do the whole procedure for
1642 * @return a pointer to where to link a new RoadStop*
1644 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1646 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1648 if (*primary_stop == NULL) {
1649 /* we have no roadstop of the type yet, so write a "primary stop" */
1650 return primary_stop;
1651 } else {
1652 /* there are stops already, so append to the end of the list */
1653 RoadStop *stop = *primary_stop;
1654 while (stop->next != NULL) stop = stop->next;
1655 return &stop->next;
1659 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
1662 * Build a bus or truck stop.
1663 * @param tile Northernmost tile of the stop.
1664 * @param flags Operation to perform.
1665 * @param p1 bit 0..7: Width of the road stop.
1666 * bit 8..15: Length of the road stop.
1667 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1668 * bit 1: 0 For normal stops, 1 for drive-through.
1669 * bit 2..3: The roadtypes.
1670 * bit 5: Allow stations directly adjacent to other stations.
1671 * bit 6..7: Entrance direction (#DiagDirection).
1672 * bit 16..31: Station ID to join (NEW_STATION if build new one).
1673 * @param text Unused.
1674 * @return The cost of this operation or an error.
1676 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1678 bool type = HasBit(p2, 0);
1679 bool is_drive_through = HasBit(p2, 1);
1680 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
1681 StationID station_to_join = GB(p2, 16, 16);
1683 uint8 width = (uint8)GB(p1, 0, 8);
1684 uint8 lenght = (uint8)GB(p1, 8, 8);
1686 /* Check if the requested road stop is too big */
1687 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1688 /* Check for incorrect width / length. */
1689 if (width == 0 || lenght == 0) return CMD_ERROR;
1690 /* Check if the first tile and the last tile are valid */
1691 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
1693 TileArea roadstop_area(tile, width, lenght);
1695 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
1697 /* Trams only have drive through stops */
1698 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
1700 DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
1702 /* Safeguard the parameters. */
1703 if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
1704 /* If it is a drive-through stop, check for valid axis. */
1705 if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
1707 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
1708 if (ret.Failed()) return ret;
1710 /* Total road stop cost. */
1711 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
1712 StationID est = INVALID_STATION;
1713 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
1714 if (ret.Failed()) return ret;
1715 cost.AddCost(ret);
1717 Station *st = NULL;
1718 ret = BuildStationPart (&st, roadstop_area, est, station_to_join,
1719 HasBit (p2, 5), STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST,
1720 flags, STATIONNAMING_ROAD);
1721 if (ret.Failed()) return ret;
1723 /* Check if this number of road stops can be allocated. */
1724 if (!RoadStop::CanAllocateItem(roadstop_area.w * roadstop_area.h)) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
1726 if (flags & DC_EXEC) {
1727 /* Check every tile in the area. */
1728 TILE_AREA_LOOP(cur_tile, roadstop_area) {
1729 RoadTypes cur_rts = (IsRoadTile(cur_tile) || IsStationTile(cur_tile)) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
1730 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
1731 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
1733 if (IsStationTile(cur_tile) && IsRoadStop(cur_tile)) {
1734 RemoveRoadStop(cur_tile, flags);
1737 RoadStop *road_stop = new RoadStop(cur_tile);
1738 /* Insert into linked list of RoadStops. */
1739 RoadStop **currstop = FindRoadStopSpot(type, st);
1740 *currstop = road_stop;
1742 if (type) {
1743 st->truck_station.Add(cur_tile);
1744 } else {
1745 st->bus_station.Add(cur_tile);
1748 /* Initialize an empty station. */
1749 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
1751 st->rect.Add (cur_tile);
1753 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
1754 if (is_drive_through) {
1755 /* Update company infrastructure counts. If the current tile is a normal
1756 * road tile, count only the new road bits needed to get a full diagonal road. */
1757 RoadType rt;
1758 FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
1759 Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
1760 if (c != NULL) {
1761 c->infrastructure.road[rt] += 2 - (IsRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
1762 DirtyCompanyInfrastructureWindows(c->index);
1766 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
1767 road_stop->MakeDriveThrough();
1768 } else {
1769 /* Non-drive-through stop never overbuild and always count as two road bits. */
1770 Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
1771 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
1773 Company::Get(st->owner)->infrastructure.station++;
1774 DirtyCompanyInfrastructureWindows(st->owner);
1776 MarkTileDirtyByTile(cur_tile);
1780 if (st != NULL) {
1781 st->UpdateVirtCoord();
1782 UpdateStationAcceptance(st, false);
1783 st->RecomputeIndustriesNear();
1784 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
1785 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
1786 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
1788 return cost;
1793 * Remove a bus station/truck stop
1794 * @param tile TileIndex been queried
1795 * @param flags operation to perform
1796 * @return cost or failure of operation
1798 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
1800 Station *st = Station::GetByTile(tile);
1802 if (_current_company != OWNER_WATER) {
1803 CommandCost ret = CheckOwnership(st->owner);
1804 if (ret.Failed()) return ret;
1807 bool is_truck = IsTruckStop(tile);
1809 RoadStop **primary_stop;
1810 RoadStop *cur_stop;
1811 if (is_truck) { // truck stop
1812 primary_stop = &st->truck_stops;
1813 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
1814 } else {
1815 primary_stop = &st->bus_stops;
1816 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
1819 assert(cur_stop != NULL);
1821 /* don't do the check for drive-through road stops when company bankrupts */
1822 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
1823 /* remove the 'going through road stop' status from all vehicles on that tile */
1824 VehicleTileIterator iter (tile);
1825 while (!iter.finished()) {
1826 Vehicle *v = iter.next();
1827 if (v->type == VEH_ROAD) {
1828 /* Okay... we are a road vehicle on a drive through road stop.
1829 * But that road stop has just been removed, so we need to make
1830 * sure we are in a valid state... however, vehicles can also
1831 * turn on road stop tiles, so only clear the 'road stop' state
1832 * bits and only when the state was 'in road stop', otherwise
1833 * we'll end up clearing the turn around bits. */
1834 RoadVehicle *rv = RoadVehicle::From(v);
1835 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
1838 } else {
1839 CommandCost ret = EnsureNoVehicleOnGround(tile);
1840 if (ret.Failed()) return ret;
1843 if (flags & DC_EXEC) {
1844 if (*primary_stop == cur_stop) {
1845 /* removed the first stop in the list */
1846 *primary_stop = cur_stop->next;
1847 /* removed the only stop? */
1848 if (*primary_stop == NULL) {
1849 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
1851 } else {
1852 /* tell the predecessor in the list to skip this stop */
1853 RoadStop *pred = *primary_stop;
1854 while (pred->next != cur_stop) pred = pred->next;
1855 pred->next = cur_stop->next;
1858 /* Update company infrastructure counts. */
1859 RoadType rt;
1860 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
1861 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
1862 if (c != NULL) {
1863 c->infrastructure.road[rt] -= 2;
1864 DirtyCompanyInfrastructureWindows(c->index);
1867 Company::Get(st->owner)->infrastructure.station--;
1869 if (IsDriveThroughStopTile(tile)) {
1870 /* Clears the tile for us */
1871 cur_stop->ClearDriveThrough();
1872 } else {
1873 DoClearSquare(tile);
1876 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
1877 delete cur_stop;
1879 /* Make sure no vehicle is going to the old roadstop */
1880 RoadVehicle *v;
1881 FOR_ALL_ROADVEHICLES(v) {
1882 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
1883 v->dest_tile == tile) {
1884 v->dest_tile = v->GetOrderStationLocation(st->index);
1888 st->AfterRemoveTile(tile);
1890 UpdateStationSign (st);
1891 st->RecomputeIndustriesNear();
1892 DeleteStationIfEmpty(st);
1894 /* Update the tile area of the truck/bus stop */
1895 if (is_truck) {
1896 st->truck_station.Clear();
1897 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
1898 } else {
1899 st->bus_station.Clear();
1900 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
1904 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
1908 * Remove bus or truck stops.
1909 * @param tile Northernmost tile of the removal area.
1910 * @param flags Operation to perform.
1911 * @param p1 bit 0..7: Width of the removal area.
1912 * bit 8..15: Height of the removal area.
1913 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1914 * @param p2 bit 1: 0 to keep roads of all drive-through stops, 1 to remove them.
1915 * @param text Unused.
1916 * @return The cost of this operation or an error.
1918 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1920 uint8 width = (uint8)GB(p1, 0, 8);
1921 uint8 height = (uint8)GB(p1, 8, 8);
1922 bool keep_drive_through_roads = !HasBit(p2, 1);
1924 /* Check for incorrect width / height. */
1925 if (width == 0 || height == 0) return CMD_ERROR;
1926 /* Check if the first tile and the last tile are valid */
1927 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
1928 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
1929 if (!keep_drive_through_roads && (flags & DC_BANKRUPT)) return CMD_ERROR;
1931 TileArea roadstop_area(tile, width, height);
1933 CommandCost cost(EXPENSES_CONSTRUCTION);
1934 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
1935 bool had_success = false;
1937 TILE_AREA_LOOP(cur_tile, roadstop_area) {
1938 /* Make sure the specified tile is a road stop of the correct type */
1939 if (!IsStationTile(cur_tile) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
1941 /* Save information on to-be-restored roads before the stop is removed. */
1942 RoadTypes rts = ROADTYPES_NONE;
1943 RoadBits road_bits = ROAD_NONE;
1944 Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
1945 assert_compile(lengthof(road_owner) == ROADTYPE_END);
1946 if (IsDriveThroughStopTile(cur_tile)) {
1947 RoadType rt;
1948 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(cur_tile)) {
1949 road_owner[rt] = GetRoadOwner(cur_tile, rt);
1950 /* If we don't want to preserve our roads then restore only roads of others. */
1951 if (keep_drive_through_roads || road_owner[rt] != _current_company) SetBit(rts, rt);
1953 road_bits = AxisToRoadBits (GetRoadStopAxis (cur_tile));
1956 CommandCost ret = RemoveRoadStop(cur_tile, flags);
1957 if (ret.Failed()) {
1958 last_error = ret;
1959 continue;
1961 cost.AddCost(ret);
1962 had_success = true;
1964 /* Restore roads. */
1965 if ((flags & DC_EXEC) && rts != ROADTYPES_NONE) {
1966 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile)->index,
1967 road_owner[ROADTYPE_ROAD], road_owner[ROADTYPE_TRAM]);
1969 /* Update company infrastructure counts. */
1970 RoadType rt;
1971 FOR_EACH_SET_ROADTYPE(rt, rts) {
1972 Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
1973 if (c != NULL) {
1974 c->infrastructure.road[rt] += CountBits(road_bits);
1975 DirtyCompanyInfrastructureWindows(c->index);
1981 return had_success ? cost : last_error;
1985 * Computes the minimal distance from town's xy to any airport's tile.
1986 * @param it An iterator over all airport tiles.
1987 * @param town_tile town's tile (t->xy)
1988 * @return minimal manhattan distance from town_tile to any airport's tile
1990 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
1992 uint mindist = UINT_MAX;
1994 for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
1995 mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
1998 return mindist;
2002 * Get a possible noise reduction factor based on distance from town center.
2003 * The further you get, the less noise you generate.
2004 * So all those folks at city council can now happily slee... work in their offices
2005 * @param as airport information
2006 * @param it An iterator over all airport tiles.
2007 * @param town_tile TileIndex of town's center, the one who will receive the airport's candidature
2008 * @return the noise that will be generated, according to distance
2010 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
2012 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2013 * So no need to go any further*/
2014 if (as->noise_level < 2) return as->noise_level;
2016 uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
2018 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2019 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2020 * Basically, it says that the less tolerant a town is, the bigger the distance before
2021 * an actual decrease can be granted */
2022 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2024 /* now, we want to have the distance segmented using the distance judged bareable by town
2025 * This will give us the coefficient of reduction the distance provides. */
2026 uint noise_reduction = distance / town_tolerance_distance;
2028 /* If the noise reduction equals the airport noise itself, don't give it for free.
2029 * Otherwise, simply reduce the airport's level. */
2030 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2034 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2035 * If two towns have the same distance, town with lower index is returned.
2036 * @param as airport's description
2037 * @param it An iterator over all airport tiles
2038 * @return nearest town to airport
2040 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
2042 Town *t, *nearest = NULL;
2043 uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2044 uint mindist = UINT_MAX - add; // prevent overflow
2045 FOR_ALL_TOWNS(t) {
2046 if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
2047 TileIterator *copy = it.Clone();
2048 uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
2049 delete copy;
2050 if (dist < mindist) {
2051 nearest = t;
2052 mindist = dist;
2057 return nearest;
2061 /** Recalculate the noise generated by the airports of each town */
2062 void UpdateAirportsNoise()
2064 Town *t;
2065 const Station *st;
2067 FOR_ALL_TOWNS(t) t->noise_reached = 0;
2069 FOR_ALL_STATIONS(st) {
2070 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2071 const AirportSpec *as = st->airport.GetSpec();
2072 AirportTileIterator it(st);
2073 Town *nearest = AirportGetNearestTown(as, it);
2074 nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
2081 * Checks if an airport can be removed (no aircraft on it or landing)
2082 * @param st Station whose airport is to be removed
2083 * @param flags Operation to perform
2084 * @return Cost or failure of operation
2086 static CommandCost CanRemoveAirport(Station *st, DoCommandFlag flags)
2088 const Aircraft *a;
2089 FOR_ALL_AIRCRAFT(a) {
2090 if (!a->IsNormalAircraft()) continue;
2091 if (a->targetairport == st->index && a->state != FLYING)
2092 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2095 CommandCost cost(EXPENSES_CONSTRUCTION);
2097 TILE_AREA_LOOP(tile_cur, st->airport) {
2098 if (!st->TileBelongsToAirport(tile_cur)) continue;
2100 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2101 if (ret.Failed()) return ret;
2103 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2106 return cost;
2111 * Place an Airport.
2112 * @param tile tile where airport will be built
2113 * @param flags operation to perform
2114 * @param p1
2115 * - p1 = (bit 0- 7) - airport type, @see airport.h
2116 * - p1 = (bit 8-15) - airport layout
2117 * @param p2 various bitstuffed elements
2118 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2119 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2120 * @param text unused
2121 * @return the cost of this operation or an error
2123 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2125 StationID station_to_join = GB(p2, 16, 16);
2126 byte airport_type = GB(p1, 0, 8);
2127 byte layout = GB(p1, 8, 8);
2129 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2131 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2132 if (ret.Failed()) return ret;
2134 /* Check if a valid, buildable airport was chosen for construction */
2135 const AirportSpec *as = AirportSpec::Get(airport_type);
2136 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
2138 Direction rotation = as->rotation[layout];
2139 int w = as->size_x;
2140 int h = as->size_y;
2141 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2142 TileArea airport_area = TileArea(tile, w, h);
2144 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2145 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2148 StationID est = INVALID_STATION;
2149 CommandCost cost = CheckFlatLandAirport(airport_area, flags, &est);
2150 if (cost.Failed()) return cost;
2152 Station *st = NULL;
2153 ret = BuildStationPart (&st, airport_area, est, station_to_join,
2154 HasBit (p2, 0), STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST,
2155 flags, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2156 if (ret.Failed()) return ret;
2158 /* action to be performed */
2159 enum {
2160 AIRPORT_NEW, // airport is a new station
2161 AIRPORT_ADD, // add an airport to an existing station
2162 AIRPORT_UPGRADE, // upgrade the airport in a station
2163 } action =
2164 (est != INVALID_STATION) ? AIRPORT_UPGRADE :
2165 (st != NULL) ? AIRPORT_ADD : AIRPORT_NEW;
2167 if (action == AIRPORT_ADD && st->airport.tile != INVALID_TILE) {
2168 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2171 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2172 AirportTileTableIterator iter(as->table[layout], tile);
2173 Town *nearest = AirportGetNearestTown(as, iter);
2174 uint newnoise_level = nearest->noise_reached + GetAirportNoiseLevelForTown(as, iter, nearest->xy);
2176 if (action == AIRPORT_UPGRADE) {
2177 const AirportSpec *old_as = st->airport.GetSpec();
2178 AirportTileTableIterator old_iter(old_as->table[st->airport.layout], st->airport.tile);
2179 Town *old_nearest = AirportGetNearestTown(old_as, old_iter);
2180 if (old_nearest == nearest) {
2181 newnoise_level -= GetAirportNoiseLevelForTown(old_as, old_iter, nearest->xy);
2185 /* Check if local auth would allow a new airport */
2186 StringID authority_refuse_message = STR_NULL;
2187 Town *authority_refuse_town = NULL;
2189 if (_settings_game.economy.station_noise_level) {
2190 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2191 if (newnoise_level > nearest->MaxTownNoise()) {
2192 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2193 authority_refuse_town = nearest;
2195 } else if (action != AIRPORT_UPGRADE) {
2196 Town *t = ClosestTownFromTile(tile);
2197 uint num = 0;
2198 const Station *st;
2199 FOR_ALL_STATIONS(st) {
2200 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2202 if (num >= 2) {
2203 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2204 authority_refuse_town = t;
2208 if (authority_refuse_message != STR_NULL) {
2209 SetDParam(0, authority_refuse_town->index);
2210 return_cmd_error(authority_refuse_message);
2213 if (action == AIRPORT_UPGRADE) {
2214 /* check that the old airport can be removed */
2215 CommandCost r = CanRemoveAirport(st, flags);
2216 if (r.Failed()) return r;
2217 cost.AddCost(r);
2220 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2221 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2224 if (flags & DC_EXEC) {
2225 if (action == AIRPORT_UPGRADE) {
2226 /* delete old airport if upgrading */
2227 const AirportSpec *old_as = st->airport.GetSpec();
2228 AirportTileTableIterator old_iter(old_as->table[st->airport.layout], st->airport.tile);
2229 Town *old_nearest = AirportGetNearestTown(old_as, old_iter);
2231 if (old_nearest != nearest) {
2232 old_nearest->noise_reached -= GetAirportNoiseLevelForTown(old_as, old_iter, old_nearest->xy);
2233 if (_settings_game.economy.station_noise_level) {
2234 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2238 TILE_AREA_LOOP(tile_cur, st->airport) {
2239 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
2240 DeleteAnimatedTile(tile_cur);
2241 DoClearSquare(tile_cur);
2242 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2245 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2246 DeleteWindowById(
2247 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
2251 st->AfterRemoveRect(st->airport);
2252 st->airport.Clear();
2255 /* Always add the noise, so there will be no need to recalculate when option toggles */
2256 nearest->noise_reached = newnoise_level;
2258 st->AddFacility(FACIL_AIRPORT, tile);
2259 st->airport.type = airport_type;
2260 st->airport.layout = layout;
2261 st->airport.flags = 0;
2262 st->airport.rotation = rotation;
2264 st->rect.Add (TileArea (tile, w, h));
2266 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2267 MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2268 SetStationTileRandomBits(iter, GB(Random(), 0, 4));
2269 st->airport.Add(iter);
2271 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
2274 /* Only call the animation trigger after all tiles have been built */
2275 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2276 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2279 if (action != AIRPORT_NEW) UpdateAirplanesOnNewStation(st);
2281 if (action == AIRPORT_UPGRADE) {
2282 UpdateStationSign (st);
2283 } else {
2284 Company::Get(st->owner)->infrastructure.airport++;
2285 DirtyCompanyInfrastructureWindows(st->owner);
2286 st->UpdateVirtCoord();
2289 UpdateStationAcceptance(st, false);
2290 st->RecomputeIndustriesNear();
2291 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
2292 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
2293 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2295 if (_settings_game.economy.station_noise_level) {
2296 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2300 return cost;
2304 * Remove an airport
2305 * @param tile TileIndex been queried
2306 * @param flags operation to perform
2307 * @return cost or failure of operation
2309 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2311 Station *st = Station::GetByTile(tile);
2313 if (_current_company != OWNER_WATER) {
2314 CommandCost ret = CheckOwnership(st->owner);
2315 if (ret.Failed()) return ret;
2318 CommandCost cost = CanRemoveAirport(st, flags);
2319 if (cost.Failed()) return cost;
2321 if (flags & DC_EXEC) {
2322 const AirportSpec *as = st->airport.GetSpec();
2323 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2324 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2325 * need of recalculation */
2326 AirportTileIterator it(st);
2327 Town *nearest = AirportGetNearestTown(as, it);
2328 nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
2330 TILE_AREA_LOOP(tile_cur, st->airport) {
2331 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
2332 DeleteAnimatedTile(tile_cur);
2333 DoClearSquare(tile_cur);
2334 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2337 /* Clear the persistent storage. */
2338 delete st->airport.psa;
2340 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2341 DeleteWindowById(
2342 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
2346 st->AfterRemoveRect(st->airport);
2348 st->airport.Clear();
2349 st->facilities &= ~FACIL_AIRPORT;
2351 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2353 if (_settings_game.economy.station_noise_level) {
2354 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2357 Company::Get(st->owner)->infrastructure.airport--;
2358 DirtyCompanyInfrastructureWindows(st->owner);
2360 UpdateStationSign (st);
2361 st->RecomputeIndustriesNear();
2362 DeleteStationIfEmpty(st);
2363 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2366 return cost;
2370 * Open/close an airport to incoming aircraft.
2371 * @param tile Unused.
2372 * @param flags Operation to perform.
2373 * @param p1 Station ID of the airport.
2374 * @param p2 Unused.
2375 * @param text unused
2376 * @return the cost of this operation or an error
2378 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2380 if (!Station::IsValidID(p1)) return CMD_ERROR;
2381 Station *st = Station::Get(p1);
2383 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2385 CommandCost ret = CheckOwnership(st->owner);
2386 if (ret.Failed()) return ret;
2388 if (flags & DC_EXEC) {
2389 st->airport.flags ^= AIRPORT_CLOSED_block;
2390 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2392 return CommandCost();
2396 * Tests whether the company's vehicles have this station in orders
2397 * @param station station ID
2398 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2399 * @param company company ID
2401 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2403 const Vehicle *v;
2404 FOR_ALL_VEHICLES(v) {
2405 if ((v->owner == company) == include_company) {
2406 const Order *order;
2407 FOR_VEHICLE_ORDERS(v, order) {
2408 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
2409 return true;
2414 return false;
2417 /** Information about dock tile area for a given direction. */
2418 struct DockTileArea {
2419 CoordDiff offset; ///< offset to northern tile
2420 byte width; ///< width of dock area
2421 byte height; ///< height of dock area
2425 * Build a dock/haven.
2426 * @param tile tile where dock will be built
2427 * @param flags operation to perform
2428 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
2429 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
2430 * @param text unused
2431 * @return the cost of this operation or an error
2433 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2435 static const DockTileArea dock_tilearea[DIAGDIR_END] = {
2436 { { -1, 0 }, 2, 1 },
2437 { { 0, 0 }, 1, 2 },
2438 { { 0, 0 }, 2, 1 },
2439 { { 0, -1 }, 1, 2 },
2442 StationID station_to_join = GB(p2, 16, 16);
2444 Slope slope = GetTileSlope (tile);
2445 DiagDirection direction = GetInclinedSlopeDirection (slope);
2446 TileArea dock_area;
2447 WaterClass wc;
2448 if (direction != INVALID_DIAGDIR) {
2449 /* Docks cannot be placed on rapids */
2450 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2452 direction = ReverseDiagDir(direction);
2454 if (HasBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2456 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2457 if (ret.Failed()) return ret;
2459 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2460 if (ret.Failed()) return ret;
2462 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2464 if (!IsWaterTile(tile_cur) || !IsTileFlat(tile_cur)) {
2465 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2468 if (HasBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2470 /* Get the water class of the water tile before it is cleared.*/
2471 wc = GetWaterClass (tile_cur);
2473 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2474 if (ret.Failed()) return ret;
2476 tile_cur += TileOffsByDiagDir(direction);
2477 if (!IsWaterTile(tile_cur) || !IsTileFlat(tile_cur)) {
2478 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2481 dock_area = TileArea(tile + ToTileIndexDiff(dock_tilearea[direction].offset),
2482 dock_tilearea[direction].width, dock_tilearea[direction].height);
2483 } else if (slope == SLOPE_FLAT) {
2484 if (!HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2486 if (HasBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2488 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2489 if (ret.Failed()) return ret;
2491 /* Get the water class of the water tile before it is cleared.*/
2492 wc = GetWaterClass (tile);
2493 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2494 if (ret.Failed()) return ret;
2496 dock_area = TileArea (tile);
2497 } else {
2498 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2501 /* middle */
2502 Station *st = NULL;
2503 CommandCost ret = BuildStationPart (&st, dock_area, INVALID_STATION,
2504 station_to_join, HasBit (p1, 0), INVALID_STRING_ID,
2505 flags, STATIONNAMING_DOCK);
2506 if (ret.Failed()) return ret;
2508 /* Check if we can allocate a new dock. */
2509 if (!Dock::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_DOCKS);
2511 if (flags & DC_EXEC) {
2512 Dock **dl = &st->docks;
2513 while (*dl != NULL) dl = &(*dl)->next;
2515 *dl = new Dock(tile);
2516 st->dock_area.Add(dock_area);
2518 st->AddFacility(FACIL_DOCK, tile);
2520 st->rect.Add (dock_area);
2522 /* If the water part of the dock is on a canal, update infrastructure counts.
2523 * This is needed as we've unconditionally cleared that tile before. */
2524 if (wc == WATER_CLASS_CANAL) {
2525 Company::Get(st->owner)->infrastructure.water++;
2527 Company::Get(st->owner)->infrastructure.station += 2;
2528 DirtyCompanyInfrastructureWindows(st->owner);
2530 if (direction != INVALID_DIAGDIR) {
2531 MakeDock (tile, st->owner, st->index, direction, wc);
2532 } else {
2533 MakeDockBuoy (tile, st->owner, st->index, wc);
2536 st->UpdateVirtCoord();
2537 UpdateStationAcceptance(st, false);
2538 st->RecomputeIndustriesNear();
2539 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
2540 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
2541 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
2544 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2548 * Remove a dock
2549 * @param tile TileIndex been queried
2550 * @param flags operation to perform
2551 * @return cost or failure of operation
2553 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2555 assert(IsDock(tile));
2557 Station *st = Station::GetByTile(tile);
2558 CommandCost ret = CheckOwnership(st->owner);
2559 if (ret.Failed()) return ret;
2561 Dock **d = &st->docks;
2562 TileIndex tile1, tile2;
2563 while ( tile1 = (*d)->xy, tile2 = GetOtherDockTile(tile1),
2564 tile != tile1 && tile != tile2 ) {
2565 /* the dock should really be there, so no check for NULL */
2566 d = &(*d)->next;
2569 ret = EnsureNoVehicleOnGround(tile1);
2570 if (ret.Succeeded() && tile2 != INVALID_TILE) ret = EnsureNoVehicleOnGround(tile2);
2571 if (ret.Failed()) return ret;
2573 if (flags & DC_EXEC) {
2574 TileIndex docking_location = GetDockingTile(tile1);
2576 TileArea dock_area (tile1);
2577 if (tile2 != INVALID_TILE) {
2578 DoClearSquare (tile1);
2579 MarkTileDirtyByTile (tile1);
2580 MakeWaterKeepingClass (tile2, st->owner);
2581 dock_area.Add (tile2);
2582 } else {
2583 MakeWaterKeepingClass (tile1, st->owner);
2585 st->AfterRemoveRect (dock_area);
2587 Dock *next = (*d)->next;
2588 delete *d;
2589 *d = next;
2590 if (next == NULL && d == &st->docks) st->facilities &= ~FACIL_DOCK;
2592 Company::Get(st->owner)->infrastructure.station -= 2;
2593 DirtyCompanyInfrastructureWindows(st->owner);
2595 /* Update the tile area of the docks */
2596 st->dock_area.Clear();
2597 for (const Dock *dock = st->docks; dock != NULL; dock = dock->next) {
2598 st->dock_area.Add(dock->xy);
2599 TileIndex other = GetOtherDockTile (dock->xy);
2600 if (other != INVALID_TILE) st->dock_area.Add (other);
2603 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
2604 UpdateStationSign (st);
2605 st->RecomputeIndustriesNear();
2606 DeleteStationIfEmpty(st);
2608 /* All ships that were going to our station, can't go to it anymore.
2609 * Just clear the order, then automatically the next appropriate order
2610 * will be selected and in case of no appropriate order it will just
2611 * wander around the world. */
2612 Ship *s;
2613 FOR_ALL_SHIPS(s) {
2614 if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
2615 s->LeaveStation();
2618 if (s->dest_tile == docking_location) {
2619 s->dest_tile = 0;
2620 s->current_order.Clear();
2625 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
2628 #include "table/station_land.h"
2630 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
2632 return &_station_display_datas[st][gfx];
2636 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
2637 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
2638 * is set to the overlay to draw.
2639 * @param ti Positional info for the tile to decide snowyness etc. May be NULL.
2640 * @param [in,out] ground Groundsprite to draw.
2641 * @param [out] overlay_offset Overlay to draw.
2642 * @return true if overlay can be drawn.
2644 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
2646 bool snow_desert;
2647 switch (*ground) {
2648 case SPR_RAIL_TRACK_X:
2649 snow_desert = false;
2650 *overlay_offset = RTO_X;
2651 break;
2653 case SPR_RAIL_TRACK_Y:
2654 snow_desert = false;
2655 *overlay_offset = RTO_Y;
2656 break;
2658 case SPR_RAIL_TRACK_X_SNOW:
2659 snow_desert = true;
2660 *overlay_offset = RTO_X;
2661 break;
2663 case SPR_RAIL_TRACK_Y_SNOW:
2664 snow_desert = true;
2665 *overlay_offset = RTO_Y;
2666 break;
2668 default:
2669 return false;
2672 if (ti != NULL) {
2673 /* Decide snow/desert from tile */
2674 switch (_settings_game.game_creation.landscape) {
2675 case LT_ARCTIC:
2676 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
2677 break;
2679 case LT_TROPIC:
2680 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
2681 break;
2683 default:
2684 break;
2688 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
2689 return true;
2692 static void DrawTile_Station(TileInfo *ti)
2694 const NewGRFSpriteLayout *layout = NULL;
2695 DrawTileSprites tmp_rail_layout;
2696 const DrawTileSprites *t = NULL;
2697 RoadTypes roadtypes;
2698 int32 total_offset;
2699 const RailtypeInfo *rti = NULL;
2700 uint32 relocation = 0;
2701 uint32 ground_relocation = 0;
2702 BaseStation *st = NULL;
2703 const StationSpec *statspec = NULL;
2704 uint tile_layout = 0;
2706 if (HasStationRail(ti->tile)) {
2707 rti = GetRailTypeInfo(GetRailType(ti->tile));
2708 roadtypes = ROADTYPES_NONE;
2709 total_offset = rti->GetRailtypeSpriteOffset();
2711 if (IsCustomStationSpecIndex(ti->tile)) {
2712 /* look for customization */
2713 st = BaseStation::GetByTile(ti->tile);
2714 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
2716 if (statspec != NULL) {
2717 tile_layout = GetStationGfx(ti->tile);
2719 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
2720 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
2721 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
2724 /* Ensure the chosen tile layout is valid for this custom station */
2725 if (statspec->renderdata != NULL) {
2726 layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
2727 if (!layout->NeedsPreprocessing()) {
2728 t = layout;
2729 layout = NULL;
2734 } else {
2735 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
2736 total_offset = 0;
2739 StationGfx gfx = GetStationGfx(ti->tile);
2740 if (IsAirport(ti->tile)) {
2741 gfx = GetAirportGfx(ti->tile);
2742 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
2743 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
2744 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
2745 return;
2747 /* No sprite group (or no valid one) found, meaning no graphics associated.
2748 * Use the substitute one instead */
2749 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
2750 gfx = ats->grf_prop.subst_id;
2752 switch (gfx) {
2753 case APT_RADAR_GRASS_FENCE_SW:
2754 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
2755 break;
2756 case APT_GRASS_FENCE_NE_FLAG:
2757 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
2758 break;
2759 case APT_RADAR_FENCE_SW:
2760 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
2761 break;
2762 case APT_RADAR_FENCE_NE:
2763 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
2764 break;
2765 case APT_GRASS_FENCE_NE_FLAG_2:
2766 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
2767 break;
2771 Owner owner = GetTileOwner(ti->tile);
2773 PaletteID palette;
2774 if (Company::IsValidID(owner)) {
2775 palette = COMPANY_SPRITE_COLOUR(owner);
2776 } else {
2777 /* Some stations are not owner by a company, namely oil rigs */
2778 palette = PALETTE_TO_GREY;
2781 if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
2783 /* don't show foundation for docks */
2784 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
2785 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
2786 /* Station has custom foundations.
2787 * Check whether the foundation continues beyond the tile's upper sides. */
2788 uint edge_info = 0;
2789 int z;
2790 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
2791 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
2792 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
2793 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
2794 if (image == 0) goto draw_default_foundation;
2796 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
2797 /* Station provides extended foundations. */
2799 static const uint8 foundation_parts[] = {
2800 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2801 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2802 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2803 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2806 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2807 } else {
2808 /* Draw simple foundations, built up from 8 possible foundation sprites. */
2810 /* Each set bit represents one of the eight composite sprites to be drawn.
2811 * 'Invalid' entries will not drawn but are included for completeness. */
2812 static const uint8 composite_foundation_parts[] = {
2813 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2814 0x00, 0xD1, 0xE4, 0xE0,
2815 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2816 0xCA, 0xC9, 0xC4, 0xC0,
2817 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2818 0xD2, 0x91, 0xE4, 0xA0,
2819 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2820 0x4A, 0x09, 0x44
2823 uint8 parts = composite_foundation_parts[ti->tileh];
2825 /* If foundations continue beyond the tile's upper sides then
2826 * mask out the last two pieces. */
2827 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
2828 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
2830 if (parts == 0) {
2831 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2832 * correct offset for the childsprites.
2833 * So, draw the (completely empty) sprite of the default foundations. */
2834 goto draw_default_foundation;
2837 StartSpriteCombine();
2838 for (int i = 0; i < 8; i++) {
2839 if (HasBit(parts, i)) {
2840 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2843 EndSpriteCombine();
2846 OffsetGroundSprite(31, 1);
2847 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
2848 } else {
2849 draw_default_foundation:
2850 DrawFoundation(ti, FOUNDATION_LEVELED);
2854 if (IsBuoy(ti->tile) || (IsDock(ti->tile) && IsDockBuoy(ti->tile))) {
2855 DrawWaterClassGround(ti);
2856 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
2857 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
2858 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
2859 if (ti->tileh == SLOPE_FLAT) {
2860 DrawWaterClassGround(ti);
2861 } else {
2862 assert(IsDock(ti->tile));
2863 TileIndex water_tile = GetOtherDockTile (ti->tile);
2864 WaterClass wc = GetWaterClass(water_tile);
2865 if (wc == WATER_CLASS_SEA) {
2866 DrawShoreTile(ti->tileh);
2867 } else {
2868 DrawClearLandTile(ti, 3);
2871 } else {
2872 if (layout != NULL) {
2873 /* Sprite layout which needs preprocessing */
2874 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
2875 uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
2876 uint8 var10;
2877 FOR_EACH_SET_BIT(var10, var10_values) {
2878 uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
2879 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
2881 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
2882 t = &tmp_rail_layout;
2883 total_offset = 0;
2884 } else if (statspec != NULL) {
2885 /* Simple sprite layout */
2886 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
2887 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
2888 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
2890 ground_relocation += rti->fallback_railtype;
2893 SpriteID image = t->ground.sprite;
2894 PaletteID pal = t->ground.pal;
2895 RailTrackOffset overlay_offset;
2896 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
2897 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2898 DrawGroundSprite(image, PAL_NONE);
2899 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
2901 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
2902 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2903 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
2905 } else {
2906 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
2907 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
2908 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
2910 /* PBS debugging, draw reserved tracks darker */
2911 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
2912 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2913 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
2918 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
2920 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
2921 Axis axis = GetRoadStopAxis(ti->tile); // tram stops are always drive-through
2922 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
2923 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
2926 if (IsRailWaypoint(ti->tile)) {
2927 /* Don't offset the waypoint graphics; they're always the same. */
2928 total_offset = 0;
2931 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
2934 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
2936 int32 total_offset = 0;
2937 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
2938 const DrawTileSprites *t = GetStationTileLayout(st, image);
2939 const RailtypeInfo *rti = NULL;
2941 if (railtype != INVALID_RAILTYPE) {
2942 rti = GetRailTypeInfo(railtype);
2943 total_offset = rti->GetRailtypeSpriteOffset();
2946 SpriteID img = t->ground.sprite;
2947 RailTrackOffset overlay_offset;
2948 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
2949 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
2950 DrawSprite(img, PAL_NONE, x, y);
2951 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
2952 } else {
2953 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
2956 if (roadtype == ROADTYPE_TRAM) {
2957 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
2960 /* Default waypoint has no railtype specific sprites */
2961 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
2964 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
2966 return GetTileMaxPixelZ(tile);
2969 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
2971 return FlatteningFoundation(tileh);
2974 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
2976 td->owner[0] = GetTileOwner(tile);
2977 if (IsDriveThroughStopTile(tile)) {
2978 Owner road_owner = INVALID_OWNER;
2979 Owner tram_owner = INVALID_OWNER;
2980 RoadTypes rts = GetRoadTypes(tile);
2981 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
2982 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
2984 /* Is there a mix of owners? */
2985 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
2986 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
2987 uint i = 1;
2988 if (road_owner != INVALID_OWNER) {
2989 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
2990 td->owner[i] = road_owner;
2991 i++;
2993 if (tram_owner != INVALID_OWNER) {
2994 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
2995 td->owner[i] = tram_owner;
2999 td->build_date = BaseStation::GetByTile(tile)->build_date;
3001 if (HasStationTileRail(tile)) {
3002 const StationSpec *spec = GetStationSpec(tile);
3004 if (spec != NULL) {
3005 td->station_class = StationClass::Get(spec->cls_id)->name;
3006 td->station_name = spec->name;
3008 if (spec->grf_prop.grffile != NULL) {
3009 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3010 td->grf = gc->GetName();
3014 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3015 td->rail_speed = rti->max_speed;
3018 if (IsAirport(tile)) {
3019 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3020 td->airport_class = AirportClass::Get(as->cls_id)->name;
3021 td->airport_name = as->name;
3023 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3024 td->airport_tile_name = ats->name;
3026 if (as->grf_prop.grffile != NULL) {
3027 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3028 td->grf = gc->GetName();
3029 } else if (ats->grf_prop.grffile != NULL) {
3030 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3031 td->grf = gc->GetName();
3035 StringID str;
3036 switch (GetStationType(tile)) {
3037 default: NOT_REACHED();
3038 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3039 case STATION_AIRPORT:
3040 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3041 break;
3042 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3043 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3044 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
3045 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3046 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3047 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3049 td->str = str;
3053 static TrackStatus GetTileRailwayStatus_Station(TileIndex tile, DiagDirection side)
3055 if (!HasStationRail(tile) || IsStationTileBlocked(tile)) return 0;
3057 return CombineTrackStatus(TrackBitsToTrackdirBits(GetRailStationTrackBits(tile)), TRACKDIR_BIT_NONE);
3060 static TrackStatus GetTileRoadStatus_Station(TileIndex tile, uint sub_mode, DiagDirection side)
3062 if (!IsRoadStop(tile) || (GetRoadTypes(tile) & sub_mode) == 0) return 0;
3064 TrackBits trackbits;
3066 if (IsStandardRoadStopTile(tile)) {
3067 DiagDirection dir = GetRoadStopDir(tile);
3069 if (side != INVALID_DIAGDIR && dir != side) return 0;
3071 trackbits = DiagDirToDiagTrackBits(dir);
3072 } else {
3073 Axis axis = GetRoadStopAxis(tile);
3075 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) return 0;
3077 trackbits = AxisToTrackBits(axis);
3080 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3083 static TrackdirBits GetTileWaterwayStatus_Station(TileIndex tile, DiagDirection side)
3085 if (!IsBuoy(tile) && !(IsDock(tile) && IsDockBuoy(tile))) return TRACKDIR_BIT_NONE;
3087 /* buoy is coded as a station, it is always on open water */
3088 TrackBits trackbits = TRACK_BIT_ALL;
3089 /* remove tracks that connect NE map edge */
3090 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3091 /* remove tracks that connect NW map edge */
3092 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3094 return TrackBitsToTrackdirBits(trackbits);
3098 static void TileLoop_Station(TileIndex tile)
3100 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3101 * hardcoded.....not good */
3102 switch (GetStationType(tile)) {
3103 case STATION_AIRPORT:
3104 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3105 break;
3107 case STATION_DOCK:
3108 if (!IsTileFlat(tile)) break; // only handle water part
3109 /* FALL THROUGH */
3110 case STATION_OILRIG: //(station part)
3111 case STATION_BUOY:
3112 TileLoop_Water(tile);
3113 break;
3115 default: break;
3120 static void AnimateTile_Station(TileIndex tile)
3122 if (HasStationRail(tile)) {
3123 AnimateStationTile(tile);
3124 return;
3127 if (IsAirport(tile)) {
3128 AnimateAirportTile(tile);
3133 static bool ClickTile_Station(TileIndex tile)
3135 const BaseStation *bst = BaseStation::GetByTile(tile);
3137 if (bst->IsWaypoint()) {
3138 ShowWaypointWindow(Waypoint::From(bst));
3139 } else if (IsHangar(tile)) {
3140 const Station *st = Station::From(bst);
3141 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3142 } else {
3143 ShowStationViewWindow(bst->index);
3145 return true;
3149 * Run the watched cargo callback for all houses in the catchment area.
3150 * @param st Station.
3152 void TriggerWatchedCargoCallbacks(Station *st)
3154 /* Collect cargoes accepted since the last big tick. */
3155 uint cargoes = 0;
3156 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3157 if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3160 /* Anything to do? */
3161 if (cargoes == 0) return;
3163 /* Loop over all houses in the catchment. */
3164 TileArea ta = st->GetCatchmentArea();
3165 TILE_AREA_LOOP(tile, ta) {
3166 if (IsHouseTile(tile)) {
3167 WatchedCargoCallback(tile, cargoes);
3173 * This function is called for each station once every 250 ticks.
3174 * Not all stations will get the tick at the same time.
3175 * @param st the station receiving the tick.
3176 * @return true if the station is still valid (wasn't deleted)
3178 static bool StationHandleBigTick(BaseStation *st)
3180 if (!st->IsInUse()) {
3181 if (++st->delete_ctr >= 8) delete st;
3182 return false;
3185 if (!st->IsWaypoint()) {
3186 TriggerWatchedCargoCallbacks(Station::From(st));
3188 for (CargoID i = 0; i < NUM_CARGO; i++) {
3189 ClrBit(Station::From(st)->goods[i].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3192 UpdateStationAcceptance(Station::From(st), true);
3195 return true;
3198 static inline void byte_inc_sat(byte *p)
3200 byte b = *p + 1;
3201 if (b != 0) *p = b;
3205 * Truncate the cargo by a specific amount.
3206 * @param cs The type of cargo to perform the truncation for.
3207 * @param ge The goods entry, of the station, to truncate.
3208 * @param amount The amount to truncate the cargo by.
3210 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3212 /* If truncating also punish the source stations' ratings to
3213 * decrease the flow of incoming cargo. */
3215 StationCargoAmountMap waiting_per_source;
3216 ge->cargo.Truncate(amount, &waiting_per_source);
3217 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3218 Station *source_station = Station::GetIfValid(i->first);
3219 if (source_station == NULL) continue;
3221 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3222 source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
3226 static void UpdateStationRating(Station *st)
3228 bool waiting_changed = false;
3230 byte_inc_sat(&st->time_since_load);
3231 byte_inc_sat(&st->time_since_unload);
3233 const CargoSpec *cs;
3234 FOR_ALL_CARGOSPECS(cs) {
3235 GoodsEntry *ge = &st->goods[cs->Index()];
3236 /* Slowly increase the rating back to his original level in the case we
3237 * didn't deliver cargo yet to this station. This happens when a bribe
3238 * failed while you didn't moved that cargo yet to a station. */
3239 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3240 ge->rating++;
3243 /* Only change the rating if we are moving this cargo */
3244 if (ge->HasRating()) {
3245 byte_inc_sat(&ge->time_since_pickup);
3246 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3247 ClrBit(ge->status, GoodsEntry::GES_RATING);
3248 ge->last_speed = 0;
3249 TruncateCargo(cs, ge);
3250 waiting_changed = true;
3251 continue;
3254 bool skip = false;
3255 int rating = 0;
3256 uint waiting = ge->cargo.AvailableCount();
3258 /* num_dests is at least 1 if there is any cargo as
3259 * INVALID_STATION is also a destination.
3261 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3263 /* Average amount of cargo per next hop, but prefer solitary stations
3264 * with only one or two next hops. They are allowed to have more
3265 * cargo waiting per next hop.
3266 * With manual cargo distribution waiting_avg = waiting / 2 as then
3267 * INVALID_STATION is the only destination.
3269 uint waiting_avg = waiting / (num_dests + 1);
3271 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3272 /* Perform custom station rating. If it succeeds the speed, days in transit and
3273 * waiting cargo ratings must not be executed. */
3275 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3276 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3278 uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
3279 /* Convert to the 'old' vehicle types */
3280 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3281 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3282 if (callback != CALLBACK_FAILED) {
3283 skip = true;
3284 rating = GB(callback, 0, 14);
3286 /* Simulate a 15 bit signed value */
3287 if (HasBit(callback, 14)) rating -= 0x4000;
3291 if (!skip) {
3292 int b = ge->last_speed - 85;
3293 if (b >= 0) rating += b >> 2;
3295 byte waittime = ge->time_since_pickup;
3296 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3297 (waittime > 21) ||
3298 (rating += 25, waittime > 12) ||
3299 (rating += 25, waittime > 6) ||
3300 (rating += 45, waittime > 3) ||
3301 (rating += 35, true);
3303 (rating -= 90, ge->max_waiting_cargo > 1500) ||
3304 (rating += 55, ge->max_waiting_cargo > 1000) ||
3305 (rating += 35, ge->max_waiting_cargo > 600) ||
3306 (rating += 10, ge->max_waiting_cargo > 300) ||
3307 (rating += 20, ge->max_waiting_cargo > 100) ||
3308 (rating += 10, true);
3311 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3313 byte age = ge->last_age;
3314 (age >= 3) ||
3315 (rating += 10, age >= 2) ||
3316 (rating += 10, age >= 1) ||
3317 (rating += 13, true);
3320 int or_ = ge->rating; // old rating
3322 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3323 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
3325 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3326 * remove some random amount of goods from the station */
3327 if (rating <= 64 && waiting_avg >= 100) {
3328 int dec = Random() & 0x1F;
3329 if (waiting_avg < 200) dec &= 7;
3330 waiting -= (dec + 1) * num_dests;
3331 waiting_changed = true;
3334 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3335 if (rating <= 127 && waiting != 0) {
3336 uint32 r = Random();
3337 if (rating <= (int)GB(r, 0, 7)) {
3338 /* Need to have int, otherwise it will just overflow etc. */
3339 waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3340 waiting_changed = true;
3344 /* At some point we really must cap the cargo. Previously this
3345 * was a strict 4095, but now we'll have a less strict, but
3346 * increasingly aggressive truncation of the amount of cargo. */
3347 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3348 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3349 static const uint MAX_WAITING_CARGO = 1 << 15;
3351 if (waiting > WAITING_CARGO_THRESHOLD) {
3352 uint difference = waiting - WAITING_CARGO_THRESHOLD;
3353 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3355 waiting = min(waiting, MAX_WAITING_CARGO);
3356 waiting_changed = true;
3359 /* We can't truncate cargo that's already reserved for loading.
3360 * Thus StoredCount() here. */
3361 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3362 /* Feed back the exact own waiting cargo at this station for the
3363 * next rating calculation. */
3364 ge->max_waiting_cargo = 0;
3366 TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3367 } else {
3368 /* If the average number per next hop is low, be more forgiving. */
3369 ge->max_waiting_cargo = waiting_avg;
3375 StationID index = st->index;
3376 if (waiting_changed) {
3377 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3378 } else {
3379 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3384 * Reroute cargo of type c at station st or in any vehicles unloading there.
3385 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3386 * @param st Station to be rerouted at.
3387 * @param c Type of cargo.
3388 * @param avoid Original next hop of cargo, avoid this.
3389 * @param avoid2 Another station to be avoided when rerouting.
3391 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
3393 GoodsEntry &ge = st->goods[c];
3395 /* Reroute cargo in station. */
3396 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
3398 /* Reroute cargo staged to be transfered. */
3399 for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
3400 for (Vehicle *v = *it; v != NULL; v = v->Next()) {
3401 if (v->cargo_type != c) continue;
3402 v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
3408 * Check all next hops of cargo packets in this station for existance of a
3409 * a valid link they may use to travel on. Reroute any cargo not having a valid
3410 * link and remove timed out links found like this from the linkgraph. We're
3411 * not all links here as that is expensive and useless. A link no one is using
3412 * doesn't hurt either.
3413 * @param from Station to check.
3415 void DeleteStaleLinks(Station *from)
3417 for (CargoID c = 0; c < NUM_CARGO; ++c) {
3418 GoodsEntry &ge = from->goods[c];
3419 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
3420 if (lg == NULL) continue;
3421 LinkGraph::NodeRef node = (*lg)[ge.node];
3422 for (LinkGraph::EdgeIterator it(node.Begin()); it != node.End();) {
3423 LinkGraph::Edge *edge = &*it;
3424 Station *to = Station::Get((*lg)[it.get_id()]->Station());
3425 assert(to->goods[c].node == it.get_id());
3426 ++it; // Do that before removing the edge. Anything else may crash.
3427 assert(_date >= edge->LastUpdate());
3428 uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
3429 if ((uint)(_date - edge->LastUpdate()) > timeout) {
3430 /* Have all vehicles refresh their next hops before deciding to
3431 * remove the node. */
3432 bool updated = false;
3433 OrderList *l;
3434 FOR_ALL_ORDER_LISTS(l) {
3435 bool found_from = false;
3436 bool found_to = false;
3437 for (Order *order = l->GetFirstOrder(); order != NULL; order = order->next) {
3438 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
3439 if (order->GetDestination() == from->index) {
3440 found_from = true;
3441 if (found_to) break;
3442 } else if (order->GetDestination() == to->index) {
3443 found_to = true;
3444 if (found_from) break;
3447 if (!found_to || !found_from) continue;
3448 for (Vehicle *v = l->GetFirstSharedVehicle(); !updated && v != NULL; v = v->NextShared()) {
3449 /* There is potential for optimization here:
3450 * - Usually consists of the same order list are the same. It's probably better to
3451 * first check the first of each list, then the second of each list and so on.
3452 * - We could try to figure out if we've seen a consist with the same cargo on the
3453 * same list already and if the consist can actually carry the cargo we're looking
3454 * for. With conditional and refit orders this is not quite trivial, though. */
3455 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
3456 if (edge->LastUpdate() == _date) updated = true;
3458 if (updated) break;
3460 if (!updated) {
3461 /* If it's still considered dead remove it. */
3462 lg->RemoveEdge (ge.node, to->goods[c].node);
3463 ge.flows.DeleteFlows(to->index);
3464 RerouteCargo(from, c, to->index, from->index);
3466 } else if (edge->LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge->LastUnrestrictedUpdate()) > timeout) {
3467 edge->Restrict();
3468 ge.flows.RestrictFlows(to->index);
3469 RerouteCargo(from, c, to->index, from->index);
3470 } else if (edge->LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge->LastRestrictedUpdate()) > timeout) {
3471 edge->Release();
3474 assert(_date >= lg->LastCompression());
3475 if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
3476 lg->Compress();
3482 * Increase capacity for a link stat given by station cargo and next hop.
3483 * @param st Station to get the link stats from.
3484 * @param cargo Cargo to increase stat for.
3485 * @param next_station_id Station the consist will be travelling to next.
3486 * @param capacity Capacity to add to link stat.
3487 * @param usage Usage to add to link stat.
3488 * @param mode Update mode to be applied.
3490 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, EdgeUpdateMode mode)
3492 GoodsEntry &ge1 = st->goods[cargo];
3493 Station *st2 = Station::Get(next_station_id);
3494 GoodsEntry &ge2 = st2->goods[cargo];
3495 LinkGraph *lg = NULL;
3496 if (ge1.link_graph == INVALID_LINK_GRAPH) {
3497 if (ge2.link_graph == INVALID_LINK_GRAPH) {
3498 if (LinkGraph::CanAllocateItem()) {
3499 lg = new LinkGraph(cargo);
3500 LinkGraphSchedule::instance.Queue(lg);
3501 ge2.link_graph = lg->index;
3502 ge2.node = lg->AddNode(st2);
3503 } else {
3504 DEBUG(misc, 0, "Can't allocate link graph");
3506 } else {
3507 lg = LinkGraph::Get(ge2.link_graph);
3509 if (lg) {
3510 ge1.link_graph = lg->index;
3511 ge1.node = lg->AddNode(st);
3513 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
3514 lg = LinkGraph::Get(ge1.link_graph);
3515 ge2.link_graph = lg->index;
3516 ge2.node = lg->AddNode(st2);
3517 } else {
3518 lg = LinkGraph::Get(ge1.link_graph);
3519 if (ge1.link_graph != ge2.link_graph) {
3520 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
3521 if (lg->Size() < lg2->Size()) {
3522 LinkGraphSchedule::instance.Unqueue(lg);
3523 lg2->Merge(lg); // Updates GoodsEntries of lg
3524 lg = lg2;
3525 } else {
3526 LinkGraphSchedule::instance.Unqueue(lg2);
3527 lg->Merge(lg2); // Updates GoodsEntries of lg2
3531 if (lg != NULL) {
3532 lg->UpdateEdge (ge1.node, ge2.node, capacity, usage, mode);
3537 * Increase capacity for all link stats associated with vehicles in the given consist.
3538 * @param st Station to get the link stats from.
3539 * @param front First vehicle in the consist.
3540 * @param next_station_id Station the consist will be travelling to next.
3542 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
3544 for (const Vehicle *v = front; v != NULL; v = v->Next()) {
3545 if (v->refit_cap > 0) {
3546 /* The cargo count can indeed be higher than the refit_cap if
3547 * wagons have been auto-replaced and subsequently auto-
3548 * refitted to a higher capacity. The cargo gets redistributed
3549 * among the wagons in that case.
3550 * As usage is not such an important figure anyway we just
3551 * ignore the additional cargo then.*/
3552 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
3553 min(v->refit_cap, v->cargo.StoredCount()), EUM_INCREASE);
3558 /* called for every station each tick */
3559 static void StationHandleSmallTick(BaseStation *st)
3561 if (st->IsWaypoint() || !st->IsInUse()) return;
3563 byte b = st->delete_ctr + 1;
3564 if (b >= STATION_RATING_TICKS) b = 0;
3565 st->delete_ctr = b;
3567 if (b == 0) UpdateStationRating(Station::From(st));
3570 void OnTick_Station()
3572 if (_game_mode == GM_EDITOR) return;
3574 BaseStation *st;
3575 FOR_ALL_BASE_STATIONS(st) {
3576 StationHandleSmallTick(st);
3578 /* Clean up the link graph about once a week. */
3579 if (!st->IsWaypoint() && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
3580 DeleteStaleLinks(Station::From(st));
3583 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3584 * Station index is included so that triggers are not all done
3585 * at the same time. */
3586 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
3587 /* Stop processing this station if it was deleted */
3588 if (!StationHandleBigTick(st)) continue;
3589 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
3590 if (!st->IsWaypoint()) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
3595 /** Monthly loop for stations. */
3596 void StationMonthlyLoop()
3598 Station *st;
3600 FOR_ALL_STATIONS(st) {
3601 for (CargoID i = 0; i < NUM_CARGO; i++) {
3602 GoodsEntry *ge = &st->goods[i];
3603 SB(ge->status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->status, GoodsEntry::GES_CURRENT_MONTH, 1));
3604 ClrBit(ge->status, GoodsEntry::GES_CURRENT_MONTH);
3610 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
3612 Station *st;
3614 FOR_ALL_STATIONS(st) {
3615 if (st->owner == owner &&
3616 DistanceManhattan(tile, st->xy) <= radius) {
3617 for (CargoID i = 0; i < NUM_CARGO; i++) {
3618 GoodsEntry *ge = &st->goods[i];
3620 if (ge->status != 0) {
3621 ge->rating = Clamp(ge->rating + amount, 0, 255);
3628 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
3630 /* We can't allocate a CargoPacket? Then don't do anything
3631 * at all; i.e. just discard the incoming cargo. */
3632 if (!CargoPacket::CanAllocateItem()) return 0;
3634 GoodsEntry &ge = st->goods[type];
3635 amount += ge.amount_fract;
3636 ge.amount_fract = GB(amount, 0, 8);
3638 amount >>= 8;
3639 /* No new "real" cargo item yet. */
3640 if (amount == 0) return 0;
3642 StationID next = ge.GetVia(st->index);
3643 ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
3644 LinkGraph *lg = NULL;
3645 if (ge.link_graph == INVALID_LINK_GRAPH) {
3646 if (LinkGraph::CanAllocateItem()) {
3647 lg = new LinkGraph(type);
3648 LinkGraphSchedule::instance.Queue(lg);
3649 ge.link_graph = lg->index;
3650 ge.node = lg->AddNode(st);
3651 } else {
3652 DEBUG(misc, 0, "Can't allocate link graph");
3654 } else {
3655 lg = LinkGraph::Get(ge.link_graph);
3657 if (lg != NULL) (*lg)[ge.node]->UpdateSupply(amount);
3659 if (!ge.HasRating()) {
3660 InvalidateWindowData(WC_STATION_LIST, st->index);
3661 SetBit(ge.status, GoodsEntry::GES_RATING);
3664 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
3665 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
3666 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
3668 SetWindowDirty(WC_STATION_VIEW, st->index);
3669 st->MarkTilesDirty(true);
3670 return amount;
3673 static bool IsUniqueStationName(const char *name)
3675 const Station *st;
3677 FOR_ALL_STATIONS(st) {
3678 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
3681 return true;
3685 * Rename a station
3686 * @param tile unused
3687 * @param flags operation to perform
3688 * @param p1 station ID that is to be renamed
3689 * @param p2 unused
3690 * @param text the new name or an empty string when resetting to the default
3691 * @return the cost of this operation or an error
3693 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3695 Station *st = Station::GetIfValid(p1);
3696 if (st == NULL) return CMD_ERROR;
3698 CommandCost ret = CheckOwnership(st->owner);
3699 if (ret.Failed()) return ret;
3701 bool reset = StrEmpty(text);
3703 if (!reset) {
3704 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
3705 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
3708 if (flags & DC_EXEC) {
3709 free(st->name);
3710 st->name = reset ? NULL : xstrdup(text);
3712 st->UpdateVirtCoord();
3713 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
3716 return CommandCost();
3720 * Find all stations around a rectangular producer (industry, house, headquarter, ...)
3722 * @param location The location/area of the producer
3723 * @param stations The list to store the stations in
3725 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
3727 /* area to search = producer plus station catchment radius */
3728 uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
3730 uint x = TileX(location.tile);
3731 uint y = TileY(location.tile);
3733 uint min_x = (x > max_rad) ? x - max_rad : 0;
3734 uint max_x = x + location.w + max_rad;
3735 uint min_y = (y > max_rad) ? y - max_rad : 0;
3736 uint max_y = y + location.h + max_rad;
3738 if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
3739 if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
3740 if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
3741 if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
3743 for (uint cy = min_y; cy < max_y; cy++) {
3744 for (uint cx = min_x; cx < max_x; cx++) {
3745 TileIndex cur_tile = TileXY(cx, cy);
3746 if (!IsStationTile(cur_tile)) continue;
3748 Station *st = Station::GetByTile(cur_tile);
3749 /* st can be NULL in case of waypoints */
3750 if (st == NULL) continue;
3752 if (_settings_game.station.modified_catchment) {
3753 int rad = st->GetCatchmentRadius();
3754 int rad_x = cx - x;
3755 int rad_y = cy - y;
3757 if (rad_x < -rad || rad_x >= rad + location.w) continue;
3758 if (rad_y < -rad || rad_y >= rad + location.h) continue;
3761 /* Insert the station in the set. This will fail if it has
3762 * already been added.
3764 stations->Include(st);
3770 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
3771 * @return pointer to a StationList containing all stations found
3773 const StationList *StationFinder::GetStations()
3775 if (this->tile != INVALID_TILE) {
3776 FindStationsAroundTiles(*this, &this->stations);
3777 this->tile = INVALID_TILE;
3779 return &this->stations;
3782 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
3784 /* Return if nothing to do. Also the rounding below fails for 0. */
3785 if (amount == 0) return 0;
3787 Station *st1 = NULL; // Station with best rating
3788 Station *st2 = NULL; // Second best station
3789 uint best_rating1 = 0; // rating of st1
3790 uint best_rating2 = 0; // rating of st2
3792 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
3793 Station *st = *st_iter;
3795 /* Is the station reserved exclusively for somebody else? */
3796 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
3798 if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
3800 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
3802 if (!st->CanHandleCargo(type)) continue; // passengers on truck stop or freight on bus stop
3804 /* This station can be used, add it to st1/st2 */
3805 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
3806 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
3807 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
3808 st2 = st; best_rating2 = st->goods[type].rating;
3812 /* no stations around at all? */
3813 if (st1 == NULL) return 0;
3815 /* From now we'll calculate with fractal cargo amounts.
3816 * First determine how much cargo we really have. */
3817 amount *= best_rating1 + 1;
3819 if (st2 == NULL) {
3820 /* only one station around */
3821 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
3824 /* several stations around, the best two (highest rating) are in st1 and st2 */
3825 assert(st1 != NULL);
3826 assert(st2 != NULL);
3827 assert(best_rating1 != 0 || best_rating2 != 0);
3829 /* Then determine the amount the worst station gets. We do it this way as the
3830 * best should get a bonus, which in this case is the rounding difference from
3831 * this calculation. In reality that will mean the bonus will be pretty low.
3832 * Nevertheless, the best station should always get the most cargo regardless
3833 * of rounding issues. */
3834 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
3835 assert(worst_cargo <= (amount - worst_cargo));
3837 /* And then send the cargo to the stations! */
3838 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
3839 /* These two UpdateStationWaiting's can't be in the statement as then the order
3840 * of execution would be undefined and that could cause desyncs with callbacks. */
3841 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
3844 void BuildOilRig(TileIndex tile)
3846 if (!Station::CanAllocateItem()) {
3847 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
3848 return;
3851 if (!Dock::CanAllocateItem()) {
3852 DEBUG(misc, 0, "Can't allocate dock for oilrig at 0x%X, reverting to oilrig only", tile);
3853 return;
3856 Station *st = new Station(tile);
3857 st->town = ClosestTownFromTile(tile);
3859 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
3861 assert(IsIndustryTile(tile));
3862 DeleteAnimatedTile(tile);
3863 MakeOilrig(tile, st->index, GetWaterClass(tile));
3865 st->owner = OWNER_NONE;
3866 st->docks = new Dock(tile);
3867 st->dock_area = TileArea(tile, 1, 1);
3868 st->airport.type = AT_OILRIG;
3869 st->airport.Add(tile);
3870 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
3871 st->build_date = _date;
3873 st->rect.Add(tile);
3875 st->UpdateVirtCoord();
3876 UpdateStationAcceptance(st, false);
3877 st->RecomputeIndustriesNear();
3880 void DeleteOilRig(TileIndex tile)
3882 Station *st = Station::GetByTile(tile);
3884 MakeWaterKeepingClass(tile, OWNER_NONE);
3886 delete st->docks;
3887 st->docks = NULL;
3888 st->dock_area.Clear();
3889 st->airport.Clear();
3890 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
3891 st->airport.flags = 0;
3893 st->AfterRemoveTile(tile);
3895 st->UpdateVirtCoord();
3896 st->RecomputeIndustriesNear();
3897 if (!st->IsInUse()) delete st;
3900 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
3902 if (IsRoadStopTile(tile)) {
3903 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
3904 /* Update all roadtypes, no matter if they are present */
3905 if (GetRoadOwner(tile, rt) == old_owner) {
3906 if (HasTileRoadType(tile, rt)) {
3907 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
3908 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
3909 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
3911 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
3916 if (!IsTileOwner(tile, old_owner)) return;
3918 if (new_owner != INVALID_OWNER) {
3919 /* Update company infrastructure counts. Only do it here
3920 * if the new owner is valid as otherwise the clear
3921 * command will do it for us. No need to dirty windows
3922 * here, we'll redraw the whole screen anyway.*/
3923 Company *old_company = Company::Get(old_owner);
3924 Company *new_company = Company::Get(new_owner);
3926 /* Update counts for underlying infrastructure. */
3927 switch (GetStationType(tile)) {
3928 case STATION_RAIL:
3929 case STATION_WAYPOINT:
3930 if (!IsStationTileBlocked(tile)) {
3931 old_company->infrastructure.rail[GetRailType(tile)]--;
3932 new_company->infrastructure.rail[GetRailType(tile)]++;
3934 break;
3936 case STATION_BUS:
3937 case STATION_TRUCK:
3938 /* Road stops were already handled above. */
3939 break;
3941 case STATION_BUOY:
3942 case STATION_DOCK:
3943 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
3944 old_company->infrastructure.water--;
3945 new_company->infrastructure.water++;
3947 break;
3949 default:
3950 break;
3953 /* Update station tile count. */
3954 if (!IsBuoy(tile) && !IsAirport(tile)) {
3955 old_company->infrastructure.station--;
3956 new_company->infrastructure.station++;
3959 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
3960 SetTileOwner(tile, new_owner);
3961 InvalidateWindowClassesData(WC_STATION_LIST, 0);
3962 } else {
3963 if (IsDriveThroughStopTile(tile)) {
3964 /* Remove the drive-through road stop */
3965 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
3966 assert(IsNormalRoadTile(tile));
3967 /* Change owner of tile and all roadtypes */
3968 ChangeTileOwner(tile, old_owner, new_owner);
3969 } else {
3970 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
3971 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
3972 * Update owner of buoy if it was not removed (was in orders).
3973 * Do not update when owned by OWNER_WATER (sea and rivers). */
3974 if ((IsWaterTile(tile) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
3980 * Check if a drive-through road stop tile can be cleared.
3981 * Road stops built on town-owned roads check the conditions
3982 * that would allow clearing of the original road.
3983 * @param tile road stop tile to check
3984 * @param flags command flags
3985 * @return true if the road can be cleared
3987 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
3989 /* Yeah... water can always remove stops, right? */
3990 if (_current_company == OWNER_WATER) return true;
3992 RoadTypes rts = GetRoadTypes(tile);
3993 if (HasBit(rts, ROADTYPE_TRAM)) {
3994 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
3995 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
3997 if (HasBit(rts, ROADTYPE_ROAD)) {
3998 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
3999 if (road_owner != OWNER_TOWN) {
4000 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
4001 } else {
4002 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
4006 return true;
4010 * Clear a single tile of a station.
4011 * @param tile The tile to clear.
4012 * @param flags The DoCommand flags related to the "command".
4013 * @return The cost, or error of clearing.
4015 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4017 if (flags & DC_AUTO) {
4018 switch (GetStationType(tile)) {
4019 default: break;
4020 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4021 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4022 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4023 case STATION_TRUCK: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4024 case STATION_BUS: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4025 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4026 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4027 case STATION_OILRIG:
4028 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4029 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4033 switch (GetStationType(tile)) {
4034 case STATION_RAIL: return RemoveRailStation(tile, flags);
4035 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4036 case STATION_AIRPORT: return RemoveAirport(tile, flags);
4037 case STATION_TRUCK:
4038 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4039 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4041 return RemoveRoadStop(tile, flags);
4042 case STATION_BUS:
4043 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4044 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4046 return RemoveRoadStop(tile, flags);
4047 case STATION_BUOY: return RemoveBuoy(tile, flags);
4048 case STATION_DOCK: return RemoveDock(tile, flags);
4049 default: break;
4052 return CMD_ERROR;
4055 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4057 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4058 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4059 * TTDP does not call it.
4061 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4062 switch (GetStationType(tile)) {
4063 case STATION_WAYPOINT:
4064 case STATION_RAIL: {
4065 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4066 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4067 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4068 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4071 case STATION_AIRPORT:
4072 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4074 case STATION_TRUCK:
4075 case STATION_BUS: {
4076 DiagDirection direction = GetRoadStopDir(tile);
4077 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4078 if (IsDriveThroughStopTile(tile)) {
4079 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4081 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4084 default: break;
4088 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
4092 * Get flow for a station.
4093 * @param st Station to get flow for.
4094 * @return Flow for st.
4096 uint FlowStat::GetShare(StationID st) const
4098 uint32 prev = 0;
4099 for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
4100 if (it->second == st) {
4101 return it->first - prev;
4102 } else {
4103 prev = it->first;
4106 return 0;
4110 * Get a station a package can be routed to, but exclude the given ones.
4111 * @param excluded StationID not to be selected.
4112 * @param excluded2 Another StationID not to be selected.
4113 * @return A station ID from the shares map.
4115 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4117 if (this->unrestricted == 0) return INVALID_STATION;
4118 assert(!this->shares.empty());
4119 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4120 assert(it != this->shares.end() && it->first <= this->unrestricted);
4121 if (it->second != excluded && it->second != excluded2) return it->second;
4123 /* We've hit one of the excluded stations.
4124 * Draw another share, from outside its range. */
4126 uint end = it->first;
4127 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4128 uint interval = end - begin;
4129 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4130 uint new_max = this->unrestricted - interval;
4131 uint rand = RandomRange(new_max);
4132 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4133 this->shares.upper_bound(rand + interval);
4134 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4135 if (it2->second != excluded && it2->second != excluded2) return it2->second;
4137 /* We've hit the second excluded station.
4138 * Same as before, only a bit more complicated. */
4140 uint end2 = it2->first;
4141 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4142 uint interval2 = end2 - begin2;
4143 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4144 new_max -= interval2;
4145 if (begin > begin2) {
4146 Swap(begin, begin2);
4147 Swap(end, end2);
4148 Swap(interval, interval2);
4150 rand = RandomRange(new_max);
4151 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4152 if (rand < begin) {
4153 it3 = this->shares.upper_bound(rand);
4154 } else if (rand < begin2 - interval) {
4155 it3 = this->shares.upper_bound(rand + interval);
4156 } else {
4157 it3 = this->shares.upper_bound(rand + interval + interval2);
4159 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4160 return it3->second;
4164 * Reduce all flows to minimum capacity so that they don't get in the way of
4165 * link usage statistics too much. Keep them around, though, to continue
4166 * routing any remaining cargo.
4168 void FlowStat::Invalidate()
4170 assert(!this->shares.empty());
4171 SharesMap new_shares;
4172 uint i = 0;
4173 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4174 new_shares[++i] = it->second;
4175 if (it->first == this->unrestricted) this->unrestricted = i;
4177 this->shares.swap(new_shares);
4178 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4182 * Change share for specified station. By specifing INT_MIN as parameter you
4183 * can erase a share. Newly added flows will be unrestricted.
4184 * @param st Next Hop to be removed.
4185 * @param flow Share to be added or removed.
4187 void FlowStat::ChangeShare(StationID st, int flow)
4189 /* We assert only before changing as afterwards the shares can actually
4190 * be empty. In that case the whole flow stat must be deleted then. */
4191 assert(!this->shares.empty());
4193 uint removed_shares = 0;
4194 uint added_shares = 0;
4195 uint last_share = 0;
4196 SharesMap new_shares;
4197 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4198 if (it->second == st) {
4199 if (flow < 0) {
4200 uint share = it->first - last_share;
4201 if (flow == INT_MIN || (uint)(-flow) >= share) {
4202 removed_shares += share;
4203 if (it->first <= this->unrestricted) this->unrestricted -= share;
4204 if (flow != INT_MIN) flow += share;
4205 last_share = it->first;
4206 continue; // remove the whole share
4208 removed_shares += (uint)(-flow);
4209 } else {
4210 added_shares += (uint)(flow);
4212 if (it->first <= this->unrestricted) this->unrestricted += flow;
4214 /* If we don't continue above the whole flow has been added or
4215 * removed. */
4216 flow = 0;
4218 new_shares[it->first + added_shares - removed_shares] = it->second;
4219 last_share = it->first;
4221 if (flow > 0) {
4222 new_shares[last_share + (uint)flow] = st;
4223 if (this->unrestricted < last_share) {
4224 this->ReleaseShare(st);
4225 } else {
4226 this->unrestricted += flow;
4229 this->shares.swap(new_shares);
4233 * Restrict a flow by moving it to the end of the map and decreasing the amount
4234 * of unrestricted flow.
4235 * @param st Station of flow to be restricted.
4237 void FlowStat::RestrictShare(StationID st)
4239 assert(!this->shares.empty());
4240 uint flow = 0;
4241 uint last_share = 0;
4242 SharesMap new_shares;
4243 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4244 if (flow == 0) {
4245 if (it->first > this->unrestricted) return; // Not present or already restricted.
4246 if (it->second == st) {
4247 flow = it->first - last_share;
4248 this->unrestricted -= flow;
4249 } else {
4250 new_shares[it->first] = it->second;
4252 } else {
4253 new_shares[it->first - flow] = it->second;
4255 last_share = it->first;
4257 if (flow == 0) return;
4258 new_shares[last_share + flow] = st;
4259 this->shares.swap(new_shares);
4260 assert(!this->shares.empty());
4264 * Release ("unrestrict") a flow by moving it to the begin of the map and
4265 * increasing the amount of unrestricted flow.
4266 * @param st Station of flow to be released.
4268 void FlowStat::ReleaseShare(StationID st)
4270 assert(!this->shares.empty());
4271 uint flow = 0;
4272 uint next_share = 0;
4273 bool found = false;
4274 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4275 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4276 if (found) {
4277 flow = next_share - it->first;
4278 this->unrestricted += flow;
4279 break;
4280 } else {
4281 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4282 if (it->second == st) found = true;
4284 next_share = it->first;
4286 if (flow == 0) return;
4287 SharesMap new_shares;
4288 new_shares[flow] = st;
4289 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4290 if (it->second != st) {
4291 new_shares[flow + it->first] = it->second;
4292 } else {
4293 flow = 0;
4296 this->shares.swap(new_shares);
4297 assert(!this->shares.empty());
4301 * Scale all shares from link graph's runtime to monthly values.
4302 * @param runtime Time the link graph has been running without compression.
4303 * @pre runtime must be greater than 0 as we don't want infinite flow values.
4305 void FlowStat::ScaleToMonthly(uint runtime)
4307 assert(runtime > 0);
4308 SharesMap new_shares;
4309 uint share = 0;
4310 for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
4311 share = max(share + 1, i->first * 30 / runtime);
4312 new_shares[share] = i->second;
4313 if (this->unrestricted == i->first) this->unrestricted = share;
4315 this->shares.swap(new_shares);
4319 * Add some flow from "origin", going via "via".
4320 * @param origin Origin of the flow.
4321 * @param via Next hop.
4322 * @param flow Amount of flow to be added.
4324 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
4326 FlowStatMap::iterator origin_it = this->find(origin);
4327 if (origin_it == this->end()) {
4328 this->insert(std::make_pair(origin, FlowStat(via, flow)));
4329 } else {
4330 origin_it->second.ChangeShare(via, flow);
4331 assert(!origin_it->second.GetShares()->empty());
4336 * Pass on some flow, remembering it as invalid, for later subtraction from
4337 * locally consumed flow. This is necessary because we can't have negative
4338 * flows and we don't want to sort the flows before adding them up.
4339 * @param origin Origin of the flow.
4340 * @param via Next hop.
4341 * @param flow Amount of flow to be passed.
4343 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
4345 FlowStatMap::iterator prev_it = this->find(origin);
4346 if (prev_it == this->end()) {
4347 FlowStat fs(via, flow);
4348 fs.AppendShare(INVALID_STATION, flow);
4349 this->insert(std::make_pair(origin, fs));
4350 } else {
4351 prev_it->second.ChangeShare(via, flow);
4352 prev_it->second.ChangeShare(INVALID_STATION, flow);
4353 assert(!prev_it->second.GetShares()->empty());
4358 * Subtract invalid flows from locally consumed flow.
4359 * @param self ID of own station.
4361 void FlowStatMap::FinalizeLocalConsumption(StationID self)
4363 for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
4364 FlowStat &fs = i->second;
4365 uint local = fs.GetShare(INVALID_STATION);
4366 if (local > INT_MAX) { // make sure it fits in an int
4367 fs.ChangeShare(self, -INT_MAX);
4368 fs.ChangeShare(INVALID_STATION, -INT_MAX);
4369 local -= INT_MAX;
4371 fs.ChangeShare(self, -(int)local);
4372 fs.ChangeShare(INVALID_STATION, -(int)local);
4374 /* If the local share is used up there must be a share for some
4375 * remote station. */
4376 assert(!fs.GetShares()->empty());
4381 * Delete all flows at a station for specific cargo and destination.
4382 * @param via Remote station of flows to be deleted.
4383 * @return IDs of source stations for which the complete FlowStat, not only a
4384 * share, has been erased.
4386 StationIDStack FlowStatMap::DeleteFlows(StationID via)
4388 StationIDStack ret;
4389 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
4390 FlowStat &s_flows = f_it->second;
4391 s_flows.ChangeShare(via, INT_MIN);
4392 if (s_flows.GetShares()->empty()) {
4393 ret.Push(f_it->first);
4394 this->erase(f_it++);
4395 } else {
4396 ++f_it;
4399 return ret;
4403 * Restrict all flows at a station for specific cargo and destination.
4404 * @param via Remote station of flows to be restricted.
4406 void FlowStatMap::RestrictFlows(StationID via)
4408 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4409 it->second.RestrictShare(via);
4414 * Release all flows at a station for specific cargo and destination.
4415 * @param via Remote station of flows to be released.
4417 void FlowStatMap::ReleaseFlows(StationID via)
4419 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4420 it->second.ReleaseShare(via);
4425 * Get the sum of all flows from this FlowStatMap.
4426 * @return sum of all flows.
4428 uint FlowStatMap::GetFlow() const
4430 uint ret = 0;
4431 for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4432 ret += (--(i->second.GetShares()->end()))->first;
4434 return ret;
4438 * Get the sum of flows via a specific station from this FlowStatMap.
4439 * @param via Remote station to look for.
4440 * @return all flows for 'via' added up.
4442 uint FlowStatMap::GetFlowVia(StationID via) const
4444 uint ret = 0;
4445 for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4446 ret += i->second.GetShare(via);
4448 return ret;
4452 * Get the sum of flows from a specific station from this FlowStatMap.
4453 * @param from Origin station to look for.
4454 * @return all flows from 'from' added up.
4456 uint FlowStatMap::GetFlowFrom(StationID from) const
4458 FlowStatMap::const_iterator i = this->find(from);
4459 if (i == this->end()) return 0;
4460 return (--(i->second.GetShares()->end()))->first;
4464 * Get the flow from a specific station via a specific other station.
4465 * @param from Origin station to look for.
4466 * @param via Remote station to look for.
4467 * @return flow share originating at 'from' and going to 'via'.
4469 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
4471 FlowStatMap::const_iterator i = this->find(from);
4472 if (i == this->end()) return 0;
4473 return i->second.GetShare(via);
4476 extern const TileTypeProcs _tile_type_station_procs = {
4477 DrawTile_Station, // draw_tile_proc
4478 GetSlopePixelZ_Station, // get_slope_z_proc
4479 ClearTile_Station, // clear_tile_proc
4480 NULL, // add_accepted_cargo_proc
4481 GetTileDesc_Station, // get_tile_desc_proc
4482 GetTileRailwayStatus_Station, // get_tile_railway_status_proc
4483 GetTileRoadStatus_Station, // get_tile_road_status_proc
4484 GetTileWaterwayStatus_Station, // get_tile_waterway_status_proc
4485 ClickTile_Station, // click_tile_proc
4486 AnimateTile_Station, // animate_tile_proc
4487 TileLoop_Station, // tile_loop_proc
4488 ChangeTileOwner_Station, // change_tile_owner_proc
4489 NULL, // add_produced_cargo_proc
4490 GetFoundation_Station, // get_foundation_proc
4491 TerraformTile_Station, // terraform_tile_proc