Translations update
[openttd/fttd.git] / src / station_cmd.cpp
blobd583105945d7bc24c97b4365bd5a2296d4f69758
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 * Get the cargo types being produced around a tile area.
369 * @param area Tile area
370 * @param rad Search radius in addition to the given area
372 CargoArray GetAreaProduction (const TileArea &area, int rad)
374 CargoArray produced;
376 TileArea ta (area);
377 ta.expand (rad);
379 /* Loop over all tiles to get the produced cargo of
380 * everything except industries */
381 TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
383 /* Loop over the industries. They produce cargo for
384 * anything that is within 'rad' from their bounding
385 * box. As such if you have e.g. a oil well the tile
386 * area loop might not hit an industry tile while
387 * the industry would produce cargo for the station.
389 const Industry *i;
390 FOR_ALL_INDUSTRIES(i) {
391 if (!ta.Intersects(i->location)) continue;
393 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
394 CargoID cargo = i->produced_cargo[j];
395 if (cargo != CT_INVALID) produced[cargo]++;
399 return produced;
403 * Get the acceptance of cargoes around a tile area in 1/8.
404 * @param area Tile area
405 * @param rad Search radius in addition to given area
406 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be NULL
408 CargoArray GetAreaAcceptance (const TileArea &area, int rad, uint32 *always_accepted)
410 CargoArray acceptance;
411 if (always_accepted != NULL) *always_accepted = 0;
413 TileArea ta (area);
414 ta.expand (rad);
416 TILE_AREA_LOOP(tile, ta) AddAcceptedCargo(tile, acceptance, always_accepted);
418 return acceptance;
422 * Update the acceptance for a station.
423 * @param st Station to update
424 * @param show_msg controls whether to display a message that acceptance was changed.
426 void UpdateStationAcceptance(Station *st, bool show_msg)
428 /* old accepted goods types */
429 uint old_acc = GetAcceptanceMask(st);
431 /* And retrieve the acceptance. */
432 CargoArray acceptance;
433 if (!st->rect.empty()) {
434 acceptance = GetAreaAcceptance (st->rect,
435 st->GetCatchmentRadius(), &st->always_accepted);
438 /* Adjust in case our station only accepts fewer kinds of goods */
439 for (CargoID i = 0; i < NUM_CARGO; i++) {
440 /* Make sure the station can accept the goods type. */
441 uint amt = st->CanHandleCargo(i) ? acceptance[i] : 0;
443 GoodsEntry &ge = st->goods[i];
444 SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
445 if (LinkGraph::IsValidID(ge.link_graph)) {
446 (*LinkGraph::Get(ge.link_graph))[ge.node]->SetDemand(amt / 8);
450 /* Only show a message in case the acceptance was actually changed. */
451 uint new_acc = GetAcceptanceMask(st);
452 uint diff_acc = old_acc ^ new_acc;
453 if (diff_acc == 0) return;
455 /* show a message to report that the acceptance was changed? */
456 if (show_msg && st->owner == _local_company && st->IsInUse()) {
457 /* List of accept and reject strings for different number of
458 * cargo types */
459 static const StringID accept_msg[] = {
460 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
461 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
463 static const StringID reject_msg[] = {
464 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
465 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
468 /* Array of accepted and rejected cargo types */
469 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
470 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
471 uint num_acc = 0;
472 uint num_rej = 0;
474 /* Test each cargo type to see if its acceptance has changed */
475 for (CargoID i = 0; i < NUM_CARGO; i++) {
476 if (!HasBit (diff_acc, i)) continue;
478 if (HasBit(new_acc, i)) {
479 if (num_acc < lengthof(accepts)) {
480 /* New cargo is accepted */
481 accepts[num_acc++] = i;
483 } else {
484 if (num_rej < lengthof(rejects)) {
485 /* Old cargo is no longer accepted */
486 rejects[num_rej++] = i;
491 /* Show news message if there are any changes */
492 if (num_acc > 0) AddNewsItem<AcceptanceNewsItem> (st, num_acc, accepts, accept_msg[num_acc - 1]);
493 if (num_rej > 0) AddNewsItem<AcceptanceNewsItem> (st, num_rej, rejects, reject_msg[num_rej - 1]);
496 /* redraw the station view since acceptance changed */
497 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
500 /** Update the station sign tile and virtual position. */
501 static void UpdateStationSign (BaseStation *st)
503 if (st->rect.empty()) { // no tiles belong to this station
504 st->UpdateVirtCoord();
505 return;
508 /* clamp sign coord to be inside the station rect */
509 st->xy = st->rect.get_closest_tile(st->xy);
510 st->UpdateVirtCoord();
512 if (st->IsWaypoint()) return;
513 Station *full_station = Station::From(st);
514 for (CargoID c = 0; c < NUM_CARGO; ++c) {
515 LinkGraphID lg = full_station->goods[c].link_graph;
516 if (!LinkGraph::IsValidID(lg)) continue;
521 * This is called right after a station was deleted.
522 * It checks if the whole station is free of substations, and if so, the station will be
523 * deleted after a little while.
524 * @param st Station
526 static void DeleteStationIfEmpty(BaseStation *st)
528 if (!st->IsInUse()) {
529 st->delete_ctr = 0;
530 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
534 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
537 * Checks if the given tile is buildable, flat and has a certain height.
538 * @param tile TileIndex to check.
539 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
540 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
541 * @param allow_steep Whether steep slopes are allowed.
542 * @param check_bridge Minimum allowed height for a bridge, 0 for none.
543 * @return The cost in case of success, or an error code if it failed.
545 CommandCost CheckBuildableTile (TileIndex tile, uint invalid_dirs,
546 int &allowed_z, bool allow_steep, int check_bridge = 0)
548 int z;
549 Slope tileh = GetTileSlope (tile, &z);
550 z += GetSlopeMaxZ (tileh);
552 if (HasBridgeAbove (tile) && ((check_bridge == 0)
553 || (GetBridgeHeight (GetSouthernBridgeEnd (tile)) < z + check_bridge))) {
554 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
557 CommandCost ret = EnsureNoVehicleOnGround(tile);
558 if (ret.Failed()) return ret;
560 /* Prohibit building if
561 * 1) The tile is "steep" (i.e. stretches two height levels).
562 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
564 if ((!allow_steep && IsSteepSlope(tileh)) ||
565 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
566 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
569 CommandCost cost(EXPENSES_CONSTRUCTION);
570 if (tileh != SLOPE_FLAT) {
571 /* Forbid building if the tile faces a slope in a invalid direction. */
572 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
573 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
574 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
577 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
580 /* The level of this tile must be equal to allowed_z. */
581 if (allowed_z < 0) {
582 /* First tile. */
583 allowed_z = z;
584 } else if (allowed_z != z) {
585 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
588 return cost;
592 * Checks if a rail station can be built at the given area.
593 * @param tile_area Area to check.
594 * @param flags Operation to perform.
595 * @param axis Rail station axis.
596 * @param station StationID to be queried and returned if available.
597 * @param rt The rail type to check for (overbuilding rail stations over rail).
598 * @param affected_vehicles List of trains with PBS reservations on the tiles
599 * @param statspec Station spec.
600 * @param plat_len Platform length.
601 * @param numtracks Number of platforms.
602 * @param layout Station layout.
603 * @return The cost in case of success, or an error code if it failed.
605 static CommandCost CheckFlatLandRailStation (TileArea tile_area,
606 DoCommandFlag flags, Axis axis, StationID *station, RailType rt,
607 SmallVector <Train *, 4> &affected_vehicles,
608 const StationSpec *statspec, byte plat_len, byte numtracks,
609 const byte *layout)
611 CommandCost cost(EXPENSES_CONSTRUCTION);
612 int allowed_z = -1;
613 uint invalid_dirs = 5 << axis;
615 bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
617 TILE_AREA_LOOP(tile_cur, tile_area) {
618 uint check_bridge;
619 if (statspec != NULL) {
620 /* Disallow bridges over custom station tiles for now. */
621 check_bridge = 0;
622 } else {
623 uint dx = TileX (tile_cur) - TileX (tile_area.tile);
624 uint dy = TileY (tile_cur) - TileY (tile_area.tile);
625 uint platform, offset;
626 if (axis == AXIS_X) {
627 platform = dy;
628 offset = dx;
629 } else {
630 platform = dx;
631 offset = dy;
633 uint gfx = layout[platform * plat_len + offset];
634 check_bridge = (gfx < 2 ? 1 : gfx < 4 ? 2 : 4);
636 CommandCost ret = CheckBuildableTile (tile_cur, invalid_dirs, allowed_z, false, check_bridge);
637 if (ret.Failed()) return ret;
638 cost.AddCost(ret);
640 if (slope_cb) {
641 /* Do slope check if requested. */
642 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
643 if (ret.Failed()) return ret;
646 /* if station is set, then we have special handling to allow building on top of already existing stations.
647 * so station points to INVALID_STATION if we can build on any station.
648 * Or it points to a station if we're only allowed to build on exactly that station. */
649 if (station != NULL && IsStationTile(tile_cur)) {
650 if (!IsRailStation(tile_cur)) {
651 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
652 } else {
653 StationID st = GetStationIndex(tile_cur);
654 if (*station == INVALID_STATION) {
655 *station = st;
656 } else if (*station != st) {
657 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
660 } else {
661 /* Rail type is only valid when building a railway station; if station to
662 * build isn't a rail station it's INVALID_RAILTYPE. */
663 if (rt != INVALID_RAILTYPE && IsNormalRailTile(tile_cur) &&
664 HasPowerOnRail(GetRailType(tile_cur), rt)) {
665 /* Allow overbuilding if the tile:
666 * - has rail, but no signals
667 * - it has exactly one track
668 * - the track is in line with the station
669 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
671 Track track = AxisToTrack(axis);
673 if (GetTrackBits(tile_cur) == TrackToTrackBits(track) && !HasSignalOnTrack(tile_cur, track)) {
674 /* Check for trains having a reservation for this tile. */
675 if (GetRailReservationTrackBits (tile_cur) != TRACK_BIT_NONE) {
676 Train *v = GetTrainForReservation(tile_cur, track);
677 if (v != NULL) {
678 *affected_vehicles.Append() = v;
681 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
682 if (ret.Failed()) return ret;
683 cost.AddCost(ret);
684 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
685 continue;
688 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
689 if (ret.Failed()) return ret;
690 cost.AddCost(ret);
694 return cost;
698 * Checks if a road stop can be built at the given tile.
699 * @param tile_area Area to check.
700 * @param flags Operation to perform.
701 * @param invalid_dirs Prohibited directions (set of DiagDirections).
702 * @param is_drive_through True if trying to build a drive-through station.
703 * @param is_truck_stop True when building a truck stop, false otherwise.
704 * @param axis Axis of a drive-through road stop.
705 * @param station StationID to be queried and returned if available.
706 * @param rts Road types to build.
707 * @return The cost in case of success, or an error code if it failed.
709 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)
711 CommandCost cost(EXPENSES_CONSTRUCTION);
712 int allowed_z = -1;
714 TILE_AREA_LOOP(cur_tile, tile_area) {
715 CommandCost ret = CheckBuildableTile (cur_tile, invalid_dirs, allowed_z, !is_drive_through, 2);
716 if (ret.Failed()) return ret;
717 cost.AddCost(ret);
719 /* If station is set, then we have special handling to allow building on top of already existing stations.
720 * Station points to INVALID_STATION if we can build on any station.
721 * Or it points to a station if we're only allowed to build on exactly that station. */
722 if (station != NULL && IsStationTile(cur_tile)) {
723 if (!IsRoadStop(cur_tile)) {
724 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
725 } else {
726 if (is_truck_stop != IsTruckStop(cur_tile) ||
727 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
728 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
730 /* Drive-through station in the wrong direction. */
731 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && GetRoadStopAxis(cur_tile) != axis){
732 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
734 StationID st = GetStationIndex(cur_tile);
735 if (*station == INVALID_STATION) {
736 *station = st;
737 } else if (*station != st) {
738 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
741 } else {
742 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
743 /* Road bits in the wrong direction. */
744 RoadBits rb = IsRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
745 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
746 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
747 switch (CountBits(rb)) {
748 case 1:
749 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
751 case 2:
752 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
753 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
755 default: // 3 or 4
756 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
760 RoadTypes cur_rts = IsRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
761 uint num_roadbits = 0;
762 if (build_over_road) {
763 /* There is a road, check if we can build road+tram stop over it. */
764 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
765 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
766 if (road_owner == OWNER_TOWN) {
767 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
768 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
769 CommandCost ret = CheckOwnership(road_owner);
770 if (ret.Failed()) return ret;
772 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
775 /* There is a tram, check if we can build road+tram stop over it. */
776 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
777 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
778 if (Company::IsValidID(tram_owner) &&
779 (!_settings_game.construction.road_stop_on_competitor_road ||
780 /* Disallow breaking end-of-line of someone else
781 * so trams can still reverse on this tile. */
782 HasExactlyOneBit(GetRoadBits(cur_tile, ROADTYPE_TRAM)))) {
783 CommandCost ret = CheckOwnership(tram_owner);
784 if (ret.Failed()) return ret;
786 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
789 /* Take into account existing roadbits. */
790 rts |= cur_rts;
791 } else {
792 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
793 if (ret.Failed()) return ret;
794 cost.AddCost(ret);
797 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
798 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
802 return cost;
806 * Checks if an airport can be built at the given area.
807 * @param tile_area Area to check.
808 * @param flags Operation to perform.
809 * @param station StationID of airport allowed in search area.
810 * @return The cost in case of success, or an error code if it failed.
812 static CommandCost CheckFlatLandAirport(TileArea tile_area, DoCommandFlag flags, StationID *station)
814 CommandCost cost(EXPENSES_CONSTRUCTION);
815 int allowed_z = -1;
817 TILE_AREA_LOOP(tile_cur, tile_area) {
818 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
819 if (ret.Failed()) return ret;
820 cost.AddCost(ret);
822 /* if station is set, then allow building on top of an already
823 * existing airport, either the one in *station if it is not
824 * INVALID_STATION, or anyone otherwise and store which one
825 * in *station */
826 if (station != NULL && IsStationTile(tile_cur)) {
827 if (!IsAirport(tile_cur)) {
828 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
829 } else {
830 StationID st = GetStationIndex(tile_cur);
831 if (*station == INVALID_STATION) {
832 *station = st;
833 } else if (*station != st) {
834 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
837 } else {
838 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
839 if (ret.Failed()) return ret;
840 cost.AddCost(ret);
844 return cost;
848 * Check whether we can expand the rail part of the given station.
849 * @param st the station to expand
850 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
851 * @param axis the axis of the newly build rail
852 * @return Succeeded or failed command.
854 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
856 TileArea cur_ta = st->train_station;
858 /* determine new size of train station region.. */
859 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
860 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
861 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
862 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
863 new_ta.tile = TileXY(x, y);
865 /* make sure the final size is not too big. */
866 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
867 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
870 return CommandCost();
873 static inline byte *CreateSingle(byte *layout, int n)
875 int i = n;
876 do *layout++ = 0; while (--i);
877 layout[((n - 1) >> 1) - n] = 2;
878 return layout;
881 static inline byte *CreateMulti(byte *layout, int n, byte b)
883 int i = n;
884 do *layout++ = b; while (--i);
885 if (n > 4) {
886 layout[0 - n] = 0;
887 layout[n - 1 - n] = 0;
889 return layout;
893 * Create the station layout for the given number of tracks and platform length.
894 * @param layout The layout to write to.
895 * @param numtracks The number of tracks to write.
896 * @param plat_len The length of the platforms.
897 * @param statspec The specification of the station to (possibly) get the layout from.
899 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
901 if (statspec != NULL && statspec->lengths >= plat_len &&
902 statspec->platforms[plat_len - 1] >= numtracks &&
903 statspec->layouts[plat_len - 1][numtracks - 1]) {
904 /* Custom layout defined, follow it. */
905 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
906 plat_len * numtracks);
907 return;
910 if (plat_len == 1) {
911 CreateSingle(layout, numtracks);
912 } else {
913 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
914 numtracks >>= 1;
916 while (--numtracks >= 0) {
917 layout = CreateMulti(layout, plat_len, 4);
918 layout = CreateMulti(layout, plat_len, 6);
924 * Find a nearby station that joins this station.
925 * @param pst 'return' pointer for the found station
926 * @param ta the area of the newly built station
927 * @param existing_station an existing station we build over
928 * @param station_to_join the station to join, if adjacent is set
929 * @param adjacent whether adjacent stations are allowed
930 * @param waypoint find waypoints, else stations
931 * @param error_message the error message when building a station on top of others
932 * @return command cost with the error or 'okay'
934 static CommandCost FindJoiningBaseStation (BaseStation **pst, TileArea ta,
935 StationID existing_station, StationID station_to_join, bool adjacent,
936 bool waypoint, StringID error_message)
938 BaseStation *st; // station to join
939 bool need_link; // need an adjacent piece of joined station
940 bool avoid_other; // avoid (other) adjacent stations
942 if (existing_station != INVALID_STATION) {
943 /* we are partially overbuilding a station */
944 if (adjacent && station_to_join != existing_station) {
945 /* you cannot join a different station */
946 return_cmd_error(error_message);
949 assert (BaseStation::IsValidID (existing_station));
950 st = BaseStation::Get (existing_station);
951 assert (st->IsWaypoint() == waypoint);
952 need_link = false;
953 avoid_other = !_settings_game.station.adjacent_stations;
954 } else if (!adjacent) {
955 /* join adjacent station if unique, else error out */
956 st = NULL;
957 need_link = true;
958 avoid_other = true;
959 } else if (station_to_join != INVALID_STATION) {
960 /* not overbuilding, and we want to join a given station */
961 st = BaseStation::GetIfValid (station_to_join);
962 if (st == NULL) return CMD_ERROR;
963 if (st->IsWaypoint() != waypoint) return CMD_ERROR;
964 need_link = st->IsInUse() && !_settings_game.station.distant_join_stations;
965 avoid_other = !_settings_game.station.adjacent_stations;
966 } else {
967 /* not overbuilding, and we want to build a new station */
968 st = NULL;
969 need_link = false;
970 avoid_other = !_settings_game.station.adjacent_stations;
973 if (need_link || avoid_other) {
974 ta.expand (1);
975 TILE_AREA_LOOP(tile_cur, ta) {
976 if (IsStationTile(tile_cur)) {
977 StationID t = GetStationIndex(tile_cur);
978 if (!BaseStation::IsValidID(t)) continue;
979 BaseStation *neighbour = BaseStation::Get(t);
980 if (neighbour->IsWaypoint() != waypoint) continue;
982 /* found an adjacent piece of a station */
983 if (st != NULL) {
984 /* wanted to join a given station */
985 if (t == st->index) {
986 /* found an adjacent piece */
987 need_link = false;
988 if (!avoid_other) break;
989 } else if (avoid_other) {
990 /* found a different station */
991 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
993 } else if (need_link) {
994 /* wanted to join any station */
995 st = neighbour;
996 need_link = false;
997 if (!avoid_other) break;
998 } else if (avoid_other) {
999 /* wanted to build a new station */
1000 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1006 /* tried to join a non-adjacent station but distant join is disabled? */
1007 if (st != NULL && need_link) return CMD_ERROR;
1009 *pst = st;
1011 return CommandCost();
1015 * Find a nearby station that joins this station.
1016 * @tparam T the class to find a station for
1017 * @param pst 'return' pointer for the found station
1018 * @param ta the area of the newly built station
1019 * @param existing_station an existing station we build over
1020 * @param station_to_join the station to join, if adjacent is set
1021 * @param adjacent whether adjacent stations are allowed
1022 * @param error_message the error message when building a station on top of others
1023 * @return command cost with the error or 'okay'
1025 template <class T>
1026 static inline CommandCost FindJoiningBaseStation (T **pst, TileArea ta,
1027 StationID existing_station, StationID station_to_join, bool adjacent,
1028 StringID error_message)
1030 BaseStation *bst;
1031 CommandCost ret = FindJoiningBaseStation (&bst, ta,
1032 existing_station, station_to_join, adjacent,
1033 T::IS_WAYPOINT, error_message);
1034 if (ret.Succeeded()) *pst = bst != NULL ? T::From (bst) : NULL;
1035 return ret;
1039 * Find a nearby waypoint that joins this waypoint.
1040 * @param existing_waypoint an existing waypoint we build over
1041 * @param waypoint_to_join the waypoint to join to
1042 * @param adjacent whether adjacent waypoints are allowed
1043 * @param ta the area of the newly build waypoint
1044 * @param wp 'return' pointer for the found waypoint
1045 * @return command cost with the error or 'okay'
1047 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
1049 return FindJoiningBaseStation<Waypoint> (wp, ta, existing_waypoint,
1050 waypoint_to_join, adjacent,
1051 STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST);
1055 * Common part of building various station parts and possibly attaching them to an existing one.
1056 * @param [out] st Station to attach to
1057 * @param area Area occupied by the new part
1058 * @param existing_station Existing station we build over
1059 * @param station_to_join Station to join, if adjacent is set
1060 * @param adjacent Whether adjacent stations are allowed
1061 * @param error_message Error message when building a station on top of others
1062 * @param flags Command flags
1063 * @param name_class Station naming class to use to generate the new station's name
1064 * @return Command error that occurred, if any
1066 static CommandCost BuildStationPart (Station **st, const TileArea &area,
1067 StationID existing_station, StationID station_to_join, bool adjacent,
1068 StringID error_message, DoCommandFlag flags, StationNaming name_class)
1070 CommandCost ret = FindJoiningBaseStation<Station> (st, area,
1071 existing_station, station_to_join, adjacent, error_message);
1072 if (ret.Failed()) return ret;
1074 /* Find a deleted station close to us */
1075 if (*st == NULL && !adjacent) *st = GetClosestDeletedStation(area.tile);
1077 if (*st != NULL) {
1078 if ((*st)->owner != _current_company) {
1079 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
1082 if (!(*st)->TestAddRect(area)) {
1083 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1085 } else {
1086 /* allocate and initialize new station */
1087 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
1089 if (flags & DC_EXEC) {
1090 *st = new Station(area.tile);
1092 (*st)->town = ClosestTownFromTile(area.tile);
1093 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
1095 if (Company::IsValidID(_current_company)) {
1096 SetBit((*st)->town->have_ratings, _current_company);
1101 return CommandCost();
1105 static void FreeTrainReservation(Train *v)
1107 FreeTrainTrackReservation(v);
1109 const RailPathPos pos = v->GetPos();
1110 if (!pos.in_wormhole() && IsRailStationTile(pos.tile)) SetRailStationPlatformReservation(pos, false);
1112 const RailPathPos rev = v->Last()->GetReversePos();
1113 if (!rev.in_wormhole() && IsRailStationTile(rev.tile)) SetRailStationPlatformReservation(rev, false);
1116 static void RestoreTrainReservation(Train *v)
1118 const RailPathPos pos = v->GetPos();
1119 if (!pos.in_wormhole() && IsRailStationTile(pos.tile)) SetRailStationPlatformReservation(pos, true);
1121 /* Check first if the train can have a reservation (not heading into a depot). */
1122 if (FreeTrainTrackReservation(v)) TryPathReserve(v, true, true);
1124 const RailPathPos rev = v->Last()->GetReversePos();
1125 if (!rev.in_wormhole() && IsRailStationTile(rev.tile)) SetRailStationPlatformReservation(rev, true);
1129 * Build rail station
1130 * @param tile_org northern most position of station dragging/placement
1131 * @param flags operation to perform
1132 * @param p1 various bitstuffed elements
1133 * - p1 = (bit 0- 3) - railtype
1134 * - p1 = (bit 4) - orientation (Axis)
1135 * - p1 = (bit 8-15) - number of tracks
1136 * - p1 = (bit 16-23) - platform length
1137 * - p1 = (bit 24) - allow stations directly adjacent to other stations.
1138 * @param p2 various bitstuffed elements
1139 * - p2 = (bit 0- 7) - custom station class
1140 * - p2 = (bit 8-15) - custom station id
1141 * - p2 = (bit 16-31) - station ID to join (INVALID_STATION if build new one)
1142 * @param text unused
1143 * @return the cost of this operation or an error
1145 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1147 /* Unpack parameters */
1148 RailType rt = Extract<RailType, 0, 4>(p1);
1149 Axis axis = Extract<Axis, 4, 1>(p1);
1150 byte numtracks = GB(p1, 8, 8);
1151 byte plat_len = GB(p1, 16, 8);
1152 bool adjacent = HasBit(p1, 24);
1154 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
1155 byte spec_index = GB(p2, 8, 8);
1156 StationID station_to_join = GB(p2, 16, 16);
1158 /* Does the authority allow this? */
1159 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1160 if (ret.Failed()) return ret;
1162 if (!ValParamRailtype(rt)) return CMD_ERROR;
1164 /* Check if the given station class is valid */
1165 if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
1166 const StationClass *statclass = StationClass::Get(spec_class);
1167 if (spec_index >= statclass->GetSpecCount()) return CMD_ERROR;
1168 const StationSpec *statspec = statclass->GetSpec(spec_index);
1170 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1172 int w_org, h_org;
1173 if (axis == AXIS_X) {
1174 w_org = plat_len;
1175 h_org = numtracks;
1176 } else {
1177 h_org = plat_len;
1178 w_org = numtracks;
1181 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1183 byte *layout_ptr = AllocaM(byte, numtracks * plat_len);
1184 GetStationLayout (layout_ptr, numtracks, plat_len, statspec);
1186 /* these values are those that will be stored in train_tile and station_platforms */
1187 TileArea new_location(tile_org, w_org, h_org);
1189 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1190 StationID est = INVALID_STATION;
1191 SmallVector<Train *, 4> affected_vehicles;
1192 /* Clear the land below the station. */
1193 CommandCost cost = CheckFlatLandRailStation (new_location, flags, axis, &est, rt, affected_vehicles, statspec, plat_len, numtracks, layout_ptr);
1194 if (cost.Failed()) return cost;
1195 /* Add construction expenses. */
1196 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
1197 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
1199 Station *st = NULL;
1200 ret = BuildStationPart (&st, new_location, est, station_to_join,
1201 adjacent, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST,
1202 flags, STATIONNAMING_RAIL);
1203 if (ret.Failed()) return ret;
1205 if (st != NULL && st->train_station.tile != INVALID_TILE) {
1206 CommandCost ret = CanExpandRailStation(st, new_location, axis);
1207 if (ret.Failed()) return ret;
1210 /* Check if we can allocate a custom stationspec to this station */
1211 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1212 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1214 if (statspec != NULL) {
1215 /* Perform NewStation checks */
1217 /* Check if the station size is permitted */
1218 if (HasBit(statspec->disallowed_platforms, min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, min(plat_len - 1, 7))) {
1219 return CMD_ERROR;
1222 /* Check if the station is buildable */
1223 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1224 uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
1225 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1229 if (flags & DC_EXEC) {
1230 st->train_station = new_location;
1231 st->AddFacility(FACIL_TRAIN, new_location.tile);
1233 st->rect.Add (TileArea (tile_org, w_org, h_org));
1235 if (statspec != NULL) {
1236 /* Include this station spec's animation trigger bitmask
1237 * in the station's cached copy. */
1238 st->cached_anim_triggers |= statspec->animation.triggers;
1241 Company *c = Company::Get(st->owner);
1243 TileIndexDiff delta_along = (axis == AXIS_X ? TileDiffXY (1, 0) : TileDiffXY (0, 1));
1244 TileIndexDiff delta_across = delta_along ^ TileDiffXY (1, 1); // perpendicular to delta_along
1246 TileIndex tile_track = tile_org;
1247 for (uint i = 0; i < numtracks; i++, tile_track += delta_across) {
1248 TileIndex tile = tile_track;
1249 for (uint j = 0; j < plat_len; j++, tile += delta_along) {
1250 byte layout = *layout_ptr++;
1251 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1252 /* Check for trains having a reservation for this tile. */
1253 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1254 if (v != NULL) {
1255 *affected_vehicles.Append() = v;
1256 FreeTrainReservation(v);
1260 /* Railtype can change when overbuilding. */
1261 if (IsRailStationTile(tile)) {
1262 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1263 c->infrastructure.station--;
1266 /* Remove animation if overbuilding */
1267 DeleteAnimatedTile(tile);
1268 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1269 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1270 /* Free the spec if we overbuild something */
1271 DeallocateSpecFromStation(st, old_specindex);
1273 SetCustomStationSpecIndex(tile, specindex);
1274 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1275 SetAnimationFrame(tile, 0);
1277 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1278 c->infrastructure.station++;
1280 if (statspec != NULL) {
1281 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1282 uint32 platinfo = GetPlatformInfo (AXIS_X, GetStationGfx(tile), plat_len, numtracks, j, i, false);
1284 /* As the station is not yet completely finished, the station does not yet exist. */
1285 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
1286 if (callback != CALLBACK_FAILED) {
1287 if (callback < 8) {
1288 SetStationGfx(tile, (callback & ~1) + axis);
1289 } else {
1290 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
1294 /* Trigger station animation -- after building? */
1295 TriggerStationAnimation(st, tile, SAT_BUILT);
1299 AddTrackToSignalBuffer (tile_track, AxisToTrack(axis), _current_company);
1300 YapfNotifyTrackLayoutChange();
1303 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
1304 RestoreTrainReservation(affected_vehicles[i]);
1307 /* Check whether we need to expand the reservation of trains already on the station. */
1308 TileIndex tile = tile_org;
1309 for (uint i = 0; i < numtracks; i++, tile += delta_across) {
1310 /* Don't even try to make eye candy parts reserved. */
1311 if (IsStationTileBlocked(tile)) continue;
1313 bool reservation = false;
1315 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1316 TileIndex platform_begin = tile;
1317 for (;;) {
1318 reservation |= HasStationReservation (platform_begin);
1319 TileIndex prev = platform_begin - delta_along;
1320 if (!IsCompatibleTrainStationTile (prev, platform_begin)) break;
1321 platform_begin = prev;
1324 TileIndex platform_end = tile;
1325 while (!reservation) {
1326 TileIndex next = platform_end + delta_along;
1327 if (!IsCompatibleTrainStationTile (next, platform_end)) break;
1328 platform_end = next;
1329 reservation = HasStationReservation (next);
1332 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1333 if (reservation) {
1334 SetRailStationPlatformReservation (platform_begin, AxisToDiagDir(axis), true);
1338 st->MarkTilesDirty(false);
1339 st->UpdateVirtCoord();
1340 UpdateStationAcceptance(st, false);
1341 st->RecomputeIndustriesNear();
1342 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
1343 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
1344 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1345 DirtyCompanyInfrastructureWindows(st->owner);
1348 return cost;
1352 * Remove a number of tiles from any rail station or waypoint within the area.
1353 * @param start tile of station piece to remove
1354 * @param flags operation to perform
1355 * @param p1 start_tile
1356 * @param p2 various bitstuffed elements
1357 * - p2 = bit 0 - if set keep the rail
1358 * @param waypoint remove from waypoints, else from stations
1359 * @return the cost of this operation or an error
1361 static CommandCost RemoveFromRailBaseStation (TileIndex start,
1362 DoCommandFlag flags, uint32 p1, uint32 p2, bool waypoint)
1364 TileIndex end = p1 == 0 ? start : p1;
1365 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1367 bool keep_rail = HasBit(p2, 0);
1369 TileArea ta(start, end);
1370 SmallVector<BaseStation *, 4> affected_stations;
1372 /* Count of the number of tiles removed */
1373 int quantity = 0;
1374 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1375 /* Accumulator for the errors seen during clearing. If no errors happen,
1376 * and the quantity is 0 there is no station. Otherwise it will be one
1377 * of the other error that got accumulated. */
1378 CommandCost error;
1380 /* Do the action for every tile into the area */
1381 TILE_AREA_LOOP(tile, ta) {
1382 /* Make sure the specified tile is a rail station */
1383 if (!HasStationTileRail(tile)) continue;
1385 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1386 CommandCost ret = EnsureNoVehicleOnGround(tile);
1387 error.AddCost(ret);
1388 if (ret.Failed()) continue;
1390 /* Check ownership of station */
1391 BaseStation *st = BaseStation::GetByTile (tile);
1392 if (st == NULL || st->IsWaypoint() != waypoint) continue;
1394 if (_current_company != OWNER_WATER) {
1395 CommandCost ret = CheckOwnership(st->owner);
1396 error.AddCost(ret);
1397 if (ret.Failed()) continue;
1400 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1401 quantity++;
1403 if (keep_rail || IsStationTileBlocked(tile)) {
1404 /* Don't refund the 'steel' of the track when we keep the
1405 * rail, or when the tile didn't have any rail at all. */
1406 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1409 if (flags & DC_EXEC) {
1410 /* read variables before the station tile is removed */
1411 uint specindex = GetCustomStationSpecIndex(tile);
1412 Track track = GetRailStationTrack(tile);
1413 Owner owner = GetTileOwner(tile);
1414 RailType rt = GetRailType(tile);
1415 Train *v = NULL;
1417 if (HasStationReservation(tile)) {
1418 v = GetTrainForReservation(tile, track);
1419 if (v != NULL) FreeTrainReservation(v);
1422 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1423 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1425 DoClearSquare(tile);
1426 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1427 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1428 Company::Get(owner)->infrastructure.station--;
1429 DirtyCompanyInfrastructureWindows(owner);
1431 st->AfterRemoveTile(tile);
1432 AddTrackToSignalBuffer(tile, track, owner);
1433 YapfNotifyTrackLayoutChange();
1435 DeallocateSpecFromStation(st, specindex);
1437 affected_stations.Include(st);
1439 if (v != NULL) RestoreTrainReservation(v);
1443 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1445 for (BaseStation **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1446 BaseStation *st = *stp;
1448 /* now we need to make the "spanned" area of the railway station smaller
1449 * if we deleted something at the edges.
1450 * we also need to adjust train_tile. */
1451 st->train_station.shrink_span (std::bind1st (std::mem_fun (&BaseStation::TileBelongsToRailStation), st));
1452 UpdateStationSign (st);
1454 /* if we deleted the whole station, delete the train facility. */
1455 if (st->train_station.tile == INVALID_TILE) {
1456 st->facilities &= ~FACIL_TRAIN;
1457 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1458 DeleteStationIfEmpty(st);
1462 total_cost.AddCost(quantity * _price[waypoint ? PR_CLEAR_WAYPOINT_RAIL : PR_CLEAR_STATION_RAIL]);
1464 if (!waypoint) {
1465 /* Do all station specific functions here. */
1466 for (BaseStation **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1467 Station *st = Station::From(*stp);
1469 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1470 st->MarkTilesDirty(false);
1471 st->RecomputeIndustriesNear();
1475 return total_cost;
1479 * Remove a single tile from a rail station.
1480 * This allows for custom-built station with holes and weird layouts
1481 * @param start tile of station piece to remove
1482 * @param flags operation to perform
1483 * @param p1 start_tile
1484 * @param p2 various bitstuffed elements
1485 * - p2 = bit 0 - if set keep the rail
1486 * @param text unused
1487 * @return the cost of this operation or an error
1489 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1491 return RemoveFromRailBaseStation (start, flags, p1, p2, false);
1495 * Remove a single tile from a waypoint.
1496 * This allows for custom-built waypoint with holes and weird layouts
1497 * @param start tile of waypoint piece to remove
1498 * @param flags operation to perform
1499 * @param p1 start_tile
1500 * @param p2 various bitstuffed elements
1501 * - p2 = bit 0 - if set keep the rail
1502 * @param text unused
1503 * @return the cost of this operation or an error
1505 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1507 return RemoveFromRailBaseStation (start, flags, p1, p2, true);
1512 * Remove a rail station/waypoint
1513 * @param st The station/waypoint to remove the rail part from
1514 * @param flags operation to perform
1515 * @param removal_cost the cost for removing a tile
1516 * @return cost or failure of operation
1518 static CommandCost RemoveRailStation (BaseStation *st, DoCommandFlag flags,
1519 Money removal_cost)
1521 /* Current company owns the station? */
1522 if (_current_company != OWNER_WATER) {
1523 CommandCost ret = CheckOwnership(st->owner);
1524 if (ret.Failed()) return ret;
1527 /* determine width and height of platforms */
1528 TileArea ta = st->train_station;
1530 assert(ta.w != 0 && ta.h != 0);
1532 CommandCost cost(EXPENSES_CONSTRUCTION);
1533 /* clear all areas of the station */
1534 TILE_AREA_LOOP(tile, ta) {
1535 /* only remove tiles that are actually train station tiles */
1536 if (!st->TileBelongsToRailStation(tile)) continue;
1538 CommandCost ret = EnsureNoVehicleOnGround(tile);
1539 if (ret.Failed()) return ret;
1541 cost.AddCost(removal_cost);
1542 if (flags & DC_EXEC) {
1543 /* read variables before the station tile is removed */
1544 Track track = GetRailStationTrack(tile);
1545 Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
1546 Train *v = NULL;
1547 if (HasStationReservation(tile)) {
1548 v = GetTrainForReservation (tile, track, true);
1550 if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1551 Company::Get(owner)->infrastructure.station--;
1552 DoClearSquare(tile);
1553 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1554 AddTrackToSignalBuffer(tile, track, owner);
1555 YapfNotifyTrackLayoutChange();
1556 if (v != NULL) TryPathReserve(v, true);
1560 if (flags & DC_EXEC) {
1561 st->AfterRemoveRect(st->train_station);
1563 st->train_station.Clear();
1565 st->facilities &= ~FACIL_TRAIN;
1567 free(st->speclist);
1568 st->num_specs = 0;
1569 st->speclist = NULL;
1570 st->cached_anim_triggers = 0;
1572 DirtyCompanyInfrastructureWindows(st->owner);
1573 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1574 UpdateStationSign (st);
1575 DeleteStationIfEmpty(st);
1578 return cost;
1582 * Remove a rail station
1583 * @param tile Tile of the station.
1584 * @param flags operation to perform
1585 * @return cost or failure of operation
1587 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1589 /* if there is flooding, remove platforms tile by tile */
1590 if (_current_company == OWNER_WATER) {
1591 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
1594 Station *st = Station::GetByTile(tile);
1595 CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1597 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
1599 return cost;
1603 * Remove a rail waypoint
1604 * @param tile Tile of the waypoint.
1605 * @param flags operation to perform
1606 * @return cost or failure of operation
1608 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1610 /* if there is flooding, remove waypoints tile by tile */
1611 if (_current_company == OWNER_WATER) {
1612 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
1615 return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1620 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1621 * @param st The Station to do the whole procedure for
1622 * @return a pointer to where to link a new RoadStop*
1624 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1626 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1628 if (*primary_stop == NULL) {
1629 /* we have no roadstop of the type yet, so write a "primary stop" */
1630 return primary_stop;
1631 } else {
1632 /* there are stops already, so append to the end of the list */
1633 RoadStop *stop = *primary_stop;
1634 while (stop->next != NULL) stop = stop->next;
1635 return &stop->next;
1639 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
1642 * Build a bus or truck stop.
1643 * @param tile Northernmost tile of the stop.
1644 * @param flags Operation to perform.
1645 * @param p1 bit 0..7: Width of the road stop.
1646 * bit 8..15: Length of the road stop.
1647 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1648 * bit 1: 0 For normal stops, 1 for drive-through.
1649 * bit 2..3: The roadtypes.
1650 * bit 5: Allow stations directly adjacent to other stations.
1651 * bit 6..7: Entrance direction (#DiagDirection).
1652 * bit 16..31: Station ID to join (INVALID_STATION if build new one).
1653 * @param text Unused.
1654 * @return The cost of this operation or an error.
1656 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1658 bool type = HasBit(p2, 0);
1659 bool is_drive_through = HasBit(p2, 1);
1660 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
1661 StationID station_to_join = GB(p2, 16, 16);
1663 uint8 width = (uint8)GB(p1, 0, 8);
1664 uint8 lenght = (uint8)GB(p1, 8, 8);
1666 /* Check if the requested road stop is too big */
1667 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1668 /* Check for incorrect width / length. */
1669 if (width == 0 || lenght == 0) return CMD_ERROR;
1670 /* Check if the first tile and the last tile are valid */
1671 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
1673 TileArea roadstop_area(tile, width, lenght);
1675 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
1677 /* Trams only have drive through stops */
1678 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
1680 DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
1682 /* Safeguard the parameters. */
1683 if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
1684 /* If it is a drive-through stop, check for valid axis. */
1685 if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
1687 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
1688 if (ret.Failed()) return ret;
1690 /* Total road stop cost. */
1691 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
1692 StationID est = INVALID_STATION;
1693 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
1694 if (ret.Failed()) return ret;
1695 cost.AddCost(ret);
1697 Station *st = NULL;
1698 ret = BuildStationPart (&st, roadstop_area, est, station_to_join,
1699 HasBit (p2, 5), STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST,
1700 flags, STATIONNAMING_ROAD);
1701 if (ret.Failed()) return ret;
1703 /* Check if this number of road stops can be allocated. */
1704 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);
1706 if (flags & DC_EXEC) {
1707 /* Check every tile in the area. */
1708 TILE_AREA_LOOP(cur_tile, roadstop_area) {
1709 RoadTypes cur_rts = (IsRoadTile(cur_tile) || IsStationTile(cur_tile)) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
1710 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
1711 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
1713 if (IsStationTile(cur_tile) && IsRoadStop(cur_tile)) {
1714 RemoveRoadStop(cur_tile, flags);
1717 RoadStop *road_stop = new RoadStop(cur_tile);
1718 /* Insert into linked list of RoadStops. */
1719 RoadStop **currstop = FindRoadStopSpot(type, st);
1720 *currstop = road_stop;
1722 if (type) {
1723 st->truck_station.Add(cur_tile);
1724 } else {
1725 st->bus_station.Add(cur_tile);
1728 /* Initialize an empty station. */
1729 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
1731 st->rect.Add (cur_tile);
1733 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
1734 if (is_drive_through) {
1735 /* Update company infrastructure counts. If the current tile is a normal
1736 * road tile, count only the new road bits needed to get a full diagonal road. */
1737 RoadType rt;
1738 FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
1739 Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
1740 if (c != NULL) {
1741 c->infrastructure.road[rt] += 2 - (IsRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
1742 DirtyCompanyInfrastructureWindows(c->index);
1746 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
1747 road_stop->MakeDriveThrough();
1748 } else {
1749 /* Non-drive-through stop never overbuild and always count as two road bits. */
1750 Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
1751 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
1753 Company::Get(st->owner)->infrastructure.station++;
1754 DirtyCompanyInfrastructureWindows(st->owner);
1756 MarkTileDirtyByTile(cur_tile);
1760 if (st != NULL) {
1761 st->UpdateVirtCoord();
1762 UpdateStationAcceptance(st, false);
1763 st->RecomputeIndustriesNear();
1764 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
1765 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
1766 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
1768 return cost;
1773 * Remove a bus station/truck stop
1774 * @param tile TileIndex been queried
1775 * @param flags operation to perform
1776 * @return cost or failure of operation
1778 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
1780 Station *st = Station::GetByTile(tile);
1782 if (_current_company != OWNER_WATER) {
1783 CommandCost ret = CheckOwnership(st->owner);
1784 if (ret.Failed()) return ret;
1787 bool is_truck = IsTruckStop(tile);
1789 RoadStop **primary_stop;
1790 RoadStop *cur_stop;
1791 if (is_truck) { // truck stop
1792 primary_stop = &st->truck_stops;
1793 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
1794 } else {
1795 primary_stop = &st->bus_stops;
1796 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
1799 assert(cur_stop != NULL);
1801 /* don't do the check for drive-through road stops when company bankrupts */
1802 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
1803 /* remove the 'going through road stop' status from all vehicles on that tile */
1804 VehicleTileIterator iter (tile);
1805 while (!iter.finished()) {
1806 Vehicle *v = iter.next();
1807 if (v->type == VEH_ROAD) {
1808 /* Okay... we are a road vehicle on a drive through road stop.
1809 * But that road stop has just been removed, so we need to make
1810 * sure we are in a valid state... however, vehicles can also
1811 * turn on road stop tiles, so only clear the 'road stop' state
1812 * bits and only when the state was 'in road stop', otherwise
1813 * we'll end up clearing the turn around bits. */
1814 RoadVehicle *rv = RoadVehicle::From(v);
1815 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
1818 } else {
1819 CommandCost ret = EnsureNoVehicleOnGround(tile);
1820 if (ret.Failed()) return ret;
1823 if (flags & DC_EXEC) {
1824 if (*primary_stop == cur_stop) {
1825 /* removed the first stop in the list */
1826 *primary_stop = cur_stop->next;
1827 /* removed the only stop? */
1828 if (*primary_stop == NULL) {
1829 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
1831 } else {
1832 /* tell the predecessor in the list to skip this stop */
1833 RoadStop *pred = *primary_stop;
1834 while (pred->next != cur_stop) pred = pred->next;
1835 pred->next = cur_stop->next;
1838 /* Update company infrastructure counts. */
1839 RoadType rt;
1840 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
1841 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
1842 if (c != NULL) {
1843 c->infrastructure.road[rt] -= 2;
1844 DirtyCompanyInfrastructureWindows(c->index);
1847 Company::Get(st->owner)->infrastructure.station--;
1848 DirtyCompanyInfrastructureWindows(st->owner);
1850 if (IsDriveThroughStopTile(tile)) {
1851 /* Clears the tile for us */
1852 cur_stop->ClearDriveThrough();
1853 } else {
1854 DoClearSquare(tile);
1857 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
1858 delete cur_stop;
1860 /* Make sure no vehicle is going to the old roadstop */
1861 RoadVehicle *v;
1862 FOR_ALL_ROADVEHICLES(v) {
1863 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
1864 v->dest_tile == tile) {
1865 v->dest_tile = v->GetOrderStationLocation(st->index);
1869 st->AfterRemoveTile(tile);
1871 UpdateStationSign (st);
1872 st->RecomputeIndustriesNear();
1873 DeleteStationIfEmpty(st);
1875 /* Update the tile area of the truck/bus stop */
1876 if (is_truck) {
1877 st->truck_station.Clear();
1878 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
1879 } else {
1880 st->bus_station.Clear();
1881 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
1885 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
1889 * Remove bus or truck stops.
1890 * @param tile Northernmost tile of the removal area.
1891 * @param flags Operation to perform.
1892 * @param p1 bit 0..7: Width of the removal area.
1893 * bit 8..15: Height of the removal area.
1894 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1895 * @param p2 bit 1: 0 to keep roads of all drive-through stops, 1 to remove them.
1896 * @param text Unused.
1897 * @return The cost of this operation or an error.
1899 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1901 uint8 width = (uint8)GB(p1, 0, 8);
1902 uint8 height = (uint8)GB(p1, 8, 8);
1903 bool keep_drive_through_roads = !HasBit(p2, 1);
1905 /* Check for incorrect width / height. */
1906 if (width == 0 || height == 0) return CMD_ERROR;
1907 /* Check if the first tile and the last tile are valid */
1908 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
1909 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
1910 if (!keep_drive_through_roads && (flags & DC_BANKRUPT)) return CMD_ERROR;
1912 TileArea roadstop_area(tile, width, height);
1914 CommandCost cost(EXPENSES_CONSTRUCTION);
1915 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
1916 bool had_success = false;
1918 TILE_AREA_LOOP(cur_tile, roadstop_area) {
1919 /* Make sure the specified tile is a road stop of the correct type */
1920 if (!IsStationTile(cur_tile) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
1922 /* Save information on to-be-restored roads before the stop is removed. */
1923 RoadTypes rts = ROADTYPES_NONE;
1924 RoadBits road_bits = ROAD_NONE;
1925 Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
1926 assert_compile(lengthof(road_owner) == ROADTYPE_END);
1927 if (IsDriveThroughStopTile(cur_tile)) {
1928 RoadType rt;
1929 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(cur_tile)) {
1930 road_owner[rt] = GetRoadOwner(cur_tile, rt);
1931 /* If we don't want to preserve our roads then restore only roads of others. */
1932 if (keep_drive_through_roads || road_owner[rt] != _current_company) SetBit(rts, rt);
1934 road_bits = AxisToRoadBits (GetRoadStopAxis (cur_tile));
1937 CommandCost ret = RemoveRoadStop(cur_tile, flags);
1938 if (ret.Failed()) {
1939 last_error = ret;
1940 continue;
1942 cost.AddCost(ret);
1943 had_success = true;
1945 /* Restore roads. */
1946 if ((flags & DC_EXEC) && rts != ROADTYPES_NONE) {
1947 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile)->index,
1948 road_owner[ROADTYPE_ROAD], road_owner[ROADTYPE_TRAM]);
1950 /* Update company infrastructure counts. */
1951 RoadType rt;
1952 FOR_EACH_SET_ROADTYPE(rt, rts) {
1953 Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
1954 if (c != NULL) {
1955 c->infrastructure.road[rt] += CountBits(road_bits);
1956 DirtyCompanyInfrastructureWindows(c->index);
1962 return had_success ? cost : last_error;
1966 * Computes the minimal distance from town's xy to any airport's tile.
1967 * @param att Airport tile table
1968 * @param airport_tile Airport reference tile
1969 * @param town_tile town's tile (t->xy)
1970 * @return minimal manhattan distance from town_tile to any airport's tile
1972 static uint GetMinimalAirportDistanceToTile (const AirportTileTable *att,
1973 TileIndex airport_tile, TileIndex town_tile)
1975 uint mindist = UINT_MAX;
1977 for (AirportTileTableIterator iter (att, airport_tile); iter != INVALID_TILE; ++iter) {
1978 mindist = min (mindist, DistanceManhattan (town_tile, iter));
1981 return mindist;
1985 * Get a possible noise reduction factor based on distance from town center.
1986 * The further you get, the less noise you generate.
1987 * So all those folks at city council can now happily slee... work in their offices
1988 * @param as airport information
1989 * @param layout Airport layout
1990 * @param airport_tile Airport reference tile
1991 * @param town_tile TileIndex of town's center, the one who will receive the airport's candidature
1992 * @return the noise that will be generated, according to distance
1994 uint8 GetAirportNoiseLevelForTown (const AirportSpec *as, uint layout,
1995 TileIndex airport_tile, TileIndex town_tile)
1997 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
1998 * So no need to go any further*/
1999 if (as->noise_level < 2) return as->noise_level;
2001 uint distance = GetMinimalAirportDistanceToTile (as->table[layout], airport_tile, town_tile);
2003 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2004 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2005 * Basically, it says that the less tolerant a town is, the bigger the distance before
2006 * an actual decrease can be granted */
2007 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2009 /* now, we want to have the distance segmented using the distance judged bareable by town
2010 * This will give us the coefficient of reduction the distance provides. */
2011 uint noise_reduction = distance / town_tolerance_distance;
2013 /* If the noise reduction equals the airport noise itself, don't give it for free.
2014 * Otherwise, simply reduce the airport's level. */
2015 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2019 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2020 * If two towns have the same distance, town with lower index is returned.
2021 * @param as airport's description
2022 * @param layout Airport layout
2023 * @param tile Airport reference tile
2024 * @return nearest town to airport
2026 Town *AirportGetNearestTown (const AirportSpec *as, uint layout, TileIndex tile)
2028 Town *t, *nearest = NULL;
2029 uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2030 uint mindist = UINT_MAX - add; // prevent overflow
2031 const AirportTileTable *att = as->table[layout];
2032 FOR_ALL_TOWNS(t) {
2033 if (DistanceManhattan (t->xy, tile) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
2034 uint dist = GetMinimalAirportDistanceToTile (att, tile, t->xy);
2035 if (dist < mindist) {
2036 nearest = t;
2037 mindist = dist;
2042 return nearest;
2046 /** Recalculate the noise generated by the airports of each town */
2047 void UpdateAirportsNoise()
2049 Town *t;
2050 const Station *st;
2052 FOR_ALL_TOWNS(t) t->noise_reached = 0;
2054 FOR_ALL_STATIONS(st) {
2055 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2056 const AirportSpec *as = st->airport.GetSpec();
2057 Town *nearest = AirportGetNearestTown (as, st->airport.layout, st->airport.tile);
2058 nearest->noise_reached += GetAirportNoiseLevelForTown (as, st->airport.layout, st->airport.tile, nearest->xy);
2065 * Checks if an airport can be removed (no aircraft on it or landing)
2066 * @param st Station whose airport is to be removed
2067 * @param flags Operation to perform
2068 * @return Cost or failure of operation
2070 static CommandCost CanRemoveAirport(Station *st, DoCommandFlag flags)
2072 const Aircraft *a;
2073 FOR_ALL_AIRCRAFT(a) {
2074 if (!a->IsNormalAircraft()) continue;
2075 if (a->targetairport == st->index && a->state != FLYING)
2076 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2079 CommandCost cost(EXPENSES_CONSTRUCTION);
2081 TILE_AREA_LOOP(tile_cur, st->airport) {
2082 if (!st->TileBelongsToAirport(tile_cur)) continue;
2084 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2085 if (ret.Failed()) return ret;
2087 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2090 return cost;
2095 * Place an Airport.
2096 * @param tile tile where airport will be built
2097 * @param flags operation to perform
2098 * @param p1
2099 * - p1 = (bit 0- 7) - airport type, @see airport.h
2100 * - p1 = (bit 8-15) - airport layout
2101 * @param p2 various bitstuffed elements
2102 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2103 * - p2 = (bit 16-31) - station ID to join (INVALID_STATION if build new one)
2104 * @param text unused
2105 * @return the cost of this operation or an error
2107 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2109 StationID station_to_join = GB(p2, 16, 16);
2110 byte airport_type = GB(p1, 0, 8);
2111 byte layout = GB(p1, 8, 8);
2113 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2115 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2116 if (ret.Failed()) return ret;
2118 /* Check if a valid, buildable airport was chosen for construction */
2119 const AirportSpec *as = AirportSpec::Get(airport_type);
2120 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
2122 Direction rotation = as->rotation[layout];
2123 int w = as->size_x;
2124 int h = as->size_y;
2125 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2126 TileArea airport_area = TileArea(tile, w, h);
2128 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2129 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2132 StationID est = INVALID_STATION;
2133 CommandCost cost = CheckFlatLandAirport(airport_area, flags, &est);
2134 if (cost.Failed()) return cost;
2136 Station *st = NULL;
2137 ret = BuildStationPart (&st, airport_area, est, station_to_join,
2138 HasBit (p2, 0), STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST,
2139 flags, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2140 if (ret.Failed()) return ret;
2142 /* action to be performed */
2143 enum {
2144 AIRPORT_NEW, // airport is a new station
2145 AIRPORT_ADD, // add an airport to an existing station
2146 AIRPORT_UPGRADE, // upgrade the airport in a station
2147 } action =
2148 (est != INVALID_STATION) ? AIRPORT_UPGRADE :
2149 (st != NULL) ? AIRPORT_ADD : AIRPORT_NEW;
2151 if (action == AIRPORT_ADD && st->airport.tile != INVALID_TILE) {
2152 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2155 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2156 Town *nearest = AirportGetNearestTown (as, layout, tile);
2157 uint newnoise_level = nearest->noise_reached + GetAirportNoiseLevelForTown (as, layout, tile, nearest->xy);
2159 if (action == AIRPORT_UPGRADE) {
2160 const AirportSpec *old_as = st->airport.GetSpec();
2161 Town *old_nearest = AirportGetNearestTown (old_as, st->airport.layout, st->airport.tile);
2162 if (old_nearest == nearest) {
2163 newnoise_level -= GetAirportNoiseLevelForTown (old_as, st->airport.layout, st->airport.tile, nearest->xy);
2167 /* Check if local auth would allow a new airport */
2168 StringID authority_refuse_message = STR_NULL;
2169 Town *authority_refuse_town = NULL;
2171 if (_settings_game.economy.station_noise_level) {
2172 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2173 if (newnoise_level > nearest->MaxTownNoise()) {
2174 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2175 authority_refuse_town = nearest;
2177 } else if (action != AIRPORT_UPGRADE) {
2178 Town *t = ClosestTownFromTile(tile);
2179 uint num = 0;
2180 const Station *st;
2181 FOR_ALL_STATIONS(st) {
2182 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2184 if (num >= 2) {
2185 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2186 authority_refuse_town = t;
2190 if (authority_refuse_message != STR_NULL) {
2191 SetDParam(0, authority_refuse_town->index);
2192 return_cmd_error(authority_refuse_message);
2195 if (action == AIRPORT_UPGRADE) {
2196 /* check that the old airport can be removed */
2197 CommandCost r = CanRemoveAirport(st, flags);
2198 if (r.Failed()) return r;
2199 cost.AddCost(r);
2202 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2203 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2206 if (flags & DC_EXEC) {
2207 if (action == AIRPORT_UPGRADE) {
2208 /* delete old airport if upgrading */
2209 const AirportSpec *old_as = st->airport.GetSpec();
2210 Town *old_nearest = AirportGetNearestTown (old_as, st->airport.layout, st->airport.tile);
2212 if (old_nearest != nearest) {
2213 old_nearest->noise_reached -= GetAirportNoiseLevelForTown (old_as, st->airport.layout, st->airport.tile, old_nearest->xy);
2214 if (_settings_game.economy.station_noise_level) {
2215 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2219 TILE_AREA_LOOP(tile_cur, st->airport) {
2220 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
2221 DeleteAnimatedTile(tile_cur);
2222 DoClearSquare(tile_cur);
2223 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2226 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2227 DeleteWindowById(
2228 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
2232 st->AfterRemoveRect(st->airport);
2233 st->airport.Clear();
2236 /* Always add the noise, so there will be no need to recalculate when option toggles */
2237 nearest->noise_reached = newnoise_level;
2239 st->AddFacility(FACIL_AIRPORT, tile);
2240 st->airport.type = airport_type;
2241 st->airport.layout = layout;
2242 st->airport.flags = 0;
2243 st->airport.rotation = rotation;
2245 st->rect.Add (TileArea (tile, w, h));
2247 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2248 MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2249 SetStationTileRandomBits(iter, GB(Random(), 0, 4));
2250 st->airport.Add(iter);
2252 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
2255 /* Only call the animation trigger after all tiles have been built */
2256 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2257 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2260 if (action != AIRPORT_NEW) UpdateAirplanesOnNewStation(st);
2262 if (action == AIRPORT_UPGRADE) {
2263 UpdateStationSign (st);
2264 } else {
2265 Company::Get(st->owner)->infrastructure.airport++;
2266 DirtyCompanyInfrastructureWindows(st->owner);
2267 st->UpdateVirtCoord();
2270 UpdateStationAcceptance(st, false);
2271 st->RecomputeIndustriesNear();
2272 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
2273 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
2274 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2276 if (_settings_game.economy.station_noise_level) {
2277 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2281 return cost;
2285 * Remove an airport
2286 * @param tile TileIndex been queried
2287 * @param flags operation to perform
2288 * @return cost or failure of operation
2290 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2292 Station *st = Station::GetByTile(tile);
2294 if (_current_company != OWNER_WATER) {
2295 CommandCost ret = CheckOwnership(st->owner);
2296 if (ret.Failed()) return ret;
2299 CommandCost cost = CanRemoveAirport(st, flags);
2300 if (cost.Failed()) return cost;
2302 if (flags & DC_EXEC) {
2303 const AirportSpec *as = st->airport.GetSpec();
2304 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2305 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2306 * need of recalculation */
2307 Town *nearest = AirportGetNearestTown (as, st->airport.layout, st->airport.tile);
2308 nearest->noise_reached -= GetAirportNoiseLevelForTown (as, st->airport.layout, st->airport.tile, nearest->xy);
2310 TILE_AREA_LOOP(tile_cur, st->airport) {
2311 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
2312 DeleteAnimatedTile(tile_cur);
2313 DoClearSquare(tile_cur);
2314 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2317 /* Clear the persistent storage. */
2318 delete st->airport.psa;
2320 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2321 DeleteWindowById(
2322 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
2326 st->AfterRemoveRect(st->airport);
2328 st->airport.Clear();
2329 st->facilities &= ~FACIL_AIRPORT;
2331 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2333 if (_settings_game.economy.station_noise_level) {
2334 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2337 Company::Get(st->owner)->infrastructure.airport--;
2338 DirtyCompanyInfrastructureWindows(st->owner);
2340 UpdateStationSign (st);
2341 st->RecomputeIndustriesNear();
2342 DeleteStationIfEmpty(st);
2343 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2346 return cost;
2350 * Open/close an airport to incoming aircraft.
2351 * @param tile Unused.
2352 * @param flags Operation to perform.
2353 * @param p1 Station ID of the airport.
2354 * @param p2 Unused.
2355 * @param text unused
2356 * @return the cost of this operation or an error
2358 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2360 if (!Station::IsValidID(p1)) return CMD_ERROR;
2361 Station *st = Station::Get(p1);
2363 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2365 CommandCost ret = CheckOwnership(st->owner);
2366 if (ret.Failed()) return ret;
2368 if (flags & DC_EXEC) {
2369 st->airport.flags ^= AIRPORT_CLOSED_block;
2370 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2372 return CommandCost();
2376 * Tests whether the company's vehicles have this station in orders
2377 * @param station station ID
2378 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2379 * @param company company ID
2381 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2383 const Vehicle *v;
2384 FOR_ALL_VEHICLES(v) {
2385 if ((v->owner == company) == include_company) {
2386 const Order *order;
2387 FOR_VEHICLE_ORDERS(v, order) {
2388 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
2389 return true;
2394 return false;
2397 /** Information about dock tile area for a given direction. */
2398 struct DockTileArea {
2399 CoordDiff offset; ///< offset to northern tile
2400 byte width; ///< width of dock area
2401 byte height; ///< height of dock area
2405 * Build a dock/haven.
2406 * @param tile tile where dock will be built
2407 * @param flags operation to perform
2408 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
2409 * @param p2 bit 16-31: station ID to join (INVALID_STATION if build new one)
2410 * @param text unused
2411 * @return the cost of this operation or an error
2413 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2415 static const DockTileArea dock_tilearea[DIAGDIR_END] = {
2416 { { -1, 0 }, 2, 1 },
2417 { { 0, 0 }, 1, 2 },
2418 { { 0, 0 }, 2, 1 },
2419 { { 0, -1 }, 1, 2 },
2422 StationID station_to_join = GB(p2, 16, 16);
2424 Slope slope = GetTileSlope (tile);
2425 DiagDirection direction = GetInclinedSlopeDirection (slope);
2426 TileArea dock_area;
2427 WaterClass wc;
2428 if (direction != INVALID_DIAGDIR) {
2429 /* Docks cannot be placed on rapids */
2430 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2432 direction = ReverseDiagDir(direction);
2434 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2435 if (ret.Failed()) return ret;
2437 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2438 if (ret.Failed()) return ret;
2440 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2442 int h;
2443 if (!IsWaterTile (tile_cur) || !IsTileFlat (tile_cur, &h)) {
2444 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2447 if (HasBridgeAbove (tile_cur)
2448 && (GetBridgeHeight (GetSouthernBridgeEnd (tile_cur)) < h + 2)) {
2449 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2452 /* Get the water class of the water tile before it is cleared.*/
2453 wc = GetWaterClass (tile_cur);
2455 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2456 if (ret.Failed()) return ret;
2458 tile_cur += TileOffsByDiagDir(direction);
2459 if (!IsWaterTile(tile_cur) || !IsTileFlat(tile_cur)) {
2460 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2463 dock_area = TileArea(tile + ToTileIndexDiff(dock_tilearea[direction].offset),
2464 dock_tilearea[direction].width, dock_tilearea[direction].height);
2465 } else if (slope == SLOPE_FLAT) {
2466 if (!HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2468 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2469 if (ret.Failed()) return ret;
2471 /* Get the water class of the water tile before it is cleared.*/
2472 wc = GetWaterClass (tile);
2473 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2474 if (ret.Failed()) return ret;
2476 dock_area = TileArea (tile);
2477 } else {
2478 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2481 /* middle */
2482 Station *st = NULL;
2483 CommandCost ret = BuildStationPart (&st, dock_area, INVALID_STATION,
2484 station_to_join, HasBit (p1, 0), INVALID_STRING_ID,
2485 flags, STATIONNAMING_DOCK);
2486 if (ret.Failed()) return ret;
2488 /* Check if we can allocate a new dock. */
2489 if (!Dock::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_DOCKS);
2491 if (flags & DC_EXEC) {
2492 Dock **dl = &st->docks;
2493 while (*dl != NULL) dl = &(*dl)->next;
2495 *dl = new Dock(tile);
2496 st->dock_area.Add(dock_area);
2498 st->AddFacility(FACIL_DOCK, tile);
2500 st->rect.Add (dock_area);
2502 /* If the water part of the dock is on a canal, update infrastructure counts.
2503 * This is needed as we've unconditionally cleared that tile before. */
2504 if (wc == WATER_CLASS_CANAL) {
2505 Company::Get(st->owner)->infrastructure.water++;
2507 Company::Get(st->owner)->infrastructure.station += 2;
2508 DirtyCompanyInfrastructureWindows(st->owner);
2510 if (direction != INVALID_DIAGDIR) {
2511 MakeDock (tile, st->owner, st->index, direction, wc);
2512 } else {
2513 MakeDockBuoy (tile, st->owner, st->index, wc);
2516 st->UpdateVirtCoord();
2517 UpdateStationAcceptance(st, false);
2518 st->RecomputeIndustriesNear();
2519 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
2520 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
2521 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
2524 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2528 * Remove a dock
2529 * @param tile TileIndex been queried
2530 * @param flags operation to perform
2531 * @return cost or failure of operation
2533 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2535 assert(IsDock(tile));
2537 Station *st = Station::GetByTile(tile);
2538 CommandCost ret = CheckOwnership(st->owner);
2539 if (ret.Failed()) return ret;
2541 Dock **d = &st->docks;
2542 TileIndex tile1, tile2;
2543 while ( tile1 = (*d)->xy, tile2 = GetOtherDockTile(tile1),
2544 tile != tile1 && tile != tile2 ) {
2545 /* the dock should really be there, so no check for NULL */
2546 d = &(*d)->next;
2549 ret = EnsureNoVehicleOnGround(tile1);
2550 if (ret.Succeeded() && tile2 != INVALID_TILE) ret = EnsureNoVehicleOnGround(tile2);
2551 if (ret.Failed()) return ret;
2553 if (flags & DC_EXEC) {
2554 TileIndex docking_location = GetDockingTile(tile1);
2556 TileArea dock_area (tile1);
2557 if (tile2 != INVALID_TILE) {
2558 DoClearSquare (tile1);
2559 MarkTileDirtyByTile (tile1);
2560 MakeWaterKeepingClass (tile2, st->owner);
2561 dock_area.Add (tile2);
2562 } else {
2563 MakeWaterKeepingClass (tile1, st->owner);
2565 st->AfterRemoveRect (dock_area);
2567 Dock *next = (*d)->next;
2568 delete *d;
2569 *d = next;
2570 if (next == NULL && d == &st->docks) st->facilities &= ~FACIL_DOCK;
2572 Company::Get(st->owner)->infrastructure.station -= 2;
2573 DirtyCompanyInfrastructureWindows(st->owner);
2575 /* Update the tile area of the docks */
2576 st->dock_area.Clear();
2577 for (const Dock *dock = st->docks; dock != NULL; dock = dock->next) {
2578 st->dock_area.Add(dock->xy);
2579 TileIndex other = GetOtherDockTile (dock->xy);
2580 if (other != INVALID_TILE) st->dock_area.Add (other);
2583 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
2584 UpdateStationSign (st);
2585 st->RecomputeIndustriesNear();
2586 DeleteStationIfEmpty(st);
2588 /* All ships that were going to our station, can't go to it anymore.
2589 * Just clear the order, then automatically the next appropriate order
2590 * will be selected and in case of no appropriate order it will just
2591 * wander around the world. */
2592 Ship *s;
2593 FOR_ALL_SHIPS(s) {
2594 if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
2595 s->LeaveStation();
2598 if (s->dest_tile == docking_location) {
2599 s->dest_tile = 0;
2600 s->current_order.Clear();
2605 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
2608 #include "table/station_land.h"
2610 const DrawTileSprites *GetDefaultStationTileLayout (void)
2612 return _station_display_datas_rail;
2616 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
2617 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
2618 * is set to the overlay to draw.
2619 * @param ti Positional info for the tile to decide snowyness etc. May be NULL.
2620 * @param [in,out] ground Groundsprite to draw.
2621 * @param [out] overlay_offset Overlay to draw.
2622 * @return true if overlay can be drawn.
2624 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
2626 bool snow_desert;
2627 switch (*ground) {
2628 case SPR_RAIL_TRACK_X:
2629 snow_desert = false;
2630 *overlay_offset = RTO_X;
2631 break;
2633 case SPR_RAIL_TRACK_Y:
2634 snow_desert = false;
2635 *overlay_offset = RTO_Y;
2636 break;
2638 case SPR_RAIL_TRACK_X_SNOW:
2639 snow_desert = true;
2640 *overlay_offset = RTO_X;
2641 break;
2643 case SPR_RAIL_TRACK_Y_SNOW:
2644 snow_desert = true;
2645 *overlay_offset = RTO_Y;
2646 break;
2648 default:
2649 return false;
2652 if (ti != NULL) {
2653 /* Decide snow/desert from tile */
2654 switch (_settings_game.game_creation.landscape) {
2655 case LT_ARCTIC:
2656 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
2657 break;
2659 case LT_TROPIC:
2660 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
2661 break;
2663 default:
2664 break;
2668 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
2669 return true;
2672 static void DrawTile_Airport (TileInfo *ti)
2674 StationGfx gfx = GetAirportGfx (ti->tile);
2675 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
2676 const AirportTileSpec *ats = AirportTileSpec::Get (gfx);
2677 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile (ti, Station::GetByTile(ti->tile), gfx, ats)) {
2678 return;
2680 /* No sprite group (or no valid one) found, meaning no graphics associated.
2681 * Use the substitute one instead */
2682 assert (ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
2683 gfx = ats->grf_prop.subst_id;
2686 const DrawTileSprites *t = &_station_display_datas_airport[gfx];
2687 PalSpriteID ground = t->ground;
2688 const DrawTileSeqStruct *const *seq;
2689 bool anim = true;
2690 switch (gfx) {
2691 case APT_GRASS_FENCE_NE_FLAG:
2692 case APT_GRASS_FENCE_NE_FLAG_2:
2693 seq = _station_display_datas_airport_flag_grass_fence_ne;
2694 break;
2695 case APT_RADAR_GRASS_FENCE_SW:
2696 case APT_RADAR_FENCE_SW:
2697 seq = _station_display_datas_airport_radar_fence_sw;
2698 break;
2699 case APT_RADAR_FENCE_NE:
2700 seq = _station_display_datas_airport_radar_fence_ne;
2701 break;
2702 default:
2703 seq = &t->seq;
2704 anim = false;
2705 break;
2707 if (anim) seq += GetAnimationFrame (ti->tile);
2709 if (ti->tileh != SLOPE_FLAT) {
2710 DrawFoundation (ti, FOUNDATION_LEVELED);
2713 Owner owner = GetTileOwner (ti->tile);
2714 PaletteID palette = COMPANY_SPRITE_COLOUR(owner);
2716 SpriteID image = ground.sprite;
2717 PaletteID pal = ground.pal;
2718 DrawGroundSprite (ti, image, GroundSpritePaletteTransform (image, pal, palette));
2720 DrawOrigTileSeq (ti, *seq, TO_BUILDINGS, palette);
2724 * Draw custom foundations for a station tile.
2725 * @param ti TileInfo of the tile.
2726 * @param statspec Station spec.
2727 * @param st Station.
2728 * @param tile_layout Tile layout.
2729 * @return Whether foundations were actually drawn.
2731 static bool DrawRailStationFoundation (TileInfo *ti,
2732 const StationSpec *statspec, BaseStation *st, uint tile_layout)
2734 /* Check whether the foundation continues beyond the tile's upper sides. */
2735 uint edge_info = GetFoundationSpriteBlock (ti->tile);
2736 SpriteID image = GetCustomStationFoundationRelocation (statspec, st, ti->tile, tile_layout, edge_info);
2737 if (image == 0) return false;
2739 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
2740 /* Station provides extended foundations. */
2741 static const uint8 foundation_parts[] = {
2742 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2743 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2744 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2745 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2748 AddSortableSpriteToDraw (ti->vd, image + foundation_parts[ti->tileh],
2749 PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2750 } else {
2751 /* Draw simple foundations, built up from 8 possible foundation sprites. */
2753 /* Each set bit represents one of the eight composite sprites to be drawn.
2754 * 'Invalid' entries will not drawn but are included for completeness. */
2755 static const uint8 composite_foundation_parts[] = {
2756 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2757 0x00, 0xD1, 0xE4, 0xE0,
2758 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2759 0xCA, 0xC9, 0xC4, 0xC0,
2760 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2761 0xD2, 0x91, 0xE4, 0xA0,
2762 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2763 0x4A, 0x09, 0x44
2766 uint8 parts = composite_foundation_parts[ti->tileh];
2768 /* If foundations continue beyond the tile's upper sides then
2769 * mask out the last two pieces. */
2770 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
2771 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
2773 if (parts == 0) {
2774 /* We always have to draw at least one sprite to make
2775 * sure there is a boundingbox and a sprite with the
2776 * correct offset for the childsprites. So, draw the
2777 * (completely empty) sprite of the default foundations. */
2778 return false;
2781 StartSpriteCombine (ti->vd);
2782 for (int i = 0; i < 8; i++) {
2783 if (HasBit(parts, i)) {
2784 AddSortableSpriteToDraw (ti->vd, image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2787 EndSpriteCombine (ti->vd);
2790 OffsetGroundSprite (ti->vd, 31, 1);
2791 ti->z += ApplyPixelFoundationToSlope (FOUNDATION_LEVELED, &ti->tileh);
2792 return true;
2795 static void DrawTile_RailStation (TileInfo *ti)
2797 const RailtypeInfo *rti = GetRailTypeInfo (GetRailType (ti->tile));
2799 const NewGRFSpriteLayout *layout = NULL;
2800 const DrawTileSprites *t = NULL;
2801 BaseStation *st = NULL;
2802 const StationSpec *statspec = NULL;
2803 uint tile_layout = 0;
2805 uint spec_index = GetCustomStationSpecIndex (ti->tile);
2806 if (spec_index != 0) {
2807 /* look for customization */
2808 st = BaseStation::GetByTile (ti->tile);
2809 statspec = st->speclist[spec_index].spec;
2811 if (statspec != NULL) {
2812 tile_layout = GetStationGfx (ti->tile);
2814 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
2815 uint16 callback = GetStationCallback (CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
2816 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis (ti->tile);
2819 /* Ensure the chosen tile layout is valid for this custom station */
2820 if (statspec->renderdata != NULL) {
2821 layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
2822 if (!layout->NeedsPreprocessing()) {
2823 t = layout;
2824 layout = NULL;
2830 if (layout == NULL && (t == NULL || t->seq == NULL)) {
2831 StationGfx gfx = GetStationGfx (ti->tile);
2832 bool waypoint = (GetStationType (ti->tile) == STATION_WAYPOINT);
2833 t = (waypoint ? _station_display_datas_waypoint : _station_display_datas_rail) + gfx;
2836 if (ti->tileh != SLOPE_FLAT) {
2837 if (statspec == NULL || !HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)
2838 || !DrawRailStationFoundation (ti, statspec, st, tile_layout)) {
2839 DrawFoundation(ti, FOUNDATION_LEVELED);
2843 int32 total_offset = rti->GetRailtypeSpriteOffset();
2844 uint32 relocation = 0;
2845 uint32 ground_relocation = 0;
2847 PalSpriteID ground;
2848 const DrawTileSeqStruct *seq;
2849 if (layout != NULL) {
2850 /* Sprite layout which needs preprocessing */
2851 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
2852 uint32 var10_values = layout->PrepareLayout (total_offset, rti->fallback_railtype, 0, 0, separate_ground);
2853 uint8 var10;
2854 FOR_EACH_SET_BIT(var10, var10_values) {
2855 uint32 var10_relocation = GetCustomStationRelocation (statspec, st, ti->tile, var10);
2856 layout->ProcessRegisters (var10, var10_relocation, separate_ground);
2858 seq = layout->GetLayout (&ground);
2859 total_offset = 0;
2860 } else {
2861 ground = t->ground;
2862 seq = t->seq;
2863 if (statspec != NULL) {
2864 /* Simple sprite layout */
2865 ground_relocation = relocation = GetCustomStationRelocation (statspec, st, ti->tile, 0);
2866 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
2867 ground_relocation = GetCustomStationRelocation (statspec, st, ti->tile, 1);
2869 ground_relocation += rti->fallback_railtype;
2873 Owner owner = GetTileOwner (ti->tile);
2874 PaletteID palette = COMPANY_SPRITE_COLOUR(owner);
2876 bool reserved = _game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation (ti->tile);
2877 SpriteID image = ground.sprite;
2878 PaletteID pal = ground.pal;
2879 RailTrackOffset overlay_offset;
2880 if (rti->UsesOverlay() && SplitGroundSpriteForOverlay (ti, &image, &overlay_offset)) {
2881 SpriteID ground = GetCustomRailSprite (rti, ti->tile, RTSG_GROUND);
2882 DrawGroundSprite (ti, image, PAL_NONE);
2883 DrawGroundSprite (ti, ground + overlay_offset, PAL_NONE);
2885 if (reserved) {
2886 image = GetCustomRailSprite (rti, ti->tile, RTSG_OVERLAY) + overlay_offset;
2888 } else {
2889 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
2890 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
2891 DrawGroundSprite (ti, image, GroundSpritePaletteTransform (image, pal, palette));
2893 if (reserved) {
2894 image = rti->base_sprites.single[GetRailStationTrack(ti->tile)];
2898 /* PBS debugging, draw reserved tracks darker */
2899 if (reserved) {
2900 DrawGroundSprite (ti, image, PALETTE_CRASH);
2903 if (HasRailCatenaryDrawn (rti)) {
2904 DrawRailAxisCatenary (ti, rti, GetRailStationAxis (ti->tile),
2905 CanStationTileHavePylons (ti->tile),
2906 CanStationTileHaveWires (ti->tile));
2909 if (IsRailWaypoint(ti->tile)) {
2910 /* Don't offset the waypoint graphics; they're always the same. */
2911 total_offset = 0;
2914 DrawRailTileSeq (ti, seq, TO_BUILDINGS, total_offset, relocation, palette);
2917 static void DrawTile_RoadStop (TileInfo *ti)
2919 if (ti->tileh != SLOPE_FLAT) {
2920 DrawFoundation (ti, FOUNDATION_LEVELED);
2923 StationGfx gfx = GetStationGfx(ti->tile);
2924 bool bus = (GetStationType (ti->tile) == STATION_BUS);
2925 const DrawTileSprites *t = (bus ? _station_display_datas_bus : _station_display_datas_truck) + gfx;
2927 Owner owner = GetTileOwner(ti->tile);
2928 PaletteID palette = COMPANY_SPRITE_COLOUR(owner);
2930 SpriteID image = t->ground.sprite;
2931 PaletteID pal = t->ground.pal;
2932 DrawGroundSprite (ti, image, GroundSpritePaletteTransform (image, pal, palette));
2934 RoadTypes roadtypes = GetRoadTypes (ti->tile);
2935 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
2936 Axis axis = GetRoadStopAxis(ti->tile); // tram stops are always drive-through
2937 DrawGroundSprite (ti, (HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
2938 DrawRoadCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
2941 DrawOrigTileSeq (ti, t->seq, TO_BUILDINGS, palette);
2944 static void DrawTile_OilRig (TileInfo *ti)
2946 if (IsTileOnWater (ti->tile)) {
2947 DrawWaterClassGround (ti);
2948 } else {
2949 DrawGroundSprite (ti, SPR_FLAT_WATER_TILE, PAL_NONE);
2953 static void DrawTile_Dock (TileInfo *ti)
2955 StationGfx gfx = IsBuoy (ti->tile) ? (int)GFX_DOCK_BUOY : GetStationGfx (ti->tile);
2957 int32 total_offset = 0;
2958 if (gfx < DIAGDIR_END) {
2959 TileIndex water_tile = GetOtherDockTile (ti->tile);
2960 WaterClass wc = GetWaterClass (water_tile);
2961 if (wc == WATER_CLASS_SEA) {
2962 DrawShoreTile (ti);
2963 } else {
2964 DrawClearLandTile (ti, 3);
2966 } else if (gfx < GFX_DOCK_BUOY) {
2967 DrawWaterClassGround (ti);
2968 } else {
2969 DrawWaterClassGround(ti);
2970 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
2971 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
2974 Owner owner = GetTileOwner(ti->tile);
2976 PaletteID palette;
2977 if (Company::IsValidID(owner)) {
2978 palette = COMPANY_SPRITE_COLOUR(owner);
2979 } else {
2980 palette = PALETTE_TO_GREY;
2983 DrawRailTileSeq (ti, _station_display_datas_dock[gfx], TO_BUILDINGS,
2984 total_offset, 0, palette);
2987 static void DrawTile_Station (TileInfo *ti)
2989 switch (GetStationType (ti->tile)) {
2990 case STATION_RAIL:
2991 case STATION_WAYPOINT:
2992 DrawTile_RailStation (ti);
2993 break;
2995 case STATION_AIRPORT:
2996 DrawTile_Airport (ti);
2997 /* Airports cannot have bridges over them. */
2998 return;
3000 case STATION_TRUCK:
3001 case STATION_BUS:
3002 DrawTile_RoadStop (ti);
3003 break;
3005 case STATION_OILRIG:
3006 DrawTile_OilRig (ti);
3007 break;
3009 default:
3010 DrawTile_Dock (ti);
3011 break;
3014 DrawBridgeMiddle (ti);
3017 void RailStationPickerDrawSprite (BlitArea *dpi, int x, int y, bool waypoint, RailType railtype, int image)
3019 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3020 const DrawTileSprites *t = (waypoint ? _station_display_datas_waypoint : _station_display_datas_rail) + image;
3021 const RailtypeInfo *rti = GetRailTypeInfo (railtype);
3022 int32 total_offset = rti->GetRailtypeSpriteOffset();
3024 SpriteID ground_spr;
3025 PaletteID ground_pal;
3026 if (rti->UsesOverlay()) {
3027 DrawSprite (dpi, SPR_FLAT_GRASS_TILE, PAL_NONE, x, y);
3028 ground_spr = GetCustomRailSprite (rti, INVALID_TILE, RTSG_GROUND);
3029 bool odd = (image % 2) != 0;
3030 assert (t->ground.sprite == (odd ? SPR_RAIL_TRACK_Y : SPR_RAIL_TRACK_X));
3031 ground_spr += odd ? RTO_Y : RTO_X;
3032 ground_pal = PAL_NONE;
3033 } else {
3034 SpriteID img = t->ground.sprite;
3035 ground_spr = img + total_offset;
3036 ground_pal = HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE;
3038 DrawSprite (dpi, ground_spr, ground_pal, x, y);
3040 /* Default waypoint has no railtype specific sprites */
3041 DrawRailTileSeqInGUI (dpi, x, y, t->seq, waypoint ? 0 : total_offset, 0, pal);
3044 void RoadStationPickerDrawSprite (BlitArea *dpi, int x, int y, bool bus, bool tram, int image)
3046 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3047 const DrawTileSprites *t = (bus ? _station_display_datas_bus : _station_display_datas_truck) + image;
3049 SpriteID img = t->ground.sprite;
3050 DrawSprite (dpi, img, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3052 if (tram) {
3053 DrawSprite (dpi, SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
3056 DrawOrigTileSeqInGUI (dpi, x, y, t->seq, pal);
3059 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
3061 return GetTileMaxPixelZ(tile);
3064 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
3066 return FlatteningFoundation(tileh);
3069 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3071 td->owner[0] = GetTileOwner(tile);
3072 if (IsDriveThroughStopTile(tile)) {
3073 Owner road_owner = INVALID_OWNER;
3074 Owner tram_owner = INVALID_OWNER;
3075 RoadTypes rts = GetRoadTypes(tile);
3076 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
3077 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
3079 /* Is there a mix of owners? */
3080 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3081 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3082 uint i = 1;
3083 if (road_owner != INVALID_OWNER) {
3084 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3085 td->owner[i] = road_owner;
3086 i++;
3088 if (tram_owner != INVALID_OWNER) {
3089 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3090 td->owner[i] = tram_owner;
3094 td->build_date = BaseStation::GetByTile(tile)->build_date;
3096 if (HasStationTileRail(tile)) {
3097 const StationSpec *spec = GetStationSpec(tile);
3099 if (spec != NULL) {
3100 td->station_class = StationClass::Get(spec->cls_id)->name;
3101 td->station_name = spec->name;
3103 if (spec->grf_prop.grffile != NULL) {
3104 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3105 td->grf = gc->GetName();
3109 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3110 td->rail[0].type = rti->strings.name;
3111 td->rail[0].speed = rti->max_speed;
3114 if (IsAirport(tile)) {
3115 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3116 td->airport_class = AirportClass::Get(as->cls_id)->name;
3117 td->airport_name = as->name;
3119 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3120 td->airport_tile_name = ats->name;
3122 if (as->grf_prop.grffile != NULL) {
3123 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3124 td->grf = gc->GetName();
3125 } else if (ats->grf_prop.grffile != NULL) {
3126 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3127 td->grf = gc->GetName();
3131 StringID str;
3132 switch (GetStationType(tile)) {
3133 default: NOT_REACHED();
3134 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3135 case STATION_AIRPORT:
3136 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3137 break;
3138 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3139 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3140 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
3141 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3142 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3143 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3145 td->str = str;
3149 static TrackStatus GetTileRailwayStatus_Station(TileIndex tile, DiagDirection side)
3151 if (!HasStationRail(tile) || IsStationTileBlocked(tile)) return 0;
3153 return CombineTrackStatus(TrackBitsToTrackdirBits(GetRailStationTrackBits(tile)), TRACKDIR_BIT_NONE);
3156 static TrackStatus GetTileRoadStatus_Station(TileIndex tile, uint sub_mode, DiagDirection side)
3158 if (!IsRoadStop(tile) || (GetRoadTypes(tile) & sub_mode) == 0) return 0;
3160 TrackBits trackbits;
3162 if (IsStandardRoadStopTile(tile)) {
3163 DiagDirection dir = GetRoadStopDir(tile);
3165 if (side != INVALID_DIAGDIR && dir != side) return 0;
3167 trackbits = DiagDirToDiagTrackBits(dir);
3168 } else {
3169 Axis axis = GetRoadStopAxis(tile);
3171 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) return 0;
3173 trackbits = AxisToTrackBits(axis);
3176 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3179 static TrackdirBits GetTileWaterwayStatus_Station(TileIndex tile, DiagDirection side)
3181 if (!IsBuoy(tile) && !(IsDock(tile) && IsDockBuoy(tile))) return TRACKDIR_BIT_NONE;
3183 /* buoy is coded as a station, it is always on open water */
3184 TrackBits trackbits = TRACK_BIT_ALL;
3185 /* remove tracks that connect NE map edge */
3186 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3187 /* remove tracks that connect NW map edge */
3188 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3190 return TrackBitsToTrackdirBits(trackbits);
3194 static void TileLoop_Station(TileIndex tile)
3196 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3197 * hardcoded.....not good */
3198 switch (GetStationType(tile)) {
3199 case STATION_AIRPORT:
3200 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3201 break;
3203 case STATION_DOCK:
3204 if (!IsTileFlat(tile)) break; // only handle water part
3205 /* FALL THROUGH */
3206 case STATION_OILRIG: //(station part)
3207 case STATION_BUOY:
3208 TileLoop_Water(tile);
3209 break;
3211 default: break;
3216 static void AnimateTile_Station(TileIndex tile)
3218 if (HasStationRail(tile)) {
3219 AnimateStationTile(tile);
3220 return;
3223 if (IsAirport(tile)) {
3224 AnimateAirportTile(tile);
3229 static bool ClickTile_Station(TileIndex tile)
3231 const BaseStation *bst = BaseStation::GetByTile(tile);
3233 if (bst->IsWaypoint()) {
3234 ShowWaypointWindow(Waypoint::From(bst));
3235 } else if (IsHangar(tile)) {
3236 const Station *st = Station::From(bst);
3237 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3238 } else {
3239 ShowStationViewWindow(bst->index);
3241 return true;
3245 * Run the watched cargo callback for all houses in the catchment area.
3246 * @param st Station.
3248 void TriggerWatchedCargoCallbacks(Station *st)
3250 /* Collect cargoes accepted since the last big tick. */
3251 uint cargoes = 0;
3252 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3253 if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3256 /* Anything to do? */
3257 if (cargoes == 0) return;
3259 /* Loop over all houses in the catchment. */
3260 TileArea ta = st->GetCatchmentArea();
3261 TILE_AREA_LOOP(tile, ta) {
3262 if (IsHouseTile(tile)) {
3263 WatchedCargoCallback(tile, cargoes);
3269 * This function is called for each station once every 250 ticks.
3270 * Not all stations will get the tick at the same time.
3271 * @param st the station receiving the tick.
3272 * @return true if the station is still valid (wasn't deleted)
3274 static bool StationHandleBigTick(BaseStation *st)
3276 if (!st->IsInUse()) {
3277 if (++st->delete_ctr >= 8) delete st;
3278 return false;
3281 if (!st->IsWaypoint()) {
3282 TriggerWatchedCargoCallbacks(Station::From(st));
3284 for (CargoID i = 0; i < NUM_CARGO; i++) {
3285 ClrBit(Station::From(st)->goods[i].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3288 UpdateStationAcceptance(Station::From(st), true);
3291 return true;
3294 static inline void byte_inc_sat(byte *p)
3296 byte b = *p + 1;
3297 if (b != 0) *p = b;
3301 * Truncate the cargo by a specific amount.
3302 * @param cs The type of cargo to perform the truncation for.
3303 * @param ge The goods entry, of the station, to truncate.
3304 * @param amount The amount to truncate the cargo by.
3306 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3308 /* If truncating also punish the source stations' ratings to
3309 * decrease the flow of incoming cargo. */
3311 StationCargoAmountMap waiting_per_source;
3312 ge->cargo.Truncate(amount, &waiting_per_source);
3313 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3314 Station *source_station = Station::GetIfValid(i->first);
3315 if (source_station == NULL) continue;
3317 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3318 source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
3322 static void UpdateStationRating(Station *st)
3324 bool waiting_changed = false;
3326 byte_inc_sat(&st->time_since_load);
3327 byte_inc_sat(&st->time_since_unload);
3329 const CargoSpec *cs;
3330 FOR_ALL_CARGOSPECS(cs) {
3331 GoodsEntry *ge = &st->goods[cs->Index()];
3332 /* Slowly increase the rating back to his original level in the case we
3333 * didn't deliver cargo yet to this station. This happens when a bribe
3334 * failed while you didn't moved that cargo yet to a station. */
3335 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3336 ge->rating++;
3339 /* Only change the rating if we are moving this cargo */
3340 if (ge->HasRating()) {
3341 byte_inc_sat(&ge->time_since_pickup);
3342 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3343 ClrBit(ge->status, GoodsEntry::GES_RATING);
3344 ge->last_speed = 0;
3345 TruncateCargo(cs, ge);
3346 waiting_changed = true;
3347 continue;
3350 bool skip = false;
3351 int rating = 0;
3352 uint waiting = ge->cargo.AvailableCount();
3354 /* num_dests is at least 1 if there is any cargo as
3355 * INVALID_STATION is also a destination.
3357 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3359 /* Average amount of cargo per next hop, but prefer solitary stations
3360 * with only one or two next hops. They are allowed to have more
3361 * cargo waiting per next hop.
3362 * With manual cargo distribution waiting_avg = waiting / 2 as then
3363 * INVALID_STATION is the only destination.
3365 uint waiting_avg = waiting / (num_dests + 1);
3367 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3368 /* Perform custom station rating. If it succeeds the speed, days in transit and
3369 * waiting cargo ratings must not be executed. */
3371 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3372 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3374 uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
3375 /* Convert to the 'old' vehicle types */
3376 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3377 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3378 if (callback != CALLBACK_FAILED) {
3379 skip = true;
3380 rating = GB(callback, 0, 14);
3382 /* Simulate a 15 bit signed value */
3383 if (HasBit(callback, 14)) rating -= 0x4000;
3387 if (!skip) {
3388 int b = ge->last_speed - 85;
3389 if (b >= 0) rating += b >> 2;
3391 byte waittime = ge->time_since_pickup;
3392 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3393 (waittime > 21) ||
3394 (rating += 25, waittime > 12) ||
3395 (rating += 25, waittime > 6) ||
3396 (rating += 45, waittime > 3) ||
3397 (rating += 35, true);
3399 (rating -= 90, ge->max_waiting_cargo > 1500) ||
3400 (rating += 55, ge->max_waiting_cargo > 1000) ||
3401 (rating += 35, ge->max_waiting_cargo > 600) ||
3402 (rating += 10, ge->max_waiting_cargo > 300) ||
3403 (rating += 20, ge->max_waiting_cargo > 100) ||
3404 (rating += 10, true);
3407 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3409 byte age = ge->last_age;
3410 (age >= 3) ||
3411 (rating += 10, age >= 2) ||
3412 (rating += 10, age >= 1) ||
3413 (rating += 13, true);
3416 int or_ = ge->rating; // old rating
3418 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3419 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
3421 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3422 * remove some random amount of goods from the station */
3423 if (rating <= 64 && waiting_avg >= 100) {
3424 int dec = Random() & 0x1F;
3425 if (waiting_avg < 200) dec &= 7;
3426 waiting -= (dec + 1) * num_dests;
3427 waiting_changed = true;
3430 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3431 if (rating <= 127 && waiting != 0) {
3432 uint32 r = Random();
3433 if (rating <= (int)GB(r, 0, 7)) {
3434 /* Need to have int, otherwise it will just overflow etc. */
3435 waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3436 waiting_changed = true;
3440 /* At some point we really must cap the cargo. Previously this
3441 * was a strict 4095, but now we'll have a less strict, but
3442 * increasingly aggressive truncation of the amount of cargo. */
3443 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3444 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3445 static const uint MAX_WAITING_CARGO = 1 << 15;
3447 if (waiting > WAITING_CARGO_THRESHOLD) {
3448 uint difference = waiting - WAITING_CARGO_THRESHOLD;
3449 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3451 waiting = min(waiting, MAX_WAITING_CARGO);
3452 waiting_changed = true;
3455 /* We can't truncate cargo that's already reserved for loading.
3456 * Thus StoredCount() here. */
3457 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3458 /* Feed back the exact own waiting cargo at this station for the
3459 * next rating calculation. */
3460 ge->max_waiting_cargo = 0;
3462 TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3463 } else {
3464 /* If the average number per next hop is low, be more forgiving. */
3465 ge->max_waiting_cargo = waiting_avg;
3471 StationID index = st->index;
3472 if (waiting_changed) {
3473 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3474 } else {
3475 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3480 * Reroute cargo of type c at station st or in any vehicles unloading there.
3481 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3482 * @param st Station to be rerouted at.
3483 * @param c Type of cargo.
3484 * @param avoid Original next hop of cargo, avoid this.
3486 void RerouteCargo (Station *st, CargoID c, StationID avoid)
3488 GoodsEntry &ge = st->goods[c];
3490 /* Reroute cargo in station. */
3491 ge.cargo.Reroute (avoid, st->index, &ge);
3493 /* Reroute cargo staged to be transfered. */
3494 for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
3495 for (Vehicle *v = *it; v != NULL; v = v->Next()) {
3496 if (v->cargo_type != c) continue;
3497 v->cargo.Reroute (avoid, st->index, &ge);
3503 * Check if an order list contains an order for both of the given stations.
3504 * @param l The order list to check.
3505 * @param st1 The first station to look for.
3506 * @param st2 The second station to look for.
3507 * @return Whether the order list has an order for both of the stations.
3509 static bool CheckOrderListLink (const OrderList *l, StationID st1,
3510 StationID st2)
3512 bool found1 = false;
3513 bool found2 = false;
3514 for (const Order *order = l->GetFirstOrder(); order != NULL; order = order->next) {
3515 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
3516 StationID dest = order->GetDestination();
3517 if (dest == st1) {
3518 found1 = true;
3519 if (found2) return true;
3520 } else if (dest == st2) {
3521 found2 = true;
3522 if (found1) return true;
3525 return false;
3529 * Check if a link is stale.
3530 * @param from Source station.
3531 * @param to Destination station.
3532 * @param edge Link to check.
3533 * @return Whether the link has been updated.
3535 static bool CheckStaleLink (StationID from, StationID to,
3536 const LinkGraph::Edge *edge)
3538 /* Have all vehicles refresh their next hops before deciding to
3539 * remove the node. */
3540 OrderList *l;
3541 SmallVector<Vehicle *, 32> vehicles;
3542 FOR_ALL_ORDER_LISTS(l) {
3543 if (!CheckOrderListLink (l, from, to)) continue;
3544 *(vehicles.Append()) = l->GetFirstSharedVehicle();
3547 Vehicle **iter = vehicles.Begin();
3548 while (iter != vehicles.End()) {
3549 Vehicle *v = *iter;
3551 LinkRefresher::Run (v, false); // Don't allow merging. Otherwise lg might get deleted.
3552 if (edge->LastUpdate() == _date) return true;
3554 Vehicle *next_shared = v->NextShared();
3555 if (next_shared) {
3556 *iter = next_shared;
3557 ++iter;
3558 } else {
3559 vehicles.Erase (iter);
3562 if (iter == vehicles.End()) iter = vehicles.Begin();
3565 return false;
3569 * Check all next hops of cargo packets in this station for existance of a
3570 * a valid link they may use to travel on. Reroute any cargo not having a valid
3571 * link and remove timed out links found like this from the linkgraph. We're
3572 * not all links here as that is expensive and useless. A link no one is using
3573 * doesn't hurt either.
3574 * @param from Station to check.
3576 static void DeleteStaleLinks (Station *from)
3578 for (CargoID c = 0; c < NUM_CARGO; ++c) {
3579 const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
3580 GoodsEntry &ge = from->goods[c];
3581 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
3582 if (lg == NULL) continue;
3583 LinkGraph::NodeRef node = (*lg)[ge.node];
3584 for (LinkGraph::EdgeIterator it(node.Begin()); it != node.End();) {
3585 LinkGraph::Edge *edge = &*it;
3586 Station *to = Station::Get((*lg)[it.get_id()]->Station());
3587 assert(to->goods[c].node == it.get_id());
3588 ++it; // Do that before removing the edge. Anything else may crash.
3589 assert(_date >= edge->LastUpdate());
3590 uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
3591 if ((uint)(_date - edge->LastUpdate()) > timeout) {
3592 if (!auto_distributed || !CheckStaleLink (from->index, to->index, edge)) {
3593 /* If it's still considered dead remove it. */
3594 lg->RemoveEdge (ge.node, to->goods[c].node);
3595 ge.flows.DeleteFlows(to->index);
3596 RerouteCargo (from, c, to->index);
3598 } else if (edge->LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge->LastUnrestrictedUpdate()) > timeout) {
3599 edge->Restrict();
3600 ge.flows.RestrictFlows(to->index);
3601 RerouteCargo (from, c, to->index);
3602 } else if (edge->LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge->LastRestrictedUpdate()) > timeout) {
3603 edge->Release();
3606 assert(_date >= lg->LastCompression());
3607 if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
3608 lg->Compress();
3614 * Increase capacity for a link stat given by station cargo and next hop.
3615 * @param st Station to get the link stats from.
3616 * @param cargo Cargo to increase stat for.
3617 * @param next_station_id Station the consist will be travelling to next.
3618 * @param capacity Capacity to add to link stat.
3619 * @param usage Usage to add to link stat.
3620 * @param mode Update mode to be applied.
3622 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, EdgeUpdateMode mode)
3624 GoodsEntry &ge1 = st->goods[cargo];
3625 Station *st2 = Station::Get(next_station_id);
3626 GoodsEntry &ge2 = st2->goods[cargo];
3627 LinkGraph *lg = NULL;
3628 if (ge1.link_graph == INVALID_LINK_GRAPH) {
3629 if (ge2.link_graph == INVALID_LINK_GRAPH) {
3630 if (LinkGraph::CanAllocateItem()) {
3631 lg = new LinkGraph(cargo);
3632 LinkGraphSchedule::instance.Queue(lg);
3633 ge2.link_graph = lg->index;
3634 ge2.node = lg->AddNode(st2);
3635 } else {
3636 DEBUG(misc, 0, "Can't allocate link graph");
3638 } else {
3639 lg = LinkGraph::Get(ge2.link_graph);
3641 if (lg) {
3642 ge1.link_graph = lg->index;
3643 ge1.node = lg->AddNode(st);
3645 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
3646 lg = LinkGraph::Get(ge1.link_graph);
3647 ge2.link_graph = lg->index;
3648 ge2.node = lg->AddNode(st2);
3649 } else {
3650 lg = LinkGraph::Get(ge1.link_graph);
3651 if (ge1.link_graph != ge2.link_graph) {
3652 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
3653 if (lg->Size() < lg2->Size()) {
3654 LinkGraphSchedule::instance.Unqueue(lg);
3655 lg2->Merge(lg); // Updates GoodsEntries of lg
3656 lg = lg2;
3657 } else {
3658 LinkGraphSchedule::instance.Unqueue(lg2);
3659 lg->Merge(lg2); // Updates GoodsEntries of lg2
3663 if (lg != NULL) {
3664 lg->UpdateEdge (ge1.node, ge2.node, capacity, usage, mode);
3669 * Increase capacity for all link stats associated with vehicles in the given consist.
3670 * @param st Station to get the link stats from.
3671 * @param front First vehicle in the consist.
3672 * @param next_station_id Station the consist will be travelling to next.
3674 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
3676 for (const Vehicle *v = front; v != NULL; v = v->Next()) {
3677 if (v->refit_cap > 0) {
3678 /* The cargo count can indeed be higher than the refit_cap if
3679 * wagons have been auto-replaced and subsequently auto-
3680 * refitted to a higher capacity. The cargo gets redistributed
3681 * among the wagons in that case.
3682 * As usage is not such an important figure anyway we just
3683 * ignore the additional cargo then.*/
3684 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
3685 min(v->refit_cap, v->cargo.StoredCount()), EUM_INCREASE);
3690 /* called for every station each tick */
3691 static void StationHandleSmallTick(BaseStation *st)
3693 if (st->IsWaypoint() || !st->IsInUse()) return;
3695 byte b = st->delete_ctr + 1;
3696 if (b >= STATION_RATING_TICKS) b = 0;
3697 st->delete_ctr = b;
3699 if (b == 0) UpdateStationRating(Station::From(st));
3702 void OnTick_Station()
3704 if (_game_mode == GM_EDITOR) return;
3706 BaseStation *st;
3707 FOR_ALL_BASE_STATIONS(st) {
3708 StationHandleSmallTick(st);
3710 /* Clean up the link graph about once a week. */
3711 if (!st->IsWaypoint() && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
3712 DeleteStaleLinks(Station::From(st));
3715 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3716 * Station index is included so that triggers are not all done
3717 * at the same time. */
3718 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
3719 /* Stop processing this station if it was deleted */
3720 if (!StationHandleBigTick(st)) continue;
3721 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
3722 if (!st->IsWaypoint()) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
3727 /** Monthly loop for stations. */
3728 void StationMonthlyLoop()
3730 Station *st;
3732 FOR_ALL_STATIONS(st) {
3733 for (CargoID i = 0; i < NUM_CARGO; i++) {
3734 GoodsEntry *ge = &st->goods[i];
3735 SB(ge->status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->status, GoodsEntry::GES_CURRENT_MONTH, 1));
3736 ClrBit(ge->status, GoodsEntry::GES_CURRENT_MONTH);
3742 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
3744 Station *st;
3746 FOR_ALL_STATIONS(st) {
3747 if (st->owner == owner &&
3748 DistanceManhattan(tile, st->xy) <= radius) {
3749 for (CargoID i = 0; i < NUM_CARGO; i++) {
3750 GoodsEntry *ge = &st->goods[i];
3752 if (ge->status != 0) {
3753 ge->rating = Clamp(ge->rating + amount, 0, 255);
3760 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
3762 /* We can't allocate a CargoPacket? Then don't do anything
3763 * at all; i.e. just discard the incoming cargo. */
3764 if (!CargoPacket::CanAllocateItem()) return 0;
3766 GoodsEntry &ge = st->goods[type];
3767 amount += ge.amount_fract;
3768 ge.amount_fract = GB(amount, 0, 8);
3770 amount >>= 8;
3771 /* No new "real" cargo item yet. */
3772 if (amount == 0) return 0;
3774 StationID next = ge.GetVia(st->index);
3775 ge.cargo.Append (new CargoPacket (st, amount, source_type, source_id), next);
3776 LinkGraph *lg = NULL;
3777 if (ge.link_graph == INVALID_LINK_GRAPH) {
3778 if (LinkGraph::CanAllocateItem()) {
3779 lg = new LinkGraph(type);
3780 LinkGraphSchedule::instance.Queue(lg);
3781 ge.link_graph = lg->index;
3782 ge.node = lg->AddNode(st);
3783 } else {
3784 DEBUG(misc, 0, "Can't allocate link graph");
3786 } else {
3787 lg = LinkGraph::Get(ge.link_graph);
3789 if (lg != NULL) (*lg)[ge.node]->UpdateSupply(amount);
3791 if (!ge.HasRating()) {
3792 InvalidateWindowData(WC_STATION_LIST, st->index);
3793 SetBit(ge.status, GoodsEntry::GES_RATING);
3796 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
3797 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
3798 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
3800 SetWindowDirty(WC_STATION_VIEW, st->index);
3801 st->MarkTilesDirty(true);
3802 return amount;
3805 static bool IsUniqueStationName(const char *name)
3807 const Station *st;
3809 FOR_ALL_STATIONS(st) {
3810 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
3813 return true;
3817 * Rename a station
3818 * @param tile unused
3819 * @param flags operation to perform
3820 * @param p1 station ID that is to be renamed
3821 * @param p2 unused
3822 * @param text the new name or an empty string when resetting to the default
3823 * @return the cost of this operation or an error
3825 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3827 Station *st = Station::GetIfValid(p1);
3828 if (st == NULL) return CMD_ERROR;
3830 CommandCost ret = CheckOwnership(st->owner);
3831 if (ret.Failed()) return ret;
3833 bool reset = StrEmpty(text);
3835 if (!reset) {
3836 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
3837 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
3840 if (flags & DC_EXEC) {
3841 free(st->name);
3842 st->name = reset ? NULL : xstrdup(text);
3844 st->UpdateVirtCoord();
3845 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
3848 return CommandCost();
3852 * Find all stations around a rectangular producer (industry, house, headquarter, ...)
3854 * @param location The location/area of the producer
3855 * @param stations The list to store the stations in
3857 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
3859 /* area to search = producer plus station catchment radius */
3860 uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
3862 uint x = TileX(location.tile);
3863 uint y = TileY(location.tile);
3865 uint min_x = (x > max_rad) ? x - max_rad : 0;
3866 uint max_x = x + location.w + max_rad;
3867 uint min_y = (y > max_rad) ? y - max_rad : 0;
3868 uint max_y = y + location.h + max_rad;
3870 if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
3871 if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
3872 if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
3873 if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
3875 for (uint cy = min_y; cy < max_y; cy++) {
3876 for (uint cx = min_x; cx < max_x; cx++) {
3877 TileIndex cur_tile = TileXY(cx, cy);
3878 if (!IsStationTile(cur_tile)) continue;
3880 Station *st = Station::GetByTile(cur_tile);
3881 /* st can be NULL in case of waypoints */
3882 if (st == NULL) continue;
3884 if (_settings_game.station.modified_catchment) {
3885 int rad = st->GetCatchmentRadius();
3886 int rad_x = cx - x;
3887 int rad_y = cy - y;
3889 if (rad_x < -rad || rad_x >= rad + location.w) continue;
3890 if (rad_y < -rad || rad_y >= rad + location.h) continue;
3893 /* Insert the station in the set. This will fail if it has
3894 * already been added.
3896 stations->Include(st);
3902 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
3903 * @return pointer to a StationList containing all stations found
3905 const StationList *StationFinder::GetStations()
3907 if (this->tile != INVALID_TILE) {
3908 FindStationsAroundTiles(*this, &this->stations);
3909 this->tile = INVALID_TILE;
3911 return &this->stations;
3914 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
3916 /* Return if nothing to do. Also the rounding below fails for 0. */
3917 if (amount == 0) return 0;
3919 Station *st1 = NULL; // Station with best rating
3920 Station *st2 = NULL; // Second best station
3921 uint best_rating1 = 0; // rating of st1
3922 uint best_rating2 = 0; // rating of st2
3924 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
3925 Station *st = *st_iter;
3927 /* Is the station reserved exclusively for somebody else? */
3928 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
3930 if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
3932 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
3934 if (!st->CanHandleCargo(type)) continue; // passengers on truck stop or freight on bus stop
3936 /* This station can be used, add it to st1/st2 */
3937 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
3938 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
3939 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
3940 st2 = st; best_rating2 = st->goods[type].rating;
3944 /* no stations around at all? */
3945 if (st1 == NULL) return 0;
3947 /* From now we'll calculate with fractal cargo amounts.
3948 * First determine how much cargo we really have. */
3949 amount *= best_rating1 + 1;
3951 if (st2 == NULL) {
3952 /* only one station around */
3953 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
3956 /* several stations around, the best two (highest rating) are in st1 and st2 */
3957 assert(st1 != NULL);
3958 assert(st2 != NULL);
3959 assert(best_rating1 != 0 || best_rating2 != 0);
3961 /* Then determine the amount the worst station gets. We do it this way as the
3962 * best should get a bonus, which in this case is the rounding difference from
3963 * this calculation. In reality that will mean the bonus will be pretty low.
3964 * Nevertheless, the best station should always get the most cargo regardless
3965 * of rounding issues. */
3966 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
3967 assert(worst_cargo <= (amount - worst_cargo));
3969 /* And then send the cargo to the stations! */
3970 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
3971 /* These two UpdateStationWaiting's can't be in the statement as then the order
3972 * of execution would be undefined and that could cause desyncs with callbacks. */
3973 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
3976 void BuildOilRig(TileIndex tile)
3978 if (!Station::CanAllocateItem()) {
3979 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
3980 return;
3983 if (!Dock::CanAllocateItem()) {
3984 DEBUG(misc, 0, "Can't allocate dock for oilrig at 0x%X, reverting to oilrig only", tile);
3985 return;
3988 Station *st = new Station(tile);
3989 st->town = ClosestTownFromTile(tile);
3991 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
3993 assert(IsIndustryTile(tile));
3994 DeleteAnimatedTile(tile);
3995 MakeOilrig(tile, st->index, GetWaterClass(tile));
3997 st->owner = OWNER_NONE;
3998 st->docks = new Dock(tile);
3999 st->dock_area = TileArea(tile, 1, 1);
4000 st->airport.type = AT_OILRIG;
4001 st->airport.Add(tile);
4002 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
4003 st->build_date = _date;
4005 st->rect.Add(tile);
4007 st->UpdateVirtCoord();
4008 UpdateStationAcceptance(st, false);
4009 st->RecomputeIndustriesNear();
4012 void DeleteOilRig(TileIndex tile)
4014 Station *st = Station::GetByTile(tile);
4016 MakeWaterKeepingClass(tile, OWNER_NONE);
4018 delete st->docks;
4019 st->docks = NULL;
4020 st->dock_area.Clear();
4021 st->airport.Clear();
4022 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
4023 st->airport.flags = 0;
4025 st->AfterRemoveTile(tile);
4027 st->UpdateVirtCoord();
4028 st->RecomputeIndustriesNear();
4029 if (!st->IsInUse()) delete st;
4032 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4034 if (IsRoadStopTile(tile)) {
4035 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
4036 /* Update all roadtypes, no matter if they are present */
4037 if (GetRoadOwner(tile, rt) == old_owner) {
4038 if (HasTileRoadType(tile, rt)) {
4039 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4040 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4041 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4043 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4048 if (!IsTileOwner(tile, old_owner)) return;
4050 if (new_owner != INVALID_OWNER) {
4051 /* Update company infrastructure counts. Only do it here
4052 * if the new owner is valid as otherwise the clear
4053 * command will do it for us. No need to dirty windows
4054 * here, we'll redraw the whole screen anyway.*/
4055 Company *old_company = Company::Get(old_owner);
4056 Company *new_company = Company::Get(new_owner);
4058 /* Update counts for underlying infrastructure. */
4059 switch (GetStationType(tile)) {
4060 case STATION_RAIL:
4061 case STATION_WAYPOINT:
4062 if (!IsStationTileBlocked(tile)) {
4063 old_company->infrastructure.rail[GetRailType(tile)]--;
4064 new_company->infrastructure.rail[GetRailType(tile)]++;
4066 break;
4068 case STATION_BUS:
4069 case STATION_TRUCK:
4070 /* Road stops were already handled above. */
4071 break;
4073 case STATION_BUOY:
4074 case STATION_DOCK:
4075 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
4076 old_company->infrastructure.water--;
4077 new_company->infrastructure.water++;
4079 break;
4081 default:
4082 break;
4085 /* Update station tile count. */
4086 if (!IsBuoy(tile) && !IsAirport(tile)) {
4087 old_company->infrastructure.station--;
4088 new_company->infrastructure.station++;
4091 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4092 SetTileOwner(tile, new_owner);
4093 InvalidateWindowClassesData(WC_STATION_LIST, 0);
4094 } else {
4095 if (IsDriveThroughStopTile(tile)) {
4096 /* Remove the drive-through road stop */
4097 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
4098 assert(IsNormalRoadTile(tile));
4099 /* Change owner of tile and all roadtypes */
4100 ChangeTileOwner(tile, old_owner, new_owner);
4101 } else {
4102 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
4103 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4104 * Update owner of buoy if it was not removed (was in orders).
4105 * Do not update when owned by OWNER_WATER (sea and rivers). */
4106 if ((IsWaterTile(tile) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4112 * Check if a drive-through road stop tile can be cleared.
4113 * Road stops built on town-owned roads check the conditions
4114 * that would allow clearing of the original road.
4115 * @param tile road stop tile to check
4116 * @param flags command flags
4117 * @return true if the road can be cleared
4119 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
4121 /* Yeah... water can always remove stops, right? */
4122 if (_current_company == OWNER_WATER) return true;
4124 RoadTypes rts = GetRoadTypes(tile);
4125 if (HasBit(rts, ROADTYPE_TRAM)) {
4126 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
4127 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
4129 if (HasBit(rts, ROADTYPE_ROAD)) {
4130 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
4131 if (road_owner != OWNER_TOWN) {
4132 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
4133 } else {
4134 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
4138 return true;
4142 * Clear a single tile of a station.
4143 * @param tile The tile to clear.
4144 * @param flags The DoCommand flags related to the "command".
4145 * @return The cost, or error of clearing.
4147 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4149 if (flags & DC_AUTO) {
4150 switch (GetStationType(tile)) {
4151 default: break;
4152 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4153 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4154 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4155 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);
4156 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);
4157 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4158 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4159 case STATION_OILRIG:
4160 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4161 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4165 switch (GetStationType(tile)) {
4166 case STATION_RAIL: return RemoveRailStation(tile, flags);
4167 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4168 case STATION_AIRPORT: return RemoveAirport(tile, flags);
4169 case STATION_TRUCK:
4170 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4171 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4173 return RemoveRoadStop(tile, flags);
4174 case STATION_BUS:
4175 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4176 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4178 return RemoveRoadStop(tile, flags);
4179 case STATION_BUOY: return RemoveBuoy(tile, flags);
4180 case STATION_DOCK: return RemoveDock(tile, flags);
4181 default: break;
4184 return CMD_ERROR;
4187 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4189 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4190 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4191 * TTDP does not call it.
4193 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4194 switch (GetStationType(tile)) {
4195 case STATION_WAYPOINT:
4196 case STATION_RAIL: {
4197 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4198 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4199 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4200 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4203 case STATION_AIRPORT:
4204 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4206 case STATION_TRUCK:
4207 case STATION_BUS: {
4208 DiagDirection direction = GetRoadStopDir(tile);
4209 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4210 if (IsDriveThroughStopTile(tile)) {
4211 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4213 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4216 default: break;
4220 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
4224 * Get flow for a station.
4225 * @param st Station to get flow for.
4226 * @return Flow for st.
4228 uint FlowStat::GetShare(StationID st) const
4230 uint32 prev = 0;
4231 for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
4232 if (it->second == st) {
4233 return it->first - prev;
4234 } else {
4235 prev = it->first;
4238 return 0;
4242 * Get a station a package can be routed to, but exclude the given ones.
4243 * @param excluded StationID not to be selected.
4244 * @param excluded2 Another StationID not to be selected.
4245 * @return A station ID from the shares map.
4247 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4249 if (this->unrestricted == 0) return INVALID_STATION;
4250 assert(!this->shares.empty());
4251 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4252 assert(it != this->shares.end() && it->first <= this->unrestricted);
4253 if (it->second != excluded && it->second != excluded2) return it->second;
4255 /* We've hit one of the excluded stations.
4256 * Draw another share, from outside its range. */
4258 uint end = it->first;
4259 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4260 uint interval = end - begin;
4261 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4262 uint new_max = this->unrestricted - interval;
4263 uint rand = RandomRange(new_max);
4264 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4265 this->shares.upper_bound(rand + interval);
4266 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4267 if (it2->second != excluded && it2->second != excluded2) return it2->second;
4269 /* We've hit the second excluded station.
4270 * Same as before, only a bit more complicated. */
4272 uint end2 = it2->first;
4273 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4274 uint interval2 = end2 - begin2;
4275 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4276 new_max -= interval2;
4277 if (begin > begin2) {
4278 Swap(begin, begin2);
4279 Swap(end, end2);
4280 Swap(interval, interval2);
4282 rand = RandomRange(new_max);
4283 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4284 if (rand < begin) {
4285 it3 = this->shares.upper_bound(rand);
4286 } else if (rand < begin2 - interval) {
4287 it3 = this->shares.upper_bound(rand + interval);
4288 } else {
4289 it3 = this->shares.upper_bound(rand + interval + interval2);
4291 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4292 return it3->second;
4296 * Reduce all flows to minimum capacity so that they don't get in the way of
4297 * link usage statistics too much. Keep them around, though, to continue
4298 * routing any remaining cargo.
4300 void FlowStat::Invalidate()
4302 assert(!this->shares.empty());
4303 SharesMap new_shares;
4304 uint i = 0;
4305 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4306 new_shares[++i] = it->second;
4307 if (it->first == this->unrestricted) this->unrestricted = i;
4309 this->shares.swap(new_shares);
4310 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4314 * Change share for specified station. By specifing INT_MIN as parameter you
4315 * can erase a share. Newly added flows will be unrestricted.
4316 * @param st Next Hop to be removed.
4317 * @param flow Share to be added or removed.
4319 void FlowStat::ChangeShare(StationID st, int flow)
4321 /* We assert only before changing as afterwards the shares can actually
4322 * be empty. In that case the whole flow stat must be deleted then. */
4323 assert(!this->shares.empty());
4325 uint removed_shares = 0;
4326 uint added_shares = 0;
4327 uint last_share = 0;
4328 SharesMap new_shares;
4329 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4330 if (it->second == st) {
4331 if (flow < 0) {
4332 uint share = it->first - last_share;
4333 if (flow == INT_MIN || (uint)(-flow) >= share) {
4334 removed_shares += share;
4335 if (it->first <= this->unrestricted) this->unrestricted -= share;
4336 if (flow != INT_MIN) flow += share;
4337 last_share = it->first;
4338 continue; // remove the whole share
4340 removed_shares += (uint)(-flow);
4341 } else {
4342 added_shares += (uint)(flow);
4344 if (it->first <= this->unrestricted) this->unrestricted += flow;
4346 /* If we don't continue above the whole flow has been added or
4347 * removed. */
4348 flow = 0;
4350 new_shares[it->first + added_shares - removed_shares] = it->second;
4351 last_share = it->first;
4353 if (flow > 0) {
4354 new_shares[last_share + (uint)flow] = st;
4355 if (this->unrestricted < last_share) {
4356 this->ReleaseShare(st);
4357 } else {
4358 this->unrestricted += flow;
4361 this->shares.swap(new_shares);
4365 * Restrict a flow by moving it to the end of the map and decreasing the amount
4366 * of unrestricted flow.
4367 * @param st Station of flow to be restricted.
4369 void FlowStat::RestrictShare(StationID st)
4371 assert(!this->shares.empty());
4372 uint flow = 0;
4373 uint last_share = 0;
4374 SharesMap new_shares;
4375 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4376 if (flow == 0) {
4377 if (it->first > this->unrestricted) return; // Not present or already restricted.
4378 if (it->second == st) {
4379 flow = it->first - last_share;
4380 this->unrestricted -= flow;
4381 } else {
4382 new_shares[it->first] = it->second;
4384 } else {
4385 new_shares[it->first - flow] = it->second;
4387 last_share = it->first;
4389 if (flow == 0) return;
4390 new_shares[last_share + flow] = st;
4391 this->shares.swap(new_shares);
4392 assert(!this->shares.empty());
4396 * Release ("unrestrict") a flow by moving it to the begin of the map and
4397 * increasing the amount of unrestricted flow.
4398 * @param st Station of flow to be released.
4400 void FlowStat::ReleaseShare(StationID st)
4402 assert(!this->shares.empty());
4403 uint flow = 0;
4404 uint next_share = 0;
4405 bool found = false;
4406 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4407 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4408 if (found) {
4409 flow = next_share - it->first;
4410 this->unrestricted += flow;
4411 break;
4412 } else {
4413 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4414 if (it->second == st) found = true;
4416 next_share = it->first;
4418 if (flow == 0) return;
4419 SharesMap new_shares;
4420 new_shares[flow] = st;
4421 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4422 if (it->second != st) {
4423 new_shares[flow + it->first] = it->second;
4424 } else {
4425 flow = 0;
4428 this->shares.swap(new_shares);
4429 assert(!this->shares.empty());
4433 * Scale all shares from link graph's runtime to monthly values.
4434 * @param runtime Time the link graph has been running without compression.
4435 * @pre runtime must be greater than 0 as we don't want infinite flow values.
4437 void FlowStat::ScaleToMonthly(uint runtime)
4439 assert(runtime > 0);
4440 SharesMap new_shares;
4441 uint share = 0;
4442 for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
4443 share = max(share + 1, i->first * 30 / runtime);
4444 new_shares[share] = i->second;
4445 if (this->unrestricted == i->first) this->unrestricted = share;
4447 this->shares.swap(new_shares);
4451 * Add some flow from "origin", going via "via".
4452 * @param origin Origin of the flow.
4453 * @param via Next hop.
4454 * @param flow Amount of flow to be added.
4456 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
4458 FlowStatMap::iterator origin_it = this->find(origin);
4459 if (origin_it == this->end()) {
4460 this->insert(std::make_pair(origin, FlowStat(via, flow)));
4461 } else {
4462 origin_it->second.ChangeShare(via, flow);
4463 assert(!origin_it->second.GetShares()->empty());
4468 * Pass on some flow, remembering it as invalid, for later subtraction from
4469 * locally consumed flow. This is necessary because we can't have negative
4470 * flows and we don't want to sort the flows before adding them up.
4471 * @param origin Origin of the flow.
4472 * @param via Next hop.
4473 * @param flow Amount of flow to be passed.
4475 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
4477 FlowStatMap::iterator prev_it = this->find(origin);
4478 if (prev_it == this->end()) {
4479 FlowStat fs(via, flow);
4480 fs.AppendShare(INVALID_STATION, flow);
4481 this->insert(std::make_pair(origin, fs));
4482 } else {
4483 prev_it->second.ChangeShare(via, flow);
4484 prev_it->second.ChangeShare(INVALID_STATION, flow);
4485 assert(!prev_it->second.GetShares()->empty());
4490 * Subtract invalid flows from locally consumed flow.
4491 * @param self ID of own station.
4493 void FlowStatMap::FinalizeLocalConsumption(StationID self)
4495 for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
4496 FlowStat &fs = i->second;
4497 uint local = fs.GetShare(INVALID_STATION);
4498 if (local > INT_MAX) { // make sure it fits in an int
4499 fs.ChangeShare(self, -INT_MAX);
4500 fs.ChangeShare(INVALID_STATION, -INT_MAX);
4501 local -= INT_MAX;
4503 fs.ChangeShare(self, -(int)local);
4504 fs.ChangeShare(INVALID_STATION, -(int)local);
4506 /* If the local share is used up there must be a share for some
4507 * remote station. */
4508 assert(!fs.GetShares()->empty());
4513 * Delete all flows at a station for specific cargo and destination.
4514 * @param via Remote station of flows to be deleted.
4515 * @param erased Station id stack to which to append the source stations
4516 * for which the complete FlowStat, not only a share, has been erased.
4518 void FlowStatMap::DeleteFlows (StationID via, StationIDStack *erased)
4520 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
4521 FlowStat &s_flows = f_it->second;
4522 s_flows.ChangeShare(via, INT_MIN);
4523 if (s_flows.GetShares()->empty()) {
4524 if (erased != NULL) erased->push_back (f_it->first);
4525 this->erase(f_it++);
4526 } else {
4527 ++f_it;
4533 * Restrict all flows at a station for specific cargo and destination.
4534 * @param via Remote station of flows to be restricted.
4536 void FlowStatMap::RestrictFlows(StationID via)
4538 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4539 it->second.RestrictShare(via);
4544 * Release all flows at a station for specific cargo and destination.
4545 * @param via Remote station of flows to be released.
4547 void FlowStatMap::ReleaseFlows(StationID via)
4549 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4550 it->second.ReleaseShare(via);
4555 * Get the sum of all flows from this FlowStatMap.
4556 * @return sum of all flows.
4558 uint FlowStatMap::GetFlow() const
4560 uint ret = 0;
4561 for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4562 ret += (--(i->second.GetShares()->end()))->first;
4564 return ret;
4568 * Get the sum of flows via a specific station from this FlowStatMap.
4569 * @param via Remote station to look for.
4570 * @return all flows for 'via' added up.
4572 uint FlowStatMap::GetFlowVia(StationID via) const
4574 uint ret = 0;
4575 for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4576 ret += i->second.GetShare(via);
4578 return ret;
4582 * Get the sum of flows from a specific station from this FlowStatMap.
4583 * @param from Origin station to look for.
4584 * @return all flows from 'from' added up.
4586 uint FlowStatMap::GetFlowFrom(StationID from) const
4588 FlowStatMap::const_iterator i = this->find(from);
4589 if (i == this->end()) return 0;
4590 return (--(i->second.GetShares()->end()))->first;
4594 * Get the flow from a specific station via a specific other station.
4595 * @param from Origin station to look for.
4596 * @param via Remote station to look for.
4597 * @return flow share originating at 'from' and going to 'via'.
4599 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
4601 FlowStatMap::const_iterator i = this->find(from);
4602 if (i == this->end()) return 0;
4603 return i->second.GetShare(via);
4606 extern const TileTypeProcs _tile_type_station_procs = {
4607 DrawTile_Station, // draw_tile_proc
4608 GetSlopePixelZ_Station, // get_slope_z_proc
4609 ClearTile_Station, // clear_tile_proc
4610 NULL, // add_accepted_cargo_proc
4611 GetTileDesc_Station, // get_tile_desc_proc
4612 GetTileRailwayStatus_Station, // get_tile_railway_status_proc
4613 GetTileRoadStatus_Station, // get_tile_road_status_proc
4614 GetTileWaterwayStatus_Station, // get_tile_waterway_status_proc
4615 ClickTile_Station, // click_tile_proc
4616 AnimateTile_Station, // animate_tile_proc
4617 TileLoop_Station, // tile_loop_proc
4618 ChangeTileOwner_Station, // change_tile_owner_proc
4619 NULL, // add_produced_cargo_proc
4620 GetFoundation_Station, // get_foundation_proc
4621 TerraformTile_Station, // terraform_tile_proc