Rearrange storage of reserved tracks for railway tiles
[openttd/fttd.git] / src / station_cmd.cpp
blob902de6f10a1db4f62a3fe4fe97b1d072fef3c1aa
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"
13 #include "aircraft.h"
14 #include "cmd_helper.h"
15 #include "viewport_func.h"
16 #include "command_func.h"
17 #include "town.h"
18 #include "news_func.h"
19 #include "train.h"
20 #include "ship.h"
21 #include "roadveh.h"
22 #include "industry.h"
23 #include "newgrf_cargo.h"
24 #include "newgrf_debug.h"
25 #include "newgrf_station.h"
26 #include "newgrf_canal.h" /* For the buoy */
27 #include "pathfinder/yapf/yapf.h"
28 #include "road_internal.h" /* For drawing catenary/checking road removal */
29 #include "autoslope.h"
30 #include "water.h"
31 #include "strings_func.h"
32 #include "clear_func.h"
33 #include "date_func.h"
34 #include "vehicle_func.h"
35 #include "string_func.h"
36 #include "animated_tile_func.h"
37 #include "elrail_func.h"
38 #include "station_base.h"
39 #include "roadstop_base.h"
40 #include "newgrf_railtype.h"
41 #include "waypoint_base.h"
42 #include "waypoint_func.h"
43 #include "pbs.h"
44 #include "debug.h"
45 #include "core/random_func.hpp"
46 #include "company_base.h"
47 #include "table/airporttile_ids.h"
48 #include "newgrf_airporttiles.h"
49 #include "order_backup.h"
50 #include "newgrf_house.h"
51 #include "company_gui.h"
52 #include "linkgraph/linkgraph_base.h"
53 #include "linkgraph/refresh.h"
54 #include "widgets/station_widget.h"
55 #include "signal_func.h"
56 #include "map/zoneheight.h"
57 #include "map/road.h"
59 #include "table/strings.h"
61 /**
62 * Check whether the given tile is a hangar.
63 * @param t the tile to of whether it is a hangar.
64 * @pre IsStationTile(t)
65 * @return true if and only if the tile is a hangar.
67 bool IsHangar(TileIndex t)
69 assert(IsStationTile(t));
71 /* If the tile isn't an airport there's no chance it's a hangar. */
72 if (!IsAirport(t)) return false;
74 const Station *st = Station::GetByTile(t);
75 const AirportSpec *as = st->airport.GetSpec();
77 for (uint i = 0; i < as->nof_depots; i++) {
78 if (st->airport.GetHangarTile(i) == t) return true;
81 return false;
84 /**
85 * Function to check whether the given tile matches some criterion.
86 * @param tile the tile to check
87 * @return true if it matches, false otherwise
89 typedef bool (*CMSAMatcher)(TileIndex tile);
91 /**
92 * Counts the numbers of tiles matching a specific type in the area around
93 * @param tile the center tile of the 'count area'
94 * @param cmp the comparator/matcher (@see CMSAMatcher)
95 * @return the number of matching tiles around
97 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
99 int num = 0;
101 for (int dx = -3; dx <= 3; dx++) {
102 for (int dy = -3; dy <= 3; dy++) {
103 TileIndex t = TileAddWrap(tile, dx, dy);
104 if (t != INVALID_TILE && cmp(t)) num++;
108 return num;
112 * Check whether the tile is a mine.
113 * @param tile the tile to investigate.
114 * @return true if and only if the tile is a mine
116 static bool CMSAMine(TileIndex tile)
118 /* No industry */
119 if (!IsIndustryTile(tile)) return false;
121 const Industry *ind = Industry::GetByTile(tile);
123 /* No extractive industry */
124 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
126 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
127 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
128 * Also the production of passengers and mail is ignored. */
129 if (ind->produced_cargo[i] != CT_INVALID &&
130 (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
131 return true;
135 return false;
139 * Check whether the tile is water.
140 * @param tile the tile to investigate.
141 * @return true if and only if the tile is a water tile
143 static bool CMSAWater(TileIndex tile)
145 return IsPlainWaterTile(tile);
149 * Check whether the tile is a tree.
150 * @param tile the tile to investigate.
151 * @return true if and only if the tile is a tree tile
153 static bool CMSATree(TileIndex tile)
155 return IsTreeTile(tile);
158 #define M(x) ((x) - STR_SV_STNAME)
160 enum StationNaming {
161 STATIONNAMING_RAIL,
162 STATIONNAMING_ROAD,
163 STATIONNAMING_AIRPORT,
164 STATIONNAMING_OILRIG,
165 STATIONNAMING_DOCK,
166 STATIONNAMING_HELIPORT,
169 /** Information to handle station action 0 property 24 correctly */
170 struct StationNameInformation {
171 uint32 free_names; ///< Current bitset of free names (we can remove names).
172 bool *indtypes; ///< Array of bools telling whether an industry type has been found.
176 * Find a station action 0 property 24 station name, or reduce the
177 * free_names if needed.
178 * @param tile the tile to search
179 * @param user_data the StationNameInformation to base the search on
180 * @return true if the tile contains an industry that has not given
181 * its name to one of the other stations in town.
183 static bool FindNearIndustryName(TileIndex tile, void *user_data)
185 /* All already found industry types */
186 StationNameInformation *sni = (StationNameInformation*)user_data;
187 if (!IsIndustryTile(tile)) return false;
189 /* If the station name is undefined it means that it doesn't name a station */
190 IndustryType indtype = GetIndustryType(tile);
191 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
193 /* In all cases if an industry that provides a name is found two of
194 * the standard names will be disabled. */
195 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
196 return !sni->indtypes[indtype];
199 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
201 static const uint32 _gen_station_name_bits[] = {
202 0, // STATIONNAMING_RAIL
203 0, // STATIONNAMING_ROAD
204 1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
205 1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
206 1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
207 1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
210 const Town *t = st->town;
211 uint32 free_names = UINT32_MAX;
213 bool indtypes[NUM_INDUSTRYTYPES];
214 memset(indtypes, 0, sizeof(indtypes));
216 const Station *s;
217 FOR_ALL_STATIONS(s) {
218 if (s != st && s->town == t) {
219 if (s->indtype != IT_INVALID) {
220 indtypes[s->indtype] = true;
221 continue;
223 uint str = M(s->string_id);
224 if (str <= 0x20) {
225 if (str == M(STR_SV_STNAME_FOREST)) {
226 str = M(STR_SV_STNAME_WOODS);
228 ClrBit(free_names, str);
233 TileIndex indtile = tile;
234 StationNameInformation sni = { free_names, indtypes };
235 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
236 /* An industry has been found nearby */
237 IndustryType indtype = GetIndustryType(indtile);
238 const IndustrySpec *indsp = GetIndustrySpec(indtype);
239 /* STR_NULL means it only disables oil rig/mines */
240 if (indsp->station_name != STR_NULL) {
241 st->indtype = indtype;
242 return STR_SV_STNAME_FALLBACK;
246 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
247 free_names = sni.free_names;
249 /* check default names */
250 uint32 tmp = free_names & _gen_station_name_bits[name_class];
251 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
253 /* check mine? */
254 if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
255 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
256 return STR_SV_STNAME_MINES;
260 /* check close enough to town to get central as name? */
261 if (DistanceMax(tile, t->xy) < 8) {
262 if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
264 if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
267 /* Check lakeside */
268 if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
269 DistanceFromEdge(tile) < 20 &&
270 CountMapSquareAround(tile, CMSAWater) >= 5) {
271 return STR_SV_STNAME_LAKESIDE;
274 /* Check woods */
275 if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
276 CountMapSquareAround(tile, CMSATree) >= 8 ||
277 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
279 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
282 /* check elevation compared to town */
283 int z = GetTileZ(tile);
284 int z2 = GetTileZ(t->xy);
285 if (z < z2) {
286 if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
287 } else if (z > z2) {
288 if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
291 /* check direction compared to town */
292 static const int8 _direction_and_table[] = {
293 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
294 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
295 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
296 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
299 free_names &= _direction_and_table[
300 (TileX(tile) < TileX(t->xy)) +
301 (TileY(tile) < TileY(t->xy)) * 2];
303 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));
304 return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
306 #undef M
309 * Find the closest deleted station of the current company
310 * @param tile the tile to search from.
311 * @return the closest station or NULL if too far.
313 static Station *GetClosestDeletedStation(TileIndex tile)
315 uint threshold = 8;
316 Station *best_station = NULL;
317 Station *st;
319 FOR_ALL_STATIONS(st) {
320 if (!st->IsInUse() && st->owner == _current_company) {
321 uint cur_dist = DistanceManhattan(tile, st->xy);
323 if (cur_dist < threshold) {
324 threshold = cur_dist;
325 best_station = st;
330 return best_station;
334 void Station::GetTileArea(TileArea *ta, StationType type) const
336 switch (type) {
337 case STATION_RAIL:
338 *ta = this->train_station;
339 return;
341 case STATION_AIRPORT:
342 *ta = this->airport;
343 return;
345 case STATION_TRUCK:
346 *ta = this->truck_station;
347 return;
349 case STATION_BUS:
350 *ta = this->bus_station;
351 return;
353 case STATION_DOCK:
354 case STATION_OILRIG:
355 *ta = this->dock_area;
356 break;
358 default: NOT_REACHED();
361 ta->w = 1;
362 ta->h = 1;
366 * Update the virtual coords needed to draw the station sign.
368 void Station::UpdateVirtCoord()
370 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
372 pt.y -= 32 * ZOOM_LVL_BASE;
373 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
375 SetDParam(0, this->index);
376 SetDParam(1, this->facilities);
377 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
379 SetWindowDirty(WC_STATION_VIEW, this->index);
382 /** Update the virtual coords needed to draw the station sign for all stations. */
383 void UpdateAllStationVirtCoords()
385 BaseStation *st;
387 FOR_ALL_BASE_STATIONS(st) {
388 st->UpdateVirtCoord();
393 * Get a mask of the cargo types that the station accepts.
394 * @param st Station to query
395 * @return the expected mask
397 static uint GetAcceptanceMask(const Station *st)
399 uint mask = 0;
401 for (CargoID i = 0; i < NUM_CARGO; i++) {
402 if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) mask |= 1 << i;
404 return mask;
408 * Items contains the two cargo names that are to be accepted or rejected.
409 * msg is the string id of the message to display.
411 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
413 for (uint i = 0; i < num_items; i++) {
414 SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
417 SetDParam(0, st->index);
418 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
422 * Get the cargo types being produced around the tile (in a rectangle).
423 * @param tile Northtile of area
424 * @param w X extent of the area
425 * @param h Y extent of the area
426 * @param rad Search radius in addition to the given area
428 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
430 CargoArray produced;
432 int x = TileX(tile);
433 int y = TileY(tile);
435 /* expand the region by rad tiles on each side
436 * while making sure that we remain inside the board. */
437 int x2 = min(x + w + rad, MapSizeX());
438 int x1 = max(x - rad, 0);
440 int y2 = min(y + h + rad, MapSizeY());
441 int y1 = max(y - rad, 0);
443 assert(x1 < x2);
444 assert(y1 < y2);
445 assert(w > 0);
446 assert(h > 0);
448 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
450 /* Loop over all tiles to get the produced cargo of
451 * everything except industries */
452 TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
454 /* Loop over the industries. They produce cargo for
455 * anything that is within 'rad' from their bounding
456 * box. As such if you have e.g. a oil well the tile
457 * area loop might not hit an industry tile while
458 * the industry would produce cargo for the station.
460 const Industry *i;
461 FOR_ALL_INDUSTRIES(i) {
462 if (!ta.Intersects(i->location)) continue;
464 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
465 CargoID cargo = i->produced_cargo[j];
466 if (cargo != CT_INVALID) produced[cargo]++;
470 return produced;
474 * Get the acceptance of cargoes around the tile in 1/8.
475 * @param tile Center of the search area
476 * @param w X extent of area
477 * @param h Y extent of area
478 * @param rad Search radius in addition to given area
479 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be NULL
481 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
483 CargoArray acceptance;
484 if (always_accepted != NULL) *always_accepted = 0;
486 int x = TileX(tile);
487 int y = TileY(tile);
489 /* expand the region by rad tiles on each side
490 * while making sure that we remain inside the board. */
491 int x2 = min(x + w + rad, MapSizeX());
492 int y2 = min(y + h + rad, MapSizeY());
493 int x1 = max(x - rad, 0);
494 int y1 = max(y - rad, 0);
496 assert(x1 < x2);
497 assert(y1 < y2);
498 assert(w > 0);
499 assert(h > 0);
501 for (int yc = y1; yc != y2; yc++) {
502 for (int xc = x1; xc != x2; xc++) {
503 TileIndex tile = TileXY(xc, yc);
504 AddAcceptedCargo(tile, acceptance, always_accepted);
508 return acceptance;
512 * Update the acceptance for a station.
513 * @param st Station to update
514 * @param show_msg controls whether to display a message that acceptance was changed.
516 void UpdateStationAcceptance(Station *st, bool show_msg)
518 /* old accepted goods types */
519 uint old_acc = GetAcceptanceMask(st);
521 /* And retrieve the acceptance. */
522 CargoArray acceptance;
523 if (!st->rect.IsEmpty()) {
524 acceptance = GetAcceptanceAroundTiles(
525 TileXY(st->rect.left, st->rect.top),
526 st->rect.right - st->rect.left + 1,
527 st->rect.bottom - st->rect.top + 1,
528 st->GetCatchmentRadius(),
529 &st->always_accepted
533 /* Adjust in case our station only accepts fewer kinds of goods */
534 for (CargoID i = 0; i < NUM_CARGO; i++) {
535 uint amt = acceptance[i];
537 /* Make sure the station can accept the goods type. */
538 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
539 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
540 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
541 amt = 0;
544 GoodsEntry &ge = st->goods[i];
545 SB(ge.acceptance_pickup, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
546 if (LinkGraph::IsValidID(ge.link_graph)) {
547 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
551 /* Only show a message in case the acceptance was actually changed. */
552 uint new_acc = GetAcceptanceMask(st);
553 if (old_acc == new_acc) return;
555 /* show a message to report that the acceptance was changed? */
556 if (show_msg && st->owner == _local_company && st->IsInUse()) {
557 /* List of accept and reject strings for different number of
558 * cargo types */
559 static const StringID accept_msg[] = {
560 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
561 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
563 static const StringID reject_msg[] = {
564 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
565 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
568 /* Array of accepted and rejected cargo types */
569 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
570 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
571 uint num_acc = 0;
572 uint num_rej = 0;
574 /* Test each cargo type to see if its acceptance has changed */
575 for (CargoID i = 0; i < NUM_CARGO; i++) {
576 if (HasBit(new_acc, i)) {
577 if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
578 /* New cargo is accepted */
579 accepts[num_acc++] = i;
581 } else {
582 if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
583 /* Old cargo is no longer accepted */
584 rejects[num_rej++] = i;
589 /* Show news message if there are any changes */
590 if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
591 if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
594 /* redraw the station view since acceptance changed */
595 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
598 static void UpdateStationSignCoord(BaseStation *st)
600 const StationRect *r = &st->rect;
602 if (r->IsEmpty()) return; // no tiles belong to this station
604 /* clamp sign coord to be inside the station rect */
605 st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
606 st->UpdateVirtCoord();
610 * Common part of building various station parts and possibly attaching them to an existing one.
611 * @param [in,out] st Station to attach to
612 * @param flags Command flags
613 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
614 * @param area Area occupied by the new part
615 * @param name_class Station naming class to use to generate the new station's name
616 * @return Command error that occured, if any
618 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
620 /* Find a deleted station close to us */
621 if (*st == NULL && reuse) *st = GetClosestDeletedStation(area.tile);
623 if (*st != NULL) {
624 if ((*st)->owner != _current_company) {
625 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
628 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
629 if (ret.Failed()) return ret;
630 } else {
631 /* allocate and initialize new station */
632 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
634 if (flags & DC_EXEC) {
635 *st = new Station(area.tile);
637 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
638 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
640 if (Company::IsValidID(_current_company)) {
641 SetBit((*st)->town->have_ratings, _current_company);
645 return CommandCost();
649 * This is called right after a station was deleted.
650 * It checks if the whole station is free of substations, and if so, the station will be
651 * deleted after a little while.
652 * @param st Station
654 static void DeleteStationIfEmpty(BaseStation *st)
656 if (!st->IsInUse()) {
657 st->delete_ctr = 0;
658 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
660 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
661 UpdateStationSignCoord(st);
664 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
667 * Checks if the given tile is buildable, flat and has a certain height.
668 * @param tile TileIndex to check.
669 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
670 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
671 * @param allow_steep Whether steep slopes are allowed.
672 * @param check_bridge Check for the existence of a bridge.
673 * @return The cost in case of success, or an error code if it failed.
675 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
677 if (check_bridge && HasBridgeAbove(tile)) {
678 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
681 CommandCost ret = EnsureNoVehicleOnGround(tile);
682 if (ret.Failed()) return ret;
684 int z;
685 Slope tileh = GetTileSlope(tile, &z);
687 /* Prohibit building if
688 * 1) The tile is "steep" (i.e. stretches two height levels).
689 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
691 if ((!allow_steep && IsSteepSlope(tileh)) ||
692 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
693 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
696 CommandCost cost(EXPENSES_CONSTRUCTION);
697 int flat_z = z + GetSlopeMaxZ(tileh);
698 if (tileh != SLOPE_FLAT) {
699 /* Forbid building if the tile faces a slope in a invalid direction. */
700 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
701 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
702 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
705 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
708 /* The level of this tile must be equal to allowed_z. */
709 if (allowed_z < 0) {
710 /* First tile. */
711 allowed_z = flat_z;
712 } else if (allowed_z != flat_z) {
713 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
716 return cost;
720 * Tries to clear the given area.
721 * @param tile_area Area to check.
722 * @param flags Operation to perform.
723 * @return The cost in case of success, or an error code if it failed.
725 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
727 CommandCost cost(EXPENSES_CONSTRUCTION);
728 int allowed_z = -1;
730 TILE_AREA_LOOP(tile_cur, tile_area) {
731 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
732 if (ret.Failed()) return ret;
733 cost.AddCost(ret);
735 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
736 if (ret.Failed()) return ret;
737 cost.AddCost(ret);
740 return cost;
744 * Checks if a rail station can be built at the given area.
745 * @param tile_area Area to check.
746 * @param flags Operation to perform.
747 * @param axis Rail station axis.
748 * @param station StationID to be queried and returned if available.
749 * @param rt The rail type to check for (overbuilding rail stations over rail).
750 * @param affected_vehicles List of trains with PBS reservations on the tiles
751 * @param spec_class Station class.
752 * @param spec_index Index into the station class.
753 * @param plat_len Platform length.
754 * @param numtracks Number of platforms.
755 * @return The cost in case of success, or an error code if it failed.
757 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, SmallVector<Train *, 4> &affected_vehicles, StationClassID spec_class, byte spec_index, byte plat_len, byte numtracks)
759 CommandCost cost(EXPENSES_CONSTRUCTION);
760 int allowed_z = -1;
761 uint invalid_dirs = 5 << axis;
763 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
764 bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
766 TILE_AREA_LOOP(tile_cur, tile_area) {
767 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
768 if (ret.Failed()) return ret;
769 cost.AddCost(ret);
771 if (slope_cb) {
772 /* Do slope check if requested. */
773 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
774 if (ret.Failed()) return ret;
777 /* if station is set, then we have special handling to allow building on top of already existing stations.
778 * so station points to INVALID_STATION if we can build on any station.
779 * Or it points to a station if we're only allowed to build on exactly that station. */
780 if (station != NULL && IsStationTile(tile_cur)) {
781 if (!IsRailStation(tile_cur)) {
782 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
783 } else {
784 StationID st = GetStationIndex(tile_cur);
785 if (*station == INVALID_STATION) {
786 *station = st;
787 } else if (*station != st) {
788 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
791 } else {
792 /* Rail type is only valid when building a railway station; if station to
793 * build isn't a rail station it's INVALID_RAILTYPE. */
794 if (rt != INVALID_RAILTYPE && IsNormalRailTile(tile_cur) &&
795 HasPowerOnRail(GetRailType(tile_cur), rt)) {
796 /* Allow overbuilding if the tile:
797 * - has rail, but no signals
798 * - it has exactly one track
799 * - the track is in line with the station
800 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
802 Track track = AxisToTrack(axis);
804 if (GetTrackBits(tile_cur) == TrackToTrackBits(track) && !HasSignalOnTrack(tile_cur, track)) {
805 /* Check for trains having a reservation for this tile. */
806 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
807 Train *v = GetTrainForReservation(tile_cur, track);
808 if (v != NULL) {
809 *affected_vehicles.Append() = v;
812 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
813 if (ret.Failed()) return ret;
814 cost.AddCost(ret);
815 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
816 continue;
819 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
820 if (ret.Failed()) return ret;
821 cost.AddCost(ret);
825 return cost;
829 * Checks if a road stop can be built at the given tile.
830 * @param tile_area Area to check.
831 * @param flags Operation to perform.
832 * @param invalid_dirs Prohibited directions (set of DiagDirections).
833 * @param is_drive_through True if trying to build a drive-through station.
834 * @param is_truck_stop True when building a truck stop, false otherwise.
835 * @param axis Axis of a drive-through road stop.
836 * @param station StationID to be queried and returned if available.
837 * @param rts Road types to build.
838 * @return The cost in case of success, or an error code if it failed.
840 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)
842 CommandCost cost(EXPENSES_CONSTRUCTION);
843 int allowed_z = -1;
845 TILE_AREA_LOOP(cur_tile, tile_area) {
846 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
847 if (ret.Failed()) return ret;
848 cost.AddCost(ret);
850 /* If station is set, then we have special handling to allow building on top of already existing stations.
851 * Station points to INVALID_STATION if we can build on any station.
852 * Or it points to a station if we're only allowed to build on exactly that station. */
853 if (station != NULL && IsStationTile(cur_tile)) {
854 if (!IsRoadStop(cur_tile)) {
855 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
856 } else {
857 if (is_truck_stop != IsTruckStop(cur_tile) ||
858 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
859 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
861 /* Drive-through station in the wrong direction. */
862 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && GetRoadStopAxis(cur_tile) != axis){
863 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
865 StationID st = GetStationIndex(cur_tile);
866 if (*station == INVALID_STATION) {
867 *station = st;
868 } else if (*station != st) {
869 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
872 } else {
873 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
874 /* Road bits in the wrong direction. */
875 RoadBits rb = IsRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
876 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
877 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
878 switch (CountBits(rb)) {
879 case 1:
880 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
882 case 2:
883 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
884 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
886 default: // 3 or 4
887 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
891 RoadTypes cur_rts = IsRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
892 uint num_roadbits = 0;
893 if (build_over_road) {
894 /* There is a road, check if we can build road+tram stop over it. */
895 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
896 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
897 if (road_owner == OWNER_TOWN) {
898 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
899 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
900 CommandCost ret = CheckOwnership(road_owner);
901 if (ret.Failed()) return ret;
903 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
906 /* There is a tram, check if we can build road+tram stop over it. */
907 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
908 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
909 if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
910 CommandCost ret = CheckOwnership(tram_owner);
911 if (ret.Failed()) return ret;
913 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
916 /* Take into account existing roadbits. */
917 rts |= cur_rts;
918 } else {
919 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
920 if (ret.Failed()) return ret;
921 cost.AddCost(ret);
924 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
925 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
929 return cost;
933 * Checks if an airport can be built at the given area.
934 * @param tile_area Area to check.
935 * @param flags Operation to perform.
936 * @param station StationID of airport allowed in search area.
937 * @return The cost in case of success, or an error code if it failed.
939 static CommandCost CheckFlatLandAirport(TileArea tile_area, DoCommandFlag flags, StationID *station)
941 CommandCost cost(EXPENSES_CONSTRUCTION);
942 int allowed_z = -1;
944 TILE_AREA_LOOP(tile_cur, tile_area) {
945 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
946 if (ret.Failed()) return ret;
947 cost.AddCost(ret);
949 /* if station is set, then allow building on top of an already
950 * existing airport, either the one in *station if it is not
951 * INVALID_STATION, or anyone otherwise and store which one
952 * in *station */
953 if (station != NULL && IsStationTile(tile_cur)) {
954 if (!IsAirport(tile_cur)) {
955 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
956 } else {
957 StationID st = GetStationIndex(tile_cur);
958 if (*station == INVALID_STATION) {
959 *station = st;
960 } else if (*station != st) {
961 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
964 } else {
965 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
966 if (ret.Failed()) return ret;
967 cost.AddCost(ret);
971 return cost;
975 * Check whether we can expand the rail part of the given station.
976 * @param st the station to expand
977 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
978 * @param axis the axis of the newly build rail
979 * @return Succeeded or failed command.
981 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
983 TileArea cur_ta = st->train_station;
985 /* determine new size of train station region.. */
986 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
987 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
988 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
989 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
990 new_ta.tile = TileXY(x, y);
992 /* make sure the final size is not too big. */
993 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
994 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
997 return CommandCost();
1000 static inline byte *CreateSingle(byte *layout, int n)
1002 int i = n;
1003 do *layout++ = 0; while (--i);
1004 layout[((n - 1) >> 1) - n] = 2;
1005 return layout;
1008 static inline byte *CreateMulti(byte *layout, int n, byte b)
1010 int i = n;
1011 do *layout++ = b; while (--i);
1012 if (n > 4) {
1013 layout[0 - n] = 0;
1014 layout[n - 1 - n] = 0;
1016 return layout;
1020 * Create the station layout for the given number of tracks and platform length.
1021 * @param layout The layout to write to.
1022 * @param numtracks The number of tracks to write.
1023 * @param plat_len The length of the platforms.
1024 * @param statspec The specification of the station to (possibly) get the layout from.
1026 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
1028 if (statspec != NULL && statspec->lengths >= plat_len &&
1029 statspec->platforms[plat_len - 1] >= numtracks &&
1030 statspec->layouts[plat_len - 1][numtracks - 1]) {
1031 /* Custom layout defined, follow it. */
1032 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
1033 plat_len * numtracks);
1034 return;
1037 if (plat_len == 1) {
1038 CreateSingle(layout, numtracks);
1039 } else {
1040 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1041 numtracks >>= 1;
1043 while (--numtracks >= 0) {
1044 layout = CreateMulti(layout, plat_len, 4);
1045 layout = CreateMulti(layout, plat_len, 6);
1051 * Find a nearby station that joins this station.
1052 * @tparam T the class to find a station for
1053 * @param existing_station an existing station we build over
1054 * @param station_to_join the station to join to
1055 * @param adjacent whether adjacent stations are allowed
1056 * @param ta the area of the newly build station
1057 * @param st 'return' pointer for the found station
1058 * @param error_message the error message when building a station on top of others
1059 * @return command cost with the error or 'okay'
1061 template <class T>
1062 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, StringID error_message)
1064 assert(*st == NULL);
1066 bool check_surrounding;
1067 if (!_settings_game.station.adjacent_stations) {
1068 check_surrounding = true;
1069 } else if (existing_station == INVALID_STATION) {
1070 /* There's no station here. Don't check the tiles surrounding this
1071 * one if the company wanted to build an adjacent station. */
1072 check_surrounding = !adjacent;
1073 } else if (adjacent && existing_station != station_to_join) {
1074 /* You can't build an adjacent station over the top of one that
1075 * already exists. */
1076 return_cmd_error(error_message);
1077 } else {
1078 /* Extend the current station, and don't check whether it will
1079 * be near any other stations. */
1080 *st = T::GetIfValid(existing_station);
1081 check_surrounding = (*st == NULL);
1084 if (check_surrounding) {
1085 /* Make sure there are no similar stations around us. */
1086 ta.tile -= TileDiffXY(1, 1);
1087 ta.w += 2;
1088 ta.h += 2;
1090 /* check around to see if there are any stations there */
1091 TILE_AREA_LOOP(tile_cur, ta) {
1092 if (IsStationTile(tile_cur)) {
1093 StationID t = GetStationIndex(tile_cur);
1094 if (!T::IsValidID(t)) continue;
1096 if (existing_station == INVALID_STATION) {
1097 existing_station = t;
1098 } else if (existing_station != t) {
1099 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1104 *st = (existing_station == INVALID_STATION) ? NULL : T::Get(existing_station);
1107 /* Distant join */
1108 if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1110 return CommandCost();
1114 * Find a nearby station that joins this station.
1115 * @param existing_station an existing station we build over
1116 * @param station_to_join the station to join to
1117 * @param adjacent whether adjacent stations are allowed
1118 * @param ta the area of the newly build station
1119 * @param st 'return' pointer for the found station
1120 * @param error_message the error message when building a station on top of others
1121 * @return command cost with the error or 'okay'
1123 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st, StringID error_message = STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST)
1125 return FindJoiningBaseStation<Station>(existing_station, station_to_join, adjacent, ta, st, error_message);
1129 * Find a nearby waypoint that joins this waypoint.
1130 * @param existing_waypoint an existing waypoint we build over
1131 * @param waypoint_to_join the waypoint to join to
1132 * @param adjacent whether adjacent waypoints are allowed
1133 * @param ta the area of the newly build waypoint
1134 * @param wp 'return' pointer for the found waypoint
1135 * @return command cost with the error or 'okay'
1137 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
1139 return FindJoiningBaseStation<Waypoint>(existing_waypoint, waypoint_to_join, adjacent, ta, wp, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST);
1142 static void FreeTrainReservation(Train *v)
1144 FreeTrainTrackReservation(v);
1146 const RailPathPos pos = v->GetPos();
1147 if (!pos.in_wormhole() && IsRailStationTile(pos.tile)) SetRailStationPlatformReservation(pos, false);
1149 const RailPathPos rev = v->Last()->GetReversePos();
1150 if (!rev.in_wormhole() && IsRailStationTile(rev.tile)) SetRailStationPlatformReservation(rev, false);
1153 static void RestoreTrainReservation(Train *v)
1155 const RailPathPos pos = v->GetPos();
1156 if (!pos.in_wormhole() && IsRailStationTile(pos.tile)) SetRailStationPlatformReservation(pos, true);
1158 TryPathReserve(v, true, true);
1160 const RailPathPos rev = v->Last()->GetReversePos();
1161 if (!rev.in_wormhole() && IsRailStationTile(rev.tile)) SetRailStationPlatformReservation(rev, true);
1165 * Build rail station
1166 * @param tile_org northern most position of station dragging/placement
1167 * @param flags operation to perform
1168 * @param p1 various bitstuffed elements
1169 * - p1 = (bit 0- 3) - railtype
1170 * - p1 = (bit 4) - orientation (Axis)
1171 * - p1 = (bit 8-15) - number of tracks
1172 * - p1 = (bit 16-23) - platform length
1173 * - p1 = (bit 24) - allow stations directly adjacent to other stations.
1174 * @param p2 various bitstuffed elements
1175 * - p2 = (bit 0- 7) - custom station class
1176 * - p2 = (bit 8-15) - custom station id
1177 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
1178 * @param text unused
1179 * @return the cost of this operation or an error
1181 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1183 /* Unpack parameters */
1184 RailType rt = Extract<RailType, 0, 4>(p1);
1185 Axis axis = Extract<Axis, 4, 1>(p1);
1186 byte numtracks = GB(p1, 8, 8);
1187 byte plat_len = GB(p1, 16, 8);
1188 bool adjacent = HasBit(p1, 24);
1190 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
1191 byte spec_index = GB(p2, 8, 8);
1192 StationID station_to_join = GB(p2, 16, 16);
1194 /* Does the authority allow this? */
1195 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1196 if (ret.Failed()) return ret;
1198 if (!ValParamRailtype(rt)) return CMD_ERROR;
1200 /* Check if the given station class is valid */
1201 if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
1202 if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
1203 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1205 int w_org, h_org;
1206 if (axis == AXIS_X) {
1207 w_org = plat_len;
1208 h_org = numtracks;
1209 } else {
1210 h_org = plat_len;
1211 w_org = numtracks;
1214 bool reuse = (station_to_join != NEW_STATION);
1215 if (!reuse) station_to_join = INVALID_STATION;
1216 bool distant_join = (station_to_join != INVALID_STATION);
1218 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1220 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1222 /* these values are those that will be stored in train_tile and station_platforms */
1223 TileArea new_location(tile_org, w_org, h_org);
1225 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1226 StationID est = INVALID_STATION;
1227 SmallVector<Train *, 4> affected_vehicles;
1228 /* Clear the land below the station. */
1229 CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1230 if (cost.Failed()) return cost;
1231 /* Add construction expenses. */
1232 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
1233 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
1235 Station *st = NULL;
1236 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1237 if (ret.Failed()) return ret;
1239 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1240 if (ret.Failed()) return ret;
1242 if (st != NULL && st->train_station.tile != INVALID_TILE) {
1243 CommandCost ret = CanExpandRailStation(st, new_location, axis);
1244 if (ret.Failed()) return ret;
1247 /* Check if we can allocate a custom stationspec to this station */
1248 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1249 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1250 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1252 if (statspec != NULL) {
1253 /* Perform NewStation checks */
1255 /* Check if the station size is permitted */
1256 if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
1257 return CMD_ERROR;
1260 /* Check if the station is buildable */
1261 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1262 uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
1263 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1267 if (flags & DC_EXEC) {
1268 TileIndexDiff tile_delta;
1269 byte *layout_ptr;
1270 byte numtracks_orig;
1271 Track track;
1273 st->train_station = new_location;
1274 st->AddFacility(FACIL_TRAIN, new_location.tile);
1276 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1278 if (statspec != NULL) {
1279 /* Include this station spec's animation trigger bitmask
1280 * in the station's cached copy. */
1281 st->cached_anim_triggers |= statspec->animation.triggers;
1284 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1285 track = AxisToTrack(axis);
1287 layout_ptr = AllocaM(byte, numtracks * plat_len);
1288 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
1290 numtracks_orig = numtracks;
1292 Company *c = Company::Get(st->owner);
1293 TileIndex tile_track = tile_org;
1294 do {
1295 TileIndex tile = tile_track;
1296 int w = plat_len;
1297 do {
1298 byte layout = *layout_ptr++;
1299 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1300 /* Check for trains having a reservation for this tile. */
1301 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1302 if (v != NULL) {
1303 *affected_vehicles.Append() = v;
1304 FreeTrainReservation(v);
1308 /* Railtype can change when overbuilding. */
1309 if (IsRailStationTile(tile)) {
1310 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1311 c->infrastructure.station--;
1314 /* Remove animation if overbuilding */
1315 DeleteAnimatedTile(tile);
1316 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1317 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1318 /* Free the spec if we overbuild something */
1319 DeallocateSpecFromStation(st, old_specindex);
1321 SetCustomStationSpecIndex(tile, specindex);
1322 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1323 SetAnimationFrame(tile, 0);
1325 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1326 c->infrastructure.station++;
1328 if (statspec != NULL) {
1329 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1330 uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1332 /* As the station is not yet completely finished, the station does not yet exist. */
1333 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
1334 if (callback != CALLBACK_FAILED) {
1335 if (callback < 8) {
1336 SetStationGfx(tile, (callback & ~1) + axis);
1337 } else {
1338 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
1342 /* Trigger station animation -- after building? */
1343 TriggerStationAnimation(st, tile, SAT_BUILT);
1346 tile += tile_delta;
1347 } while (--w);
1348 AddTrackToSignalBuffer(tile_track, track, _current_company);
1349 YapfNotifyTrackLayoutChange(tile_track, track);
1350 tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1351 } while (--numtracks);
1353 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
1354 RestoreTrainReservation(affected_vehicles[i]);
1357 /* Check whether we need to expand the reservation of trains already on the station. */
1358 TileArea update_reservation_area;
1359 if (axis == AXIS_X) {
1360 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1361 } else {
1362 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1365 TILE_AREA_LOOP(tile, update_reservation_area) {
1366 /* Don't even try to make eye candy parts reserved. */
1367 if (IsStationTileBlocked(tile)) continue;
1369 DiagDirection dir = AxisToDiagDir(axis);
1370 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1371 TileIndex platform_begin = tile;
1372 TileIndex platform_end = tile;
1374 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1375 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1376 platform_begin = next_tile;
1378 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1379 platform_end = next_tile;
1382 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1383 bool reservation = false;
1384 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1385 reservation = HasStationReservation(t);
1388 if (reservation) {
1389 SetRailStationPlatformReservation(platform_begin, dir, true);
1393 st->MarkTilesDirty(false);
1394 st->UpdateVirtCoord();
1395 UpdateStationAcceptance(st, false);
1396 st->RecomputeIndustriesNear();
1397 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
1398 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
1399 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1400 DirtyCompanyInfrastructureWindows(st->owner);
1403 return cost;
1406 static void MakeRailStationAreaSmaller(BaseStation *st)
1408 TileArea ta = st->train_station;
1410 restart:
1412 /* too small? */
1413 if (ta.w != 0 && ta.h != 0) {
1414 /* check the left side, x = constant, y changes */
1415 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
1416 /* the left side is unused? */
1417 if (++i == ta.h) {
1418 ta.tile += TileDiffXY(1, 0);
1419 ta.w--;
1420 goto restart;
1424 /* check the right side, x = constant, y changes */
1425 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
1426 /* the right side is unused? */
1427 if (++i == ta.h) {
1428 ta.w--;
1429 goto restart;
1433 /* check the upper side, y = constant, x changes */
1434 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
1435 /* the left side is unused? */
1436 if (++i == ta.w) {
1437 ta.tile += TileDiffXY(0, 1);
1438 ta.h--;
1439 goto restart;
1443 /* check the lower side, y = constant, x changes */
1444 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
1445 /* the left side is unused? */
1446 if (++i == ta.w) {
1447 ta.h--;
1448 goto restart;
1451 } else {
1452 ta.Clear();
1455 st->train_station = ta;
1459 * Remove a number of tiles from any rail station within the area.
1460 * @param ta the area to clear station tile from.
1461 * @param affected_stations the stations affected.
1462 * @param flags the command flags.
1463 * @param removal_cost the cost for removing the tile, including the rail.
1464 * @param keep_rail whether to keep the rail of the station.
1465 * @tparam T the type of station to remove.
1466 * @return the number of cleared tiles or an error.
1468 template <class T>
1469 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1471 /* Count of the number of tiles removed */
1472 int quantity = 0;
1473 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1474 /* Accumulator for the errors seen during clearing. If no errors happen,
1475 * and the quantity is 0 there is no station. Otherwise it will be one
1476 * of the other error that got accumulated. */
1477 CommandCost error;
1479 /* Do the action for every tile into the area */
1480 TILE_AREA_LOOP(tile, ta) {
1481 /* Make sure the specified tile is a rail station */
1482 if (!HasStationTileRail(tile)) continue;
1484 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1485 CommandCost ret = EnsureNoVehicleOnGround(tile);
1486 error.AddCost(ret);
1487 if (ret.Failed()) continue;
1489 /* Check ownership of station */
1490 T *st = T::GetByTile(tile);
1491 if (st == NULL) continue;
1493 if (_current_company != OWNER_WATER) {
1494 CommandCost ret = CheckOwnership(st->owner);
1495 error.AddCost(ret);
1496 if (ret.Failed()) continue;
1499 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1500 quantity++;
1502 if (keep_rail || IsStationTileBlocked(tile)) {
1503 /* Don't refund the 'steel' of the track when we keep the
1504 * rail, or when the tile didn't have any rail at all. */
1505 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1508 if (flags & DC_EXEC) {
1509 /* read variables before the station tile is removed */
1510 uint specindex = GetCustomStationSpecIndex(tile);
1511 Track track = GetRailStationTrack(tile);
1512 Owner owner = GetTileOwner(tile);
1513 RailType rt = GetRailType(tile);
1514 Train *v = NULL;
1516 if (HasStationReservation(tile)) {
1517 v = GetTrainForReservation(tile, track);
1518 if (v != NULL) FreeTrainReservation(v);
1521 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1522 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1524 DoClearSquare(tile);
1525 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1526 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1527 Company::Get(owner)->infrastructure.station--;
1528 DirtyCompanyInfrastructureWindows(owner);
1530 st->rect.AfterRemoveTile(st, tile);
1531 AddTrackToSignalBuffer(tile, track, owner);
1532 YapfNotifyTrackLayoutChange(tile, track);
1534 DeallocateSpecFromStation(st, specindex);
1536 affected_stations.Include(st);
1538 if (v != NULL) RestoreTrainReservation(v);
1542 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1544 for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1545 T *st = *stp;
1547 /* now we need to make the "spanned" area of the railway station smaller
1548 * if we deleted something at the edges.
1549 * we also need to adjust train_tile. */
1550 MakeRailStationAreaSmaller(st);
1551 UpdateStationSignCoord(st);
1553 /* if we deleted the whole station, delete the train facility. */
1554 if (st->train_station.tile == INVALID_TILE) {
1555 st->facilities &= ~FACIL_TRAIN;
1556 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1557 st->UpdateVirtCoord();
1558 DeleteStationIfEmpty(st);
1562 total_cost.AddCost(quantity * removal_cost);
1563 return total_cost;
1567 * Remove a single tile from a rail station.
1568 * This allows for custom-built station with holes and weird layouts
1569 * @param start tile of station piece to remove
1570 * @param flags operation to perform
1571 * @param p1 start_tile
1572 * @param p2 various bitstuffed elements
1573 * - p2 = bit 0 - if set keep the rail
1574 * @param text unused
1575 * @return the cost of this operation or an error
1577 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1579 TileIndex end = p1 == 0 ? start : p1;
1580 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1582 TileArea ta(start, end);
1583 SmallVector<Station *, 4> affected_stations;
1585 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
1586 if (ret.Failed()) return ret;
1588 /* Do all station specific functions here. */
1589 for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1590 Station *st = *stp;
1592 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1593 st->MarkTilesDirty(false);
1594 st->RecomputeIndustriesNear();
1597 /* Now apply the rail cost to the number that we deleted */
1598 return ret;
1602 * Remove a single tile from a waypoint.
1603 * This allows for custom-built waypoint with holes and weird layouts
1604 * @param start tile of waypoint piece to remove
1605 * @param flags operation to perform
1606 * @param p1 start_tile
1607 * @param p2 various bitstuffed elements
1608 * - p2 = bit 0 - if set keep the rail
1609 * @param text unused
1610 * @return the cost of this operation or an error
1612 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1614 TileIndex end = p1 == 0 ? start : p1;
1615 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1617 TileArea ta(start, end);
1618 SmallVector<Waypoint *, 4> affected_stations;
1620 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
1625 * Remove a rail station/waypoint
1626 * @param st The station/waypoint to remove the rail part from
1627 * @param flags operation to perform
1628 * @tparam T the type of station to remove
1629 * @return cost or failure of operation
1631 template <class T>
1632 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
1634 /* Current company owns the station? */
1635 if (_current_company != OWNER_WATER) {
1636 CommandCost ret = CheckOwnership(st->owner);
1637 if (ret.Failed()) return ret;
1640 /* determine width and height of platforms */
1641 TileArea ta = st->train_station;
1643 assert(ta.w != 0 && ta.h != 0);
1645 CommandCost cost(EXPENSES_CONSTRUCTION);
1646 /* clear all areas of the station */
1647 TILE_AREA_LOOP(tile, ta) {
1648 /* only remove tiles that are actually train station tiles */
1649 if (!st->TileBelongsToRailStation(tile)) continue;
1651 CommandCost ret = EnsureNoVehicleOnGround(tile);
1652 if (ret.Failed()) return ret;
1654 cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
1655 if (flags & DC_EXEC) {
1656 /* read variables before the station tile is removed */
1657 Track track = GetRailStationTrack(tile);
1658 Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
1659 Train *v = NULL;
1660 if (HasStationReservation(tile)) {
1661 v = GetTrainForReservation(tile, track);
1662 if (v != NULL) FreeTrainTrackReservation(v);
1664 if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1665 Company::Get(owner)->infrastructure.station--;
1666 DoClearSquare(tile);
1667 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1668 AddTrackToSignalBuffer(tile, track, owner);
1669 YapfNotifyTrackLayoutChange(tile, track);
1670 if (v != NULL) TryPathReserve(v, true);
1674 if (flags & DC_EXEC) {
1675 st->rect.AfterRemoveRect(st, st->train_station);
1677 st->train_station.Clear();
1679 st->facilities &= ~FACIL_TRAIN;
1681 free(st->speclist);
1682 st->num_specs = 0;
1683 st->speclist = NULL;
1684 st->cached_anim_triggers = 0;
1686 DirtyCompanyInfrastructureWindows(st->owner);
1687 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1688 st->UpdateVirtCoord();
1689 DeleteStationIfEmpty(st);
1692 return cost;
1696 * Remove a rail station
1697 * @param tile Tile of the station.
1698 * @param flags operation to perform
1699 * @return cost or failure of operation
1701 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1703 /* if there is flooding, remove platforms tile by tile */
1704 if (_current_company == OWNER_WATER) {
1705 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
1708 Station *st = Station::GetByTile(tile);
1709 CommandCost cost = RemoveRailStation(st, flags);
1711 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
1713 return cost;
1717 * Remove a rail waypoint
1718 * @param tile Tile of the waypoint.
1719 * @param flags operation to perform
1720 * @return cost or failure of operation
1722 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1724 /* if there is flooding, remove waypoints tile by tile */
1725 if (_current_company == OWNER_WATER) {
1726 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
1729 return RemoveRailStation(Waypoint::GetByTile(tile), flags);
1734 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1735 * @param st The Station to do the whole procedure for
1736 * @return a pointer to where to link a new RoadStop*
1738 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1740 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1742 if (*primary_stop == NULL) {
1743 /* we have no roadstop of the type yet, so write a "primary stop" */
1744 return primary_stop;
1745 } else {
1746 /* there are stops already, so append to the end of the list */
1747 RoadStop *stop = *primary_stop;
1748 while (stop->next != NULL) stop = stop->next;
1749 return &stop->next;
1753 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
1756 * Build a bus or truck stop.
1757 * @param tile Northernmost tile of the stop.
1758 * @param flags Operation to perform.
1759 * @param p1 bit 0..7: Width of the road stop.
1760 * bit 8..15: Length of the road stop.
1761 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1762 * bit 1: 0 For normal stops, 1 for drive-through.
1763 * bit 2..3: The roadtypes.
1764 * bit 5: Allow stations directly adjacent to other stations.
1765 * bit 6..7: Entrance direction (#DiagDirection).
1766 * bit 16..31: Station ID to join (NEW_STATION if build new one).
1767 * @param text Unused.
1768 * @return The cost of this operation or an error.
1770 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1772 bool type = HasBit(p2, 0);
1773 bool is_drive_through = HasBit(p2, 1);
1774 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
1775 StationID station_to_join = GB(p2, 16, 16);
1776 bool reuse = (station_to_join != NEW_STATION);
1777 if (!reuse) station_to_join = INVALID_STATION;
1778 bool distant_join = (station_to_join != INVALID_STATION);
1780 uint8 width = (uint8)GB(p1, 0, 8);
1781 uint8 lenght = (uint8)GB(p1, 8, 8);
1783 /* Check if the requested road stop is too big */
1784 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1785 /* Check for incorrect width / length. */
1786 if (width == 0 || lenght == 0) return CMD_ERROR;
1787 /* Check if the first tile and the last tile are valid */
1788 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
1790 TileArea roadstop_area(tile, width, lenght);
1792 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1794 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
1796 /* Trams only have drive through stops */
1797 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
1799 DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
1801 /* Safeguard the parameters. */
1802 if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
1803 /* If it is a drive-through stop, check for valid axis. */
1804 if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
1806 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
1807 if (ret.Failed()) return ret;
1809 /* Total road stop cost. */
1810 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
1811 StationID est = INVALID_STATION;
1812 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
1813 if (ret.Failed()) return ret;
1814 cost.AddCost(ret);
1816 Station *st = NULL;
1817 ret = FindJoiningStation(est, station_to_join, HasBit(p2, 5), roadstop_area, &st, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST);
1818 if (ret.Failed()) return ret;
1820 /* Check if this number of road stops can be allocated. */
1821 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);
1823 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
1824 if (ret.Failed()) return ret;
1826 if (flags & DC_EXEC) {
1827 /* Check every tile in the area. */
1828 TILE_AREA_LOOP(cur_tile, roadstop_area) {
1829 RoadTypes cur_rts = (IsRoadTile(cur_tile) || IsStationTile(cur_tile)) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
1830 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
1831 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
1833 if (IsStationTile(cur_tile) && IsRoadStop(cur_tile)) {
1834 RemoveRoadStop(cur_tile, flags);
1837 RoadStop *road_stop = new RoadStop(cur_tile);
1838 /* Insert into linked list of RoadStops. */
1839 RoadStop **currstop = FindRoadStopSpot(type, st);
1840 *currstop = road_stop;
1842 if (type) {
1843 st->truck_station.Add(cur_tile);
1844 } else {
1845 st->bus_station.Add(cur_tile);
1848 /* Initialize an empty station. */
1849 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
1851 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
1853 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
1854 if (is_drive_through) {
1855 /* Update company infrastructure counts. If the current tile is a normal
1856 * road tile, count only the new road bits needed to get a full diagonal road. */
1857 RoadType rt;
1858 FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
1859 Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
1860 if (c != NULL) {
1861 c->infrastructure.road[rt] += 2 - (IsRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
1862 DirtyCompanyInfrastructureWindows(c->index);
1866 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
1867 road_stop->MakeDriveThrough();
1868 } else {
1869 /* Non-drive-through stop never overbuild and always count as two road bits. */
1870 Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
1871 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
1873 Company::Get(st->owner)->infrastructure.station++;
1874 DirtyCompanyInfrastructureWindows(st->owner);
1876 MarkTileDirtyByTile(cur_tile);
1880 if (st != NULL) {
1881 st->UpdateVirtCoord();
1882 UpdateStationAcceptance(st, false);
1883 st->RecomputeIndustriesNear();
1884 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
1885 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
1886 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
1888 return cost;
1893 * Remove a bus station/truck stop
1894 * @param tile TileIndex been queried
1895 * @param flags operation to perform
1896 * @return cost or failure of operation
1898 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
1900 Station *st = Station::GetByTile(tile);
1902 if (_current_company != OWNER_WATER) {
1903 CommandCost ret = CheckOwnership(st->owner);
1904 if (ret.Failed()) return ret;
1907 bool is_truck = IsTruckStop(tile);
1909 RoadStop **primary_stop;
1910 RoadStop *cur_stop;
1911 if (is_truck) { // truck stop
1912 primary_stop = &st->truck_stops;
1913 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
1914 } else {
1915 primary_stop = &st->bus_stops;
1916 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
1919 assert(cur_stop != NULL);
1921 /* don't do the check for drive-through road stops when company bankrupts */
1922 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
1923 /* remove the 'going through road stop' status from all vehicles on that tile */
1924 VehicleTileIterator iter (tile);
1925 while (!iter.finished()) {
1926 Vehicle *v = iter.next();
1927 if (v->type == VEH_ROAD) {
1928 /* Okay... we are a road vehicle on a drive through road stop.
1929 * But that road stop has just been removed, so we need to make
1930 * sure we are in a valid state... however, vehicles can also
1931 * turn on road stop tiles, so only clear the 'road stop' state
1932 * bits and only when the state was 'in road stop', otherwise
1933 * we'll end up clearing the turn around bits. */
1934 RoadVehicle *rv = RoadVehicle::From(v);
1935 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
1938 } else {
1939 CommandCost ret = EnsureNoVehicleOnGround(tile);
1940 if (ret.Failed()) return ret;
1943 if (flags & DC_EXEC) {
1944 if (*primary_stop == cur_stop) {
1945 /* removed the first stop in the list */
1946 *primary_stop = cur_stop->next;
1947 /* removed the only stop? */
1948 if (*primary_stop == NULL) {
1949 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
1951 } else {
1952 /* tell the predecessor in the list to skip this stop */
1953 RoadStop *pred = *primary_stop;
1954 while (pred->next != cur_stop) pred = pred->next;
1955 pred->next = cur_stop->next;
1958 /* Update company infrastructure counts. */
1959 RoadType rt;
1960 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
1961 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
1962 if (c != NULL) {
1963 c->infrastructure.road[rt] -= 2;
1964 DirtyCompanyInfrastructureWindows(c->index);
1967 Company::Get(st->owner)->infrastructure.station--;
1969 if (IsDriveThroughStopTile(tile)) {
1970 /* Clears the tile for us */
1971 cur_stop->ClearDriveThrough();
1972 } else {
1973 DoClearSquare(tile);
1976 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
1977 delete cur_stop;
1979 /* Make sure no vehicle is going to the old roadstop */
1980 RoadVehicle *v;
1981 FOR_ALL_ROADVEHICLES(v) {
1982 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
1983 v->dest_tile == tile) {
1984 v->dest_tile = v->GetOrderStationLocation(st->index);
1988 st->rect.AfterRemoveTile(st, tile);
1990 st->UpdateVirtCoord();
1991 st->RecomputeIndustriesNear();
1992 DeleteStationIfEmpty(st);
1994 /* Update the tile area of the truck/bus stop */
1995 if (is_truck) {
1996 st->truck_station.Clear();
1997 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
1998 } else {
1999 st->bus_station.Clear();
2000 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
2004 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
2008 * Remove bus or truck stops.
2009 * @param tile Northernmost tile of the removal area.
2010 * @param flags Operation to perform.
2011 * @param p1 bit 0..7: Width of the removal area.
2012 * bit 8..15: Height of the removal area.
2013 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
2014 * @param text Unused.
2015 * @return The cost of this operation or an error.
2017 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2019 uint8 width = (uint8)GB(p1, 0, 8);
2020 uint8 height = (uint8)GB(p1, 8, 8);
2022 /* Check for incorrect width / height. */
2023 if (width == 0 || height == 0) return CMD_ERROR;
2024 /* Check if the first tile and the last tile are valid */
2025 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2027 TileArea roadstop_area(tile, width, height);
2029 int quantity = 0;
2030 CommandCost cost(EXPENSES_CONSTRUCTION);
2031 TILE_AREA_LOOP(cur_tile, roadstop_area) {
2032 /* Make sure the specified tile is a road stop of the correct type */
2033 if (!IsStationTile(cur_tile) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
2035 /* Save the stop info before it is removed */
2036 bool is_drive_through = IsDriveThroughStopTile(cur_tile);
2037 RoadTypes rts = GetRoadTypes(cur_tile);
2038 RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
2039 AxisToRoadBits(GetRoadStopAxis(cur_tile)) :
2040 DiagDirToRoadBits(GetRoadStopDir(cur_tile));
2042 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
2043 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
2044 CommandCost ret = RemoveRoadStop(cur_tile, flags);
2045 if (ret.Failed()) return ret;
2046 cost.AddCost(ret);
2048 quantity++;
2049 /* If the stop was a drive-through stop replace the road */
2050 if ((flags & DC_EXEC) && is_drive_through) {
2051 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2052 road_owner, tram_owner);
2054 /* Update company infrastructure counts. */
2055 RoadType rt;
2056 FOR_EACH_SET_ROADTYPE(rt, rts) {
2057 Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
2058 if (c != NULL) {
2059 c->infrastructure.road[rt] += CountBits(road_bits);
2060 DirtyCompanyInfrastructureWindows(c->index);
2066 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
2068 return cost;
2072 * Computes the minimal distance from town's xy to any airport's tile.
2073 * @param it An iterator over all airport tiles.
2074 * @param town_tile town's tile (t->xy)
2075 * @return minimal manhattan distance from town_tile to any airport's tile
2077 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
2079 uint mindist = UINT_MAX;
2081 for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2082 mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
2085 return mindist;
2089 * Get a possible noise reduction factor based on distance from town center.
2090 * The further you get, the less noise you generate.
2091 * So all those folks at city council can now happily slee... work in their offices
2092 * @param as airport information
2093 * @param it An iterator over all airport tiles.
2094 * @param town_tile TileIndex of town's center, the one who will receive the airport's candidature
2095 * @return the noise that will be generated, according to distance
2097 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
2099 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2100 * So no need to go any further*/
2101 if (as->noise_level < 2) return as->noise_level;
2103 uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
2105 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2106 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2107 * Basically, it says that the less tolerant a town is, the bigger the distance before
2108 * an actual decrease can be granted */
2109 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2111 /* now, we want to have the distance segmented using the distance judged bareable by town
2112 * This will give us the coefficient of reduction the distance provides. */
2113 uint noise_reduction = distance / town_tolerance_distance;
2115 /* If the noise reduction equals the airport noise itself, don't give it for free.
2116 * Otherwise, simply reduce the airport's level. */
2117 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2121 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2122 * If two towns have the same distance, town with lower index is returned.
2123 * @param as airport's description
2124 * @param it An iterator over all airport tiles
2125 * @return nearest town to airport
2127 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
2129 Town *t, *nearest = NULL;
2130 uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2131 uint mindist = UINT_MAX - add; // prevent overflow
2132 FOR_ALL_TOWNS(t) {
2133 if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
2134 TileIterator *copy = it.Clone();
2135 uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
2136 delete copy;
2137 if (dist < mindist) {
2138 nearest = t;
2139 mindist = dist;
2144 return nearest;
2148 /** Recalculate the noise generated by the airports of each town */
2149 void UpdateAirportsNoise()
2151 Town *t;
2152 const Station *st;
2154 FOR_ALL_TOWNS(t) t->noise_reached = 0;
2156 FOR_ALL_STATIONS(st) {
2157 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2158 const AirportSpec *as = st->airport.GetSpec();
2159 AirportTileIterator it(st);
2160 Town *nearest = AirportGetNearestTown(as, it);
2161 nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
2168 * Checks if an airport can be removed (no aircraft on it or landing)
2169 * @param st Station whose airport is to be removed
2170 * @param flags Operation to perform
2171 * @return Cost or failure of operation
2173 static CommandCost CanRemoveAirport(Station *st, DoCommandFlag flags)
2175 const Aircraft *a;
2176 FOR_ALL_AIRCRAFT(a) {
2177 if (!a->IsNormalAircraft()) continue;
2178 if (a->targetairport == st->index && a->state != FLYING)
2179 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2182 CommandCost cost(EXPENSES_CONSTRUCTION);
2184 TILE_AREA_LOOP(tile_cur, st->airport) {
2185 if (!st->TileBelongsToAirport(tile_cur)) continue;
2187 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2188 if (ret.Failed()) return ret;
2190 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2193 return cost;
2198 * Place an Airport.
2199 * @param tile tile where airport will be built
2200 * @param flags operation to perform
2201 * @param p1
2202 * - p1 = (bit 0- 7) - airport type, @see airport.h
2203 * - p1 = (bit 8-15) - airport layout
2204 * @param p2 various bitstuffed elements
2205 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2206 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2207 * @param text unused
2208 * @return the cost of this operation or an error
2210 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2212 StationID station_to_join = GB(p2, 16, 16);
2213 bool reuse = (station_to_join != NEW_STATION);
2214 if (!reuse) station_to_join = INVALID_STATION;
2215 bool distant_join = (station_to_join != INVALID_STATION);
2216 byte airport_type = GB(p1, 0, 8);
2217 byte layout = GB(p1, 8, 8);
2219 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2221 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2223 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2224 if (ret.Failed()) return ret;
2226 /* Check if a valid, buildable airport was chosen for construction */
2227 const AirportSpec *as = AirportSpec::Get(airport_type);
2228 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
2230 Direction rotation = as->rotation[layout];
2231 int w = as->size_x;
2232 int h = as->size_y;
2233 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2234 TileArea airport_area = TileArea(tile, w, h);
2236 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2237 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2240 StationID est = INVALID_STATION;
2241 CommandCost cost = CheckFlatLandAirport(airport_area, flags, &est);
2242 if (cost.Failed()) return cost;
2244 Station *st = NULL;
2245 ret = FindJoiningStation(est, station_to_join, HasBit(p2, 0), airport_area, &st, STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
2246 if (ret.Failed()) return ret;
2248 /* Distant join */
2249 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
2251 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2252 if (ret.Failed()) return ret;
2254 /* action to be performed */
2255 enum {
2256 AIRPORT_NEW, // airport is a new station
2257 AIRPORT_ADD, // add an airport to an existing station
2258 AIRPORT_UPGRADE, // upgrade the airport in a station
2259 } action =
2260 (est != INVALID_STATION) ? AIRPORT_UPGRADE :
2261 (st != NULL) ? AIRPORT_ADD : AIRPORT_NEW;
2263 if (action == AIRPORT_ADD && st->airport.tile != INVALID_TILE) {
2264 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2267 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2268 AirportTileTableIterator iter(as->table[layout], tile);
2269 Town *nearest = AirportGetNearestTown(as, iter);
2270 uint newnoise_level = nearest->noise_reached + GetAirportNoiseLevelForTown(as, iter, nearest->xy);
2272 if (action == AIRPORT_UPGRADE) {
2273 const AirportSpec *old_as = st->airport.GetSpec();
2274 AirportTileTableIterator old_iter(old_as->table[st->airport.layout], st->airport.tile);
2275 Town *old_nearest = AirportGetNearestTown(old_as, old_iter);
2276 if (old_nearest == nearest) {
2277 newnoise_level -= GetAirportNoiseLevelForTown(old_as, old_iter, nearest->xy);
2281 /* Check if local auth would allow a new airport */
2282 StringID authority_refuse_message = STR_NULL;
2283 Town *authority_refuse_town = NULL;
2285 if (_settings_game.economy.station_noise_level) {
2286 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2287 if (newnoise_level > nearest->MaxTownNoise()) {
2288 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2289 authority_refuse_town = nearest;
2291 } else if (action != AIRPORT_UPGRADE) {
2292 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2293 uint num = 0;
2294 const Station *st;
2295 FOR_ALL_STATIONS(st) {
2296 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2298 if (num >= 2) {
2299 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2300 authority_refuse_town = t;
2304 if (authority_refuse_message != STR_NULL) {
2305 SetDParam(0, authority_refuse_town->index);
2306 return_cmd_error(authority_refuse_message);
2309 if (action == AIRPORT_UPGRADE) {
2310 /* check that the old airport can be removed */
2311 CommandCost r = CanRemoveAirport(st, flags);
2312 if (r.Failed()) return r;
2313 cost.AddCost(r);
2316 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2317 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2320 if (flags & DC_EXEC) {
2321 if (action == AIRPORT_UPGRADE) {
2322 /* delete old airport if upgrading */
2323 const AirportSpec *old_as = st->airport.GetSpec();
2324 AirportTileTableIterator old_iter(old_as->table[st->airport.layout], st->airport.tile);
2325 Town *old_nearest = AirportGetNearestTown(old_as, old_iter);
2327 if (old_nearest != nearest) {
2328 old_nearest->noise_reached -= GetAirportNoiseLevelForTown(old_as, old_iter, old_nearest->xy);
2329 if (_settings_game.economy.station_noise_level) {
2330 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2334 TILE_AREA_LOOP(tile_cur, st->airport) {
2335 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
2336 DeleteAnimatedTile(tile_cur);
2337 DoClearSquare(tile_cur);
2338 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2341 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2342 DeleteWindowById(
2343 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
2347 st->rect.AfterRemoveRect(st, st->airport);
2348 st->airport.Clear();
2351 /* Always add the noise, so there will be no need to recalculate when option toggles */
2352 nearest->noise_reached = newnoise_level;
2354 st->AddFacility(FACIL_AIRPORT, tile);
2355 st->airport.type = airport_type;
2356 st->airport.layout = layout;
2357 st->airport.flags = 0;
2358 st->airport.rotation = rotation;
2360 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2362 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2363 MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2364 SetStationTileRandomBits(iter, GB(Random(), 0, 4));
2365 st->airport.Add(iter);
2367 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
2370 /* Only call the animation trigger after all tiles have been built */
2371 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2372 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2375 if (action != AIRPORT_NEW) UpdateAirplanesOnNewStation(st);
2377 if (action == AIRPORT_UPGRADE) {
2378 UpdateStationSignCoord(st);
2379 } else {
2380 Company::Get(st->owner)->infrastructure.airport++;
2381 DirtyCompanyInfrastructureWindows(st->owner);
2382 st->UpdateVirtCoord();
2385 UpdateStationAcceptance(st, false);
2386 st->RecomputeIndustriesNear();
2387 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
2388 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
2389 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2391 if (_settings_game.economy.station_noise_level) {
2392 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2396 return cost;
2400 * Remove an airport
2401 * @param tile TileIndex been queried
2402 * @param flags operation to perform
2403 * @return cost or failure of operation
2405 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2407 Station *st = Station::GetByTile(tile);
2409 if (_current_company != OWNER_WATER) {
2410 CommandCost ret = CheckOwnership(st->owner);
2411 if (ret.Failed()) return ret;
2414 CommandCost cost = CanRemoveAirport(st, flags);
2415 if (cost.Failed()) return cost;
2417 if (flags & DC_EXEC) {
2418 const AirportSpec *as = st->airport.GetSpec();
2419 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2420 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2421 * need of recalculation */
2422 AirportTileIterator it(st);
2423 Town *nearest = AirportGetNearestTown(as, it);
2424 nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
2426 TILE_AREA_LOOP(tile_cur, st->airport) {
2427 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
2428 DeleteAnimatedTile(tile_cur);
2429 DoClearSquare(tile_cur);
2430 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2433 /* Clear the persistent storage. */
2434 delete st->airport.psa;
2436 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2437 DeleteWindowById(
2438 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
2442 st->rect.AfterRemoveRect(st, st->airport);
2444 st->airport.Clear();
2445 st->facilities &= ~FACIL_AIRPORT;
2447 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2449 if (_settings_game.economy.station_noise_level) {
2450 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2453 Company::Get(st->owner)->infrastructure.airport--;
2454 DirtyCompanyInfrastructureWindows(st->owner);
2456 st->UpdateVirtCoord();
2457 st->RecomputeIndustriesNear();
2458 DeleteStationIfEmpty(st);
2459 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2462 return cost;
2466 * Open/close an airport to incoming aircraft.
2467 * @param tile Unused.
2468 * @param flags Operation to perform.
2469 * @param p1 Station ID of the airport.
2470 * @param p2 Unused.
2471 * @param text unused
2472 * @return the cost of this operation or an error
2474 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2476 if (!Station::IsValidID(p1)) return CMD_ERROR;
2477 Station *st = Station::Get(p1);
2479 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2481 CommandCost ret = CheckOwnership(st->owner);
2482 if (ret.Failed()) return ret;
2484 if (flags & DC_EXEC) {
2485 st->airport.flags ^= AIRPORT_CLOSED_block;
2486 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2488 return CommandCost();
2492 * Tests whether the company's vehicles have this station in orders
2493 * @param station station ID
2494 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2495 * @param company company ID
2497 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2499 const Vehicle *v;
2500 FOR_ALL_VEHICLES(v) {
2501 if ((v->owner == company) == include_company) {
2502 const Order *order;
2503 FOR_VEHICLE_ORDERS(v, order) {
2504 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
2505 return true;
2510 return false;
2513 /** Information about dock tile area for a given direction. */
2514 struct DockTileArea {
2515 CoordDiff offset; ///< offset to northern tile
2516 byte width; ///< width of dock area
2517 byte height; ///< height of dock area
2521 * Build a dock/haven.
2522 * @param tile tile where dock will be built
2523 * @param flags operation to perform
2524 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
2525 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
2526 * @param text unused
2527 * @return the cost of this operation or an error
2529 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2531 static const DockTileArea dock_tilearea[DIAGDIR_END] = {
2532 { { -1, 0 }, 2, 1 },
2533 { { 0, 0 }, 1, 2 },
2534 { { 0, 0 }, 2, 1 },
2535 { { 0, -1 }, 1, 2 },
2538 StationID station_to_join = GB(p2, 16, 16);
2539 bool reuse = (station_to_join != NEW_STATION);
2540 if (!reuse) station_to_join = INVALID_STATION;
2541 bool distant_join = (station_to_join != INVALID_STATION);
2543 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2545 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
2546 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2547 direction = ReverseDiagDir(direction);
2549 /* Docks cannot be placed on rapids */
2550 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2552 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2553 if (ret.Failed()) return ret;
2555 if (HasBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2557 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2558 if (ret.Failed()) return ret;
2560 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2562 if (!IsWaterTile(tile_cur) || !IsTileFlat(tile_cur)) {
2563 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2566 if (HasBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2568 /* Get the water class of the water tile before it is cleared.*/
2569 WaterClass wc = GetWaterClass(tile_cur);
2571 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2572 if (ret.Failed()) return ret;
2574 tile_cur += TileOffsByDiagDir(direction);
2575 if (!IsWaterTile(tile_cur) || !IsTileFlat(tile_cur)) {
2576 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2579 TileArea dock_area = TileArea(tile + ToTileIndexDiff(dock_tilearea[direction].offset),
2580 dock_tilearea[direction].width, dock_tilearea[direction].height);
2582 /* middle */
2583 Station *st = NULL;
2584 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
2585 if (ret.Failed()) return ret;
2587 /* Distant join */
2588 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
2590 /* Check if we can allocate a new dock. */
2591 if (!Dock::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_DOCKS);
2593 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2594 if (ret.Failed()) return ret;
2596 if (flags & DC_EXEC) {
2597 Dock **dl = &st->docks;
2598 while (*dl != NULL) dl = &(*dl)->next;
2600 *dl = new Dock(tile);
2601 st->dock_area.Add(dock_area);
2603 st->AddFacility(FACIL_DOCK, tile);
2605 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2607 /* If the water part of the dock is on a canal, update infrastructure counts.
2608 * This is needed as we've unconditionally cleared that tile before. */
2609 if (wc == WATER_CLASS_CANAL) {
2610 Company::Get(st->owner)->infrastructure.water++;
2612 Company::Get(st->owner)->infrastructure.station += 2;
2613 DirtyCompanyInfrastructureWindows(st->owner);
2615 MakeDock(tile, st->owner, st->index, direction, wc);
2617 st->UpdateVirtCoord();
2618 UpdateStationAcceptance(st, false);
2619 st->RecomputeIndustriesNear();
2620 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
2621 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
2622 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
2625 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2629 * Remove a dock
2630 * @param tile TileIndex been queried
2631 * @param flags operation to perform
2632 * @return cost or failure of operation
2634 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2636 assert(IsDock(tile));
2638 Station *st = Station::GetByTile(tile);
2639 CommandCost ret = CheckOwnership(st->owner);
2640 if (ret.Failed()) return ret;
2642 Dock **d = &st->docks;
2643 TileIndex tile1, tile2;
2644 while ( tile1 = (*d)->xy, tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1)),
2645 tile != tile1 && tile != tile2 ) {
2646 /* the dock should really be there, so no check for NULL */
2647 d = &(*d)->next;
2650 ret = EnsureNoVehicleOnGround(tile1);
2651 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2652 if (ret.Failed()) return ret;
2654 if (flags & DC_EXEC) {
2655 TileIndex docking_location = GetDockingTile(tile1);
2657 DoClearSquare(tile1);
2658 MarkTileDirtyByTile(tile1);
2659 MakeWaterKeepingClass(tile2, st->owner);
2661 st->rect.AfterRemoveTile(st, tile1);
2662 st->rect.AfterRemoveTile(st, tile2);
2664 Dock *next = (*d)->next;
2665 delete *d;
2666 *d = next;
2667 if (next == NULL && d == &st->docks) st->facilities &= ~FACIL_DOCK;
2669 Company::Get(st->owner)->infrastructure.station -= 2;
2670 DirtyCompanyInfrastructureWindows(st->owner);
2672 /* Update the tile area of the docks */
2673 st->dock_area.Clear();
2674 for (const Dock *dock = st->docks; dock != NULL; dock = dock->next) {
2675 st->dock_area.Add(dock->xy);
2676 st->dock_area.Add(dock->xy + TileOffsByDiagDir(GetDockDirection(dock->xy)));
2679 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
2680 st->UpdateVirtCoord();
2681 st->RecomputeIndustriesNear();
2682 DeleteStationIfEmpty(st);
2684 /* All ships that were going to our station, can't go to it anymore.
2685 * Just clear the order, then automatically the next appropriate order
2686 * will be selected and in case of no appropriate order it will just
2687 * wander around the world. */
2688 Ship *s;
2689 FOR_ALL_SHIPS(s) {
2690 if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
2691 s->LeaveStation();
2694 if (s->dest_tile == docking_location) {
2695 s->dest_tile = 0;
2696 s->current_order.Free();
2701 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
2704 #include "table/station_land.h"
2706 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
2708 return &_station_display_datas[st][gfx];
2712 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
2713 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
2714 * is set to the overlay to draw.
2715 * @param ti Positional info for the tile to decide snowyness etc. May be NULL.
2716 * @param [in,out] ground Groundsprite to draw.
2717 * @param [out] overlay_offset Overlay to draw.
2718 * @return true if overlay can be drawn.
2720 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
2722 bool snow_desert;
2723 switch (*ground) {
2724 case SPR_RAIL_TRACK_X:
2725 snow_desert = false;
2726 *overlay_offset = RTO_X;
2727 break;
2729 case SPR_RAIL_TRACK_Y:
2730 snow_desert = false;
2731 *overlay_offset = RTO_Y;
2732 break;
2734 case SPR_RAIL_TRACK_X_SNOW:
2735 snow_desert = true;
2736 *overlay_offset = RTO_X;
2737 break;
2739 case SPR_RAIL_TRACK_Y_SNOW:
2740 snow_desert = true;
2741 *overlay_offset = RTO_Y;
2742 break;
2744 default:
2745 return false;
2748 if (ti != NULL) {
2749 /* Decide snow/desert from tile */
2750 switch (_settings_game.game_creation.landscape) {
2751 case LT_ARCTIC:
2752 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
2753 break;
2755 case LT_TROPIC:
2756 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
2757 break;
2759 default:
2760 break;
2764 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
2765 return true;
2768 static void DrawTile_Station(TileInfo *ti)
2770 const NewGRFSpriteLayout *layout = NULL;
2771 DrawTileSprites tmp_rail_layout;
2772 const DrawTileSprites *t = NULL;
2773 RoadTypes roadtypes;
2774 int32 total_offset;
2775 const RailtypeInfo *rti = NULL;
2776 uint32 relocation = 0;
2777 uint32 ground_relocation = 0;
2778 BaseStation *st = NULL;
2779 const StationSpec *statspec = NULL;
2780 uint tile_layout = 0;
2782 if (HasStationRail(ti->tile)) {
2783 rti = GetRailTypeInfo(GetRailType(ti->tile));
2784 roadtypes = ROADTYPES_NONE;
2785 total_offset = rti->GetRailtypeSpriteOffset();
2787 if (IsCustomStationSpecIndex(ti->tile)) {
2788 /* look for customization */
2789 st = BaseStation::GetByTile(ti->tile);
2790 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
2792 if (statspec != NULL) {
2793 tile_layout = GetStationGfx(ti->tile);
2795 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
2796 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
2797 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
2800 /* Ensure the chosen tile layout is valid for this custom station */
2801 if (statspec->renderdata != NULL) {
2802 layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
2803 if (!layout->NeedsPreprocessing()) {
2804 t = layout;
2805 layout = NULL;
2810 } else {
2811 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
2812 total_offset = 0;
2815 StationGfx gfx = GetStationGfx(ti->tile);
2816 if (IsAirport(ti->tile)) {
2817 gfx = GetAirportGfx(ti->tile);
2818 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
2819 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
2820 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
2821 return;
2823 /* No sprite group (or no valid one) found, meaning no graphics associated.
2824 * Use the substitute one instead */
2825 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
2826 gfx = ats->grf_prop.subst_id;
2828 switch (gfx) {
2829 case APT_RADAR_GRASS_FENCE_SW:
2830 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
2831 break;
2832 case APT_GRASS_FENCE_NE_FLAG:
2833 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
2834 break;
2835 case APT_RADAR_FENCE_SW:
2836 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
2837 break;
2838 case APT_RADAR_FENCE_NE:
2839 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
2840 break;
2841 case APT_GRASS_FENCE_NE_FLAG_2:
2842 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
2843 break;
2847 Owner owner = GetTileOwner(ti->tile);
2849 PaletteID palette;
2850 if (Company::IsValidID(owner)) {
2851 palette = COMPANY_SPRITE_COLOUR(owner);
2852 } else {
2853 /* Some stations are not owner by a company, namely oil rigs */
2854 palette = PALETTE_TO_GREY;
2857 if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
2859 /* don't show foundation for docks */
2860 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
2861 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
2862 /* Station has custom foundations.
2863 * Check whether the foundation continues beyond the tile's upper sides. */
2864 uint edge_info = 0;
2865 int z;
2866 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
2867 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
2868 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
2869 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
2870 if (image == 0) goto draw_default_foundation;
2872 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
2873 /* Station provides extended foundations. */
2875 static const uint8 foundation_parts[] = {
2876 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2877 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2878 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2879 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2882 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2883 } else {
2884 /* Draw simple foundations, built up from 8 possible foundation sprites. */
2886 /* Each set bit represents one of the eight composite sprites to be drawn.
2887 * 'Invalid' entries will not drawn but are included for completeness. */
2888 static const uint8 composite_foundation_parts[] = {
2889 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2890 0x00, 0xD1, 0xE4, 0xE0,
2891 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2892 0xCA, 0xC9, 0xC4, 0xC0,
2893 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2894 0xD2, 0x91, 0xE4, 0xA0,
2895 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2896 0x4A, 0x09, 0x44
2899 uint8 parts = composite_foundation_parts[ti->tileh];
2901 /* If foundations continue beyond the tile's upper sides then
2902 * mask out the last two pieces. */
2903 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
2904 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
2906 if (parts == 0) {
2907 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2908 * correct offset for the childsprites.
2909 * So, draw the (completely empty) sprite of the default foundations. */
2910 goto draw_default_foundation;
2913 StartSpriteCombine();
2914 for (int i = 0; i < 8; i++) {
2915 if (HasBit(parts, i)) {
2916 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2919 EndSpriteCombine();
2922 OffsetGroundSprite(31, 1);
2923 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
2924 } else {
2925 draw_default_foundation:
2926 DrawFoundation(ti, FOUNDATION_LEVELED);
2930 if (IsBuoy(ti->tile)) {
2931 DrawWaterClassGround(ti);
2932 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
2933 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
2934 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
2935 if (ti->tileh == SLOPE_FLAT) {
2936 DrawWaterClassGround(ti);
2937 } else {
2938 assert(IsDock(ti->tile));
2939 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
2940 WaterClass wc = GetWaterClass(water_tile);
2941 if (wc == WATER_CLASS_SEA) {
2942 DrawShoreTile(ti->tileh);
2943 } else {
2944 DrawClearLandTile(ti, 3);
2947 } else {
2948 if (layout != NULL) {
2949 /* Sprite layout which needs preprocessing */
2950 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
2951 uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
2952 uint8 var10;
2953 FOR_EACH_SET_BIT(var10, var10_values) {
2954 uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
2955 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
2957 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
2958 t = &tmp_rail_layout;
2959 total_offset = 0;
2960 } else if (statspec != NULL) {
2961 /* Simple sprite layout */
2962 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
2963 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
2964 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
2966 ground_relocation += rti->fallback_railtype;
2969 SpriteID image = t->ground.sprite;
2970 PaletteID pal = t->ground.pal;
2971 RailTrackOffset overlay_offset;
2972 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
2973 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2974 DrawGroundSprite(image, PAL_NONE);
2975 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
2977 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
2978 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2979 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
2981 } else {
2982 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
2983 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
2984 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
2986 /* PBS debugging, draw reserved tracks darker */
2987 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
2988 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2989 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
2994 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
2996 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
2997 Axis axis = GetRoadStopAxis(ti->tile); // tram stops are always drive-through
2998 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
2999 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
3002 if (IsRailWaypoint(ti->tile)) {
3003 /* Don't offset the waypoint graphics; they're always the same. */
3004 total_offset = 0;
3007 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
3010 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3012 int32 total_offset = 0;
3013 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3014 const DrawTileSprites *t = GetStationTileLayout(st, image);
3015 const RailtypeInfo *rti = NULL;
3017 if (railtype != INVALID_RAILTYPE) {
3018 rti = GetRailTypeInfo(railtype);
3019 total_offset = rti->GetRailtypeSpriteOffset();
3022 SpriteID img = t->ground.sprite;
3023 RailTrackOffset overlay_offset;
3024 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
3025 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
3026 DrawSprite(img, PAL_NONE, x, y);
3027 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3028 } else {
3029 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3032 if (roadtype == ROADTYPE_TRAM) {
3033 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
3036 /* Default waypoint has no railtype specific sprites */
3037 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
3040 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
3042 return GetTileMaxPixelZ(tile);
3045 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
3047 return FlatteningFoundation(tileh);
3050 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3052 td->owner[0] = GetTileOwner(tile);
3053 if (IsDriveThroughStopTile(tile)) {
3054 Owner road_owner = INVALID_OWNER;
3055 Owner tram_owner = INVALID_OWNER;
3056 RoadTypes rts = GetRoadTypes(tile);
3057 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
3058 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
3060 /* Is there a mix of owners? */
3061 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3062 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3063 uint i = 1;
3064 if (road_owner != INVALID_OWNER) {
3065 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3066 td->owner[i] = road_owner;
3067 i++;
3069 if (tram_owner != INVALID_OWNER) {
3070 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3071 td->owner[i] = tram_owner;
3075 td->build_date = BaseStation::GetByTile(tile)->build_date;
3077 if (HasStationTileRail(tile)) {
3078 const StationSpec *spec = GetStationSpec(tile);
3080 if (spec != NULL) {
3081 td->station_class = StationClass::Get(spec->cls_id)->name;
3082 td->station_name = spec->name;
3084 if (spec->grf_prop.grffile != NULL) {
3085 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3086 td->grf = gc->GetName();
3090 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3091 td->rail_speed = rti->max_speed;
3094 if (IsAirport(tile)) {
3095 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3096 td->airport_class = AirportClass::Get(as->cls_id)->name;
3097 td->airport_name = as->name;
3099 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3100 td->airport_tile_name = ats->name;
3102 if (as->grf_prop.grffile != NULL) {
3103 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3104 td->grf = gc->GetName();
3105 } else if (ats->grf_prop.grffile != NULL) {
3106 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3107 td->grf = gc->GetName();
3111 StringID str;
3112 switch (GetStationType(tile)) {
3113 default: NOT_REACHED();
3114 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3115 case STATION_AIRPORT:
3116 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3117 break;
3118 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3119 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3120 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
3121 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3122 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3123 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3125 td->str = str;
3129 static TrackStatus GetTileRailwayStatus_Station(TileIndex tile, DiagDirection side)
3131 if (!HasStationRail(tile) || IsStationTileBlocked(tile)) return 0;
3133 return CombineTrackStatus(TrackBitsToTrackdirBits(GetRailStationTrackBits(tile)), TRACKDIR_BIT_NONE);
3136 static TrackStatus GetTileRoadStatus_Station(TileIndex tile, uint sub_mode, DiagDirection side)
3138 if (!IsRoadStop(tile) || (GetRoadTypes(tile) & sub_mode) == 0) return 0;
3140 TrackBits trackbits;
3142 if (IsStandardRoadStopTile(tile)) {
3143 DiagDirection dir = GetRoadStopDir(tile);
3145 if (side != INVALID_DIAGDIR && dir != side) return 0;
3147 trackbits = DiagDirToDiagTrackBits(dir);
3148 } else {
3149 Axis axis = GetRoadStopAxis(tile);
3151 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) return 0;
3153 trackbits = AxisToTrackBits(axis);
3156 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3159 static TrackdirBits GetTileWaterwayStatus_Station(TileIndex tile, DiagDirection side)
3161 if (!IsBuoy(tile)) return TRACKDIR_BIT_NONE;
3163 /* buoy is coded as a station, it is always on open water */
3164 TrackBits trackbits = TRACK_BIT_ALL;
3165 /* remove tracks that connect NE map edge */
3166 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3167 /* remove tracks that connect NW map edge */
3168 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3170 return TrackBitsToTrackdirBits(trackbits);
3174 static void TileLoop_Station(TileIndex tile)
3176 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3177 * hardcoded.....not good */
3178 switch (GetStationType(tile)) {
3179 case STATION_AIRPORT:
3180 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3181 break;
3183 case STATION_DOCK:
3184 if (!IsTileFlat(tile)) break; // only handle water part
3185 /* FALL THROUGH */
3186 case STATION_OILRIG: //(station part)
3187 case STATION_BUOY:
3188 TileLoop_Water(tile);
3189 break;
3191 default: break;
3196 static void AnimateTile_Station(TileIndex tile)
3198 if (HasStationRail(tile)) {
3199 AnimateStationTile(tile);
3200 return;
3203 if (IsAirport(tile)) {
3204 AnimateAirportTile(tile);
3209 static bool ClickTile_Station(TileIndex tile)
3211 const BaseStation *bst = BaseStation::GetByTile(tile);
3213 if (bst->facilities & FACIL_WAYPOINT) {
3214 ShowWaypointWindow(Waypoint::From(bst));
3215 } else if (IsHangar(tile)) {
3216 const Station *st = Station::From(bst);
3217 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3218 } else {
3219 ShowStationViewWindow(bst->index);
3221 return true;
3225 * Run the watched cargo callback for all houses in the catchment area.
3226 * @param st Station.
3228 void TriggerWatchedCargoCallbacks(Station *st)
3230 /* Collect cargoes accepted since the last big tick. */
3231 uint cargoes = 0;
3232 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3233 if (HasBit(st->goods[cid].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3236 /* Anything to do? */
3237 if (cargoes == 0) return;
3239 /* Loop over all houses in the catchment. */
3240 Rect r = st->GetCatchmentRect();
3241 TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
3242 TILE_AREA_LOOP(tile, ta) {
3243 if (IsHouseTile(tile)) {
3244 WatchedCargoCallback(tile, cargoes);
3250 * This function is called for each station once every 250 ticks.
3251 * Not all stations will get the tick at the same time.
3252 * @param st the station receiving the tick.
3253 * @return true if the station is still valid (wasn't deleted)
3255 static bool StationHandleBigTick(BaseStation *st)
3257 if (!st->IsInUse()) {
3258 if (++st->delete_ctr >= 8) delete st;
3259 return false;
3262 if (Station::IsExpected(st)) {
3263 TriggerWatchedCargoCallbacks(Station::From(st));
3265 for (CargoID i = 0; i < NUM_CARGO; i++) {
3266 ClrBit(Station::From(st)->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
3271 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3273 return true;
3276 static inline void byte_inc_sat(byte *p)
3278 byte b = *p + 1;
3279 if (b != 0) *p = b;
3282 static void UpdateStationRating(Station *st)
3284 bool waiting_changed = false;
3286 byte_inc_sat(&st->time_since_load);
3287 byte_inc_sat(&st->time_since_unload);
3289 const CargoSpec *cs;
3290 FOR_ALL_CARGOSPECS(cs) {
3291 GoodsEntry *ge = &st->goods[cs->Index()];
3292 /* Slowly increase the rating back to his original level in the case we
3293 * didn't deliver cargo yet to this station. This happens when a bribe
3294 * failed while you didn't moved that cargo yet to a station. */
3295 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3296 ge->rating++;
3299 /* Only change the rating if we are moving this cargo */
3300 if (ge->HasRating()) {
3301 byte_inc_sat(&ge->time_since_pickup);
3303 bool skip = false;
3304 int rating = 0;
3305 uint waiting = ge->cargo.TotalCount();
3307 /* num_dests is at least 1 if there is any cargo as
3308 * INVALID_STATION is also a destination.
3310 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3312 /* Average amount of cargo per next hop, but prefer solitary stations
3313 * with only one or two next hops. They are allowed to have more
3314 * cargo waiting per next hop.
3315 * With manual cargo distribution waiting_avg = waiting / 2 as then
3316 * INVALID_STATION is the only destination.
3318 uint waiting_avg = waiting / (num_dests + 1);
3320 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3321 /* Perform custom station rating. If it succeeds the speed, days in transit and
3322 * waiting cargo ratings must not be executed. */
3324 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3325 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3327 uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
3328 /* Convert to the 'old' vehicle types */
3329 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3330 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3331 if (callback != CALLBACK_FAILED) {
3332 skip = true;
3333 rating = GB(callback, 0, 14);
3335 /* Simulate a 15 bit signed value */
3336 if (HasBit(callback, 14)) rating -= 0x4000;
3340 if (!skip) {
3341 int b = ge->last_speed - 85;
3342 if (b >= 0) rating += b >> 2;
3344 byte waittime = ge->time_since_pickup;
3345 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3346 (waittime > 21) ||
3347 (rating += 25, waittime > 12) ||
3348 (rating += 25, waittime > 6) ||
3349 (rating += 45, waittime > 3) ||
3350 (rating += 35, true);
3352 (rating -= 90, ge->max_waiting_cargo > 1500) ||
3353 (rating += 55, ge->max_waiting_cargo > 1000) ||
3354 (rating += 35, ge->max_waiting_cargo > 600) ||
3355 (rating += 10, ge->max_waiting_cargo > 300) ||
3356 (rating += 20, ge->max_waiting_cargo > 100) ||
3357 (rating += 10, true);
3360 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3362 byte age = ge->last_age;
3363 (age >= 3) ||
3364 (rating += 10, age >= 2) ||
3365 (rating += 10, age >= 1) ||
3366 (rating += 13, true);
3369 int or_ = ge->rating; // old rating
3371 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3372 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
3374 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3375 * remove some random amount of goods from the station */
3376 if (rating <= 64 && waiting_avg >= 100) {
3377 int dec = Random() & 0x1F;
3378 if (waiting_avg < 200) dec &= 7;
3379 waiting -= (dec + 1) * num_dests;
3380 waiting_changed = true;
3383 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3384 if (rating <= 127 && waiting != 0) {
3385 uint32 r = Random();
3386 if (rating <= (int)GB(r, 0, 7)) {
3387 /* Need to have int, otherwise it will just overflow etc. */
3388 waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3389 waiting_changed = true;
3393 /* At some point we really must cap the cargo. Previously this
3394 * was a strict 4095, but now we'll have a less strict, but
3395 * increasingly aggressive truncation of the amount of cargo. */
3396 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3397 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3398 static const uint MAX_WAITING_CARGO = 1 << 15;
3400 if (waiting > WAITING_CARGO_THRESHOLD) {
3401 uint difference = waiting - WAITING_CARGO_THRESHOLD;
3402 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3404 waiting = min(waiting, MAX_WAITING_CARGO);
3405 waiting_changed = true;
3408 /* We can't truncate cargo that's already reserved for loading.
3409 * Thus StoredCount() here. */
3410 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3411 /* Feed back the exact own waiting cargo at this station for the
3412 * next rating calculation. */
3413 ge->max_waiting_cargo = 0;
3415 /* If truncating also punish the source stations' ratings to
3416 * decrease the flow of incoming cargo. */
3418 StationCargoAmountMap waiting_per_source;
3419 ge->cargo.Truncate(ge->cargo.AvailableCount() - waiting, &waiting_per_source);
3420 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3421 Station *source_station = Station::GetIfValid(i->first);
3422 if (source_station == NULL) continue;
3424 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3425 source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
3427 } else {
3428 /* If the average number per next hop is low, be more forgiving. */
3429 ge->max_waiting_cargo = waiting_avg;
3435 StationID index = st->index;
3436 if (waiting_changed) {
3437 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3438 } else {
3439 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3444 * Reroute cargo of type c at station st or in any vehicles unloading there.
3445 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3446 * @param st Station to be rerouted at.
3447 * @param c Type of cargo.
3448 * @param avoid Original next hop of cargo, avoid this.
3449 * @param avoid2 Another station to be avoided when rerouting.
3451 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
3453 GoodsEntry &ge = st->goods[c];
3455 /* Reroute cargo in station. */
3456 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
3458 /* Reroute cargo staged to be transfered. */
3459 for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
3460 for (Vehicle *v = *it; v != NULL; v = v->Next()) {
3461 if (v->cargo_type != c) continue;
3462 v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
3468 * Check all next hops of cargo packets in this station for existance of a
3469 * a valid link they may use to travel on. Reroute any cargo not having a valid
3470 * link and remove timed out links found like this from the linkgraph. We're
3471 * not all links here as that is expensive and useless. A link no one is using
3472 * doesn't hurt either.
3473 * @param from Station to check.
3475 void DeleteStaleLinks(Station *from)
3477 for (CargoID c = 0; c < NUM_CARGO; ++c) {
3478 GoodsEntry &ge = from->goods[c];
3479 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
3480 if (lg == NULL) continue;
3481 Node node = (*lg)[ge.node];
3482 for (EdgeIterator it(node.Begin()); it != node.End();) {
3483 Edge edge = it->second;
3484 Station *to = Station::Get((*lg)[it->first].Station());
3485 assert(to->goods[c].node == it->first);
3486 ++it; // Do that before removing the edge. Anything else may crash.
3487 assert(_date >= edge.LastUpdate());
3488 uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
3489 if ((uint)(_date - edge.LastUpdate()) > timeout) {
3490 /* Have all vehicles refresh their next hops before deciding to
3491 * remove the node. */
3492 bool updated = false;
3493 OrderList *l;
3494 FOR_ALL_ORDER_LISTS(l) {
3495 bool found_from = false;
3496 bool found_to = false;
3497 for (Order *order = l->GetFirstOrder(); order != NULL; order = order->next) {
3498 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
3499 if (order->GetDestination() == from->index) {
3500 found_from = true;
3501 if (found_to) break;
3502 } else if (order->GetDestination() == to->index) {
3503 found_to = true;
3504 if (found_from) break;
3507 if (!found_to || !found_from) continue;
3508 for (Vehicle *v = l->GetFirstSharedVehicle(); !updated && v != NULL; v = v->NextShared()) {
3509 /* There is potential for optimization here:
3510 * - Usually consists of the same order list are the same. It's probably better to
3511 * first check the first of each list, then the second of each list and so on.
3512 * - We could try to figure out if we've seen a consist with the same cargo on the
3513 * same list already and if the consist can actually carry the cargo we're looking
3514 * for. With conditional and refit orders this is not quite trivial, though. */
3515 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
3516 if (edge.LastUpdate() == _date) updated = true;
3518 if (updated) break;
3520 if (!updated) {
3521 /* If it's still considered dead remove it. */
3522 node.RemoveEdge(to->goods[c].node);
3523 ge.flows.DeleteFlows(to->index);
3524 RerouteCargo(from, c, to->index, from->index);
3526 } else if (edge.LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastUnrestrictedUpdate()) > timeout) {
3527 edge.Restrict();
3528 ge.flows.RestrictFlows(to->index);
3529 RerouteCargo(from, c, to->index, from->index);
3530 } else if (edge.LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastRestrictedUpdate()) > timeout) {
3531 edge.Release();
3534 assert(_date >= lg->LastCompression());
3535 if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
3536 lg->Compress();
3542 * Increase capacity for a link stat given by station cargo and next hop.
3543 * @param st Station to get the link stats from.
3544 * @param cargo Cargo to increase stat for.
3545 * @param next_station_id Station the consist will be travelling to next.
3546 * @param capacity Capacity to add to link stat.
3547 * @param usage Usage to add to link stat. If UINT_MAX refresh the link instead of increasing.
3549 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage)
3551 GoodsEntry &ge1 = st->goods[cargo];
3552 Station *st2 = Station::Get(next_station_id);
3553 GoodsEntry &ge2 = st2->goods[cargo];
3554 LinkGraph *lg = NULL;
3555 if (ge1.link_graph == INVALID_LINK_GRAPH) {
3556 if (ge2.link_graph == INVALID_LINK_GRAPH) {
3557 if (LinkGraph::CanAllocateItem()) {
3558 lg = new LinkGraph(cargo);
3559 LinkGraphSchedule::Instance()->Queue(lg);
3560 ge2.link_graph = lg->index;
3561 ge2.node = lg->AddNode(st2);
3562 } else {
3563 DEBUG(misc, 0, "Can't allocate link graph");
3565 } else {
3566 lg = LinkGraph::Get(ge2.link_graph);
3568 if (lg) {
3569 ge1.link_graph = lg->index;
3570 ge1.node = lg->AddNode(st);
3572 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
3573 lg = LinkGraph::Get(ge1.link_graph);
3574 ge2.link_graph = lg->index;
3575 ge2.node = lg->AddNode(st2);
3576 } else {
3577 lg = LinkGraph::Get(ge1.link_graph);
3578 if (ge1.link_graph != ge2.link_graph) {
3579 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
3580 if (lg->Size() < lg2->Size()) {
3581 LinkGraphSchedule::Instance()->Unqueue(lg);
3582 lg2->Merge(lg); // Updates GoodsEntries of lg
3583 lg = lg2;
3584 } else {
3585 LinkGraphSchedule::Instance()->Unqueue(lg2);
3586 lg->Merge(lg2); // Updates GoodsEntries of lg2
3590 if (lg != NULL) {
3591 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage);
3596 * Increase capacity for all link stats associated with vehicles in the given consist.
3597 * @param st Station to get the link stats from.
3598 * @param front First vehicle in the consist.
3599 * @param next_station_id Station the consist will be travelling to next.
3601 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
3603 for (const Vehicle *v = front; v != NULL; v = v->Next()) {
3604 if (v->refit_cap > 0) {
3605 /* The cargo count can indeed be higher than the refit_cap if
3606 * wagons have been auto-replaced and subsequently auto-
3607 * refitted to a higher capacity. The cargo gets redistributed
3608 * among the wagons in that case.
3609 * As usage is not such an important figure anyway we just
3610 * ignore the additional cargo then.*/
3611 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
3612 min(v->refit_cap, v->cargo.StoredCount()));
3617 /* called for every station each tick */
3618 static void StationHandleSmallTick(BaseStation *st)
3620 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
3622 byte b = st->delete_ctr + 1;
3623 if (b >= STATION_RATING_TICKS) b = 0;
3624 st->delete_ctr = b;
3626 if (b == 0) UpdateStationRating(Station::From(st));
3629 void OnTick_Station()
3631 if (_game_mode == GM_EDITOR) return;
3633 BaseStation *st;
3634 FOR_ALL_BASE_STATIONS(st) {
3635 StationHandleSmallTick(st);
3637 /* Clean up the link graph about once a week. */
3638 if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
3639 DeleteStaleLinks(Station::From(st));
3642 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3643 * Station index is included so that triggers are not all done
3644 * at the same time. */
3645 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
3646 /* Stop processing this station if it was deleted */
3647 if (!StationHandleBigTick(st)) continue;
3648 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
3649 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
3654 /** Monthly loop for stations. */
3655 void StationMonthlyLoop()
3657 Station *st;
3659 FOR_ALL_STATIONS(st) {
3660 for (CargoID i = 0; i < NUM_CARGO; i++) {
3661 GoodsEntry *ge = &st->goods[i];
3662 SB(ge->acceptance_pickup, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH, 1));
3663 ClrBit(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
3669 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
3671 Station *st;
3673 FOR_ALL_STATIONS(st) {
3674 if (st->owner == owner &&
3675 DistanceManhattan(tile, st->xy) <= radius) {
3676 for (CargoID i = 0; i < NUM_CARGO; i++) {
3677 GoodsEntry *ge = &st->goods[i];
3679 if (ge->acceptance_pickup != 0) {
3680 ge->rating = Clamp(ge->rating + amount, 0, 255);
3687 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
3689 /* We can't allocate a CargoPacket? Then don't do anything
3690 * at all; i.e. just discard the incoming cargo. */
3691 if (!CargoPacket::CanAllocateItem()) return 0;
3693 GoodsEntry &ge = st->goods[type];
3694 amount += ge.amount_fract;
3695 ge.amount_fract = GB(amount, 0, 8);
3697 amount >>= 8;
3698 /* No new "real" cargo item yet. */
3699 if (amount == 0) return 0;
3701 StationID next = ge.GetVia(st->index);
3702 ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
3703 LinkGraph *lg = NULL;
3704 if (ge.link_graph == INVALID_LINK_GRAPH) {
3705 if (LinkGraph::CanAllocateItem()) {
3706 lg = new LinkGraph(type);
3707 LinkGraphSchedule::Instance()->Queue(lg);
3708 ge.link_graph = lg->index;
3709 ge.node = lg->AddNode(st);
3710 } else {
3711 DEBUG(misc, 0, "Can't allocate link graph");
3713 } else {
3714 lg = LinkGraph::Get(ge.link_graph);
3716 if (lg != NULL) (*lg)[ge.node].UpdateSupply(amount);
3718 if (!ge.HasRating()) {
3719 InvalidateWindowData(WC_STATION_LIST, st->index);
3720 SetBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP);
3723 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
3724 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
3725 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
3727 SetWindowDirty(WC_STATION_VIEW, st->index);
3728 st->MarkTilesDirty(true);
3729 return amount;
3732 static bool IsUniqueStationName(const char *name)
3734 const Station *st;
3736 FOR_ALL_STATIONS(st) {
3737 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
3740 return true;
3744 * Rename a station
3745 * @param tile unused
3746 * @param flags operation to perform
3747 * @param p1 station ID that is to be renamed
3748 * @param p2 unused
3749 * @param text the new name or an empty string when resetting to the default
3750 * @return the cost of this operation or an error
3752 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3754 Station *st = Station::GetIfValid(p1);
3755 if (st == NULL) return CMD_ERROR;
3757 CommandCost ret = CheckOwnership(st->owner);
3758 if (ret.Failed()) return ret;
3760 bool reset = StrEmpty(text);
3762 if (!reset) {
3763 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
3764 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
3767 if (flags & DC_EXEC) {
3768 free(st->name);
3769 st->name = reset ? NULL : strdup(text);
3771 st->UpdateVirtCoord();
3772 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
3775 return CommandCost();
3779 * Find all stations around a rectangular producer (industry, house, headquarter, ...)
3781 * @param location The location/area of the producer
3782 * @param stations The list to store the stations in
3784 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
3786 /* area to search = producer plus station catchment radius */
3787 uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
3789 uint x = TileX(location.tile);
3790 uint y = TileY(location.tile);
3792 uint min_x = (x > max_rad) ? x - max_rad : 0;
3793 uint max_x = x + location.w + max_rad;
3794 uint min_y = (y > max_rad) ? y - max_rad : 0;
3795 uint max_y = y + location.h + max_rad;
3797 if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
3798 if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
3799 if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
3800 if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
3802 for (uint cy = min_y; cy < max_y; cy++) {
3803 for (uint cx = min_x; cx < max_x; cx++) {
3804 TileIndex cur_tile = TileXY(cx, cy);
3805 if (!IsStationTile(cur_tile)) continue;
3807 Station *st = Station::GetByTile(cur_tile);
3808 /* st can be NULL in case of waypoints */
3809 if (st == NULL) continue;
3811 if (_settings_game.station.modified_catchment) {
3812 int rad = st->GetCatchmentRadius();
3813 int rad_x = cx - x;
3814 int rad_y = cy - y;
3816 if (rad_x < -rad || rad_x >= rad + location.w) continue;
3817 if (rad_y < -rad || rad_y >= rad + location.h) continue;
3820 /* Insert the station in the set. This will fail if it has
3821 * already been added.
3823 stations->Include(st);
3829 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
3830 * @return pointer to a StationList containing all stations found
3832 const StationList *StationFinder::GetStations()
3834 if (this->tile != INVALID_TILE) {
3835 FindStationsAroundTiles(*this, &this->stations);
3836 this->tile = INVALID_TILE;
3838 return &this->stations;
3841 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
3843 /* Return if nothing to do. Also the rounding below fails for 0. */
3844 if (amount == 0) return 0;
3846 Station *st1 = NULL; // Station with best rating
3847 Station *st2 = NULL; // Second best station
3848 uint best_rating1 = 0; // rating of st1
3849 uint best_rating2 = 0; // rating of st2
3851 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
3852 Station *st = *st_iter;
3854 /* Is the station reserved exclusively for somebody else? */
3855 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
3857 if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
3859 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
3861 if (IsCargoInClass(type, CC_PASSENGERS)) {
3862 if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
3863 } else {
3864 if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
3867 /* This station can be used, add it to st1/st2 */
3868 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
3869 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
3870 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
3871 st2 = st; best_rating2 = st->goods[type].rating;
3875 /* no stations around at all? */
3876 if (st1 == NULL) return 0;
3878 /* From now we'll calculate with fractal cargo amounts.
3879 * First determine how much cargo we really have. */
3880 amount *= best_rating1 + 1;
3882 if (st2 == NULL) {
3883 /* only one station around */
3884 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
3887 /* several stations around, the best two (highest rating) are in st1 and st2 */
3888 assert(st1 != NULL);
3889 assert(st2 != NULL);
3890 assert(best_rating1 != 0 || best_rating2 != 0);
3892 /* Then determine the amount the worst station gets. We do it this way as the
3893 * best should get a bonus, which in this case is the rounding difference from
3894 * this calculation. In reality that will mean the bonus will be pretty low.
3895 * Nevertheless, the best station should always get the most cargo regardless
3896 * of rounding issues. */
3897 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
3898 assert(worst_cargo <= (amount - worst_cargo));
3900 /* And then send the cargo to the stations! */
3901 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
3902 /* These two UpdateStationWaiting's can't be in the statement as then the order
3903 * of execution would be undefined and that could cause desyncs with callbacks. */
3904 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
3907 void BuildOilRig(TileIndex tile)
3909 if (!Station::CanAllocateItem()) {
3910 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
3911 return;
3914 if (!Dock::CanAllocateItem()) {
3915 DEBUG(misc, 0, "Can't allocate dock for oilrig at 0x%X, reverting to oilrig only", tile);
3916 return;
3919 Station *st = new Station(tile);
3920 st->town = ClosestTownFromTile(tile, UINT_MAX);
3922 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
3924 assert(IsIndustryTile(tile));
3925 DeleteAnimatedTile(tile);
3926 MakeOilrig(tile, st->index, GetWaterClass(tile));
3928 st->owner = OWNER_NONE;
3929 st->docks = new Dock(tile);
3930 st->dock_area = TileArea(tile, 1, 1);
3931 st->airport.type = AT_OILRIG;
3932 st->airport.Add(tile);
3933 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
3934 st->build_date = _date;
3936 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
3938 st->UpdateVirtCoord();
3939 UpdateStationAcceptance(st, false);
3940 st->RecomputeIndustriesNear();
3943 void DeleteOilRig(TileIndex tile)
3945 Station *st = Station::GetByTile(tile);
3947 MakeWaterKeepingClass(tile, OWNER_NONE);
3949 delete st->docks;
3950 st->docks = NULL;
3951 st->dock_area.Clear();
3952 st->airport.Clear();
3953 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
3954 st->airport.flags = 0;
3956 st->rect.AfterRemoveTile(st, tile);
3958 st->UpdateVirtCoord();
3959 st->RecomputeIndustriesNear();
3960 if (!st->IsInUse()) delete st;
3963 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
3965 if (IsRoadStopTile(tile)) {
3966 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
3967 /* Update all roadtypes, no matter if they are present */
3968 if (GetRoadOwner(tile, rt) == old_owner) {
3969 if (HasTileRoadType(tile, rt)) {
3970 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
3971 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
3972 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
3974 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
3979 if (!IsTileOwner(tile, old_owner)) return;
3981 if (new_owner != INVALID_OWNER) {
3982 /* Update company infrastructure counts. Only do it here
3983 * if the new owner is valid as otherwise the clear
3984 * command will do it for us. No need to dirty windows
3985 * here, we'll redraw the whole screen anyway.*/
3986 Company *old_company = Company::Get(old_owner);
3987 Company *new_company = Company::Get(new_owner);
3989 /* Update counts for underlying infrastructure. */
3990 switch (GetStationType(tile)) {
3991 case STATION_RAIL:
3992 case STATION_WAYPOINT:
3993 if (!IsStationTileBlocked(tile)) {
3994 old_company->infrastructure.rail[GetRailType(tile)]--;
3995 new_company->infrastructure.rail[GetRailType(tile)]++;
3997 break;
3999 case STATION_BUS:
4000 case STATION_TRUCK:
4001 /* Road stops were already handled above. */
4002 break;
4004 case STATION_BUOY:
4005 case STATION_DOCK:
4006 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
4007 old_company->infrastructure.water--;
4008 new_company->infrastructure.water++;
4010 break;
4012 default:
4013 break;
4016 /* Update station tile count. */
4017 if (!IsBuoy(tile) && !IsAirport(tile)) {
4018 old_company->infrastructure.station--;
4019 new_company->infrastructure.station++;
4022 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4023 SetTileOwner(tile, new_owner);
4024 InvalidateWindowClassesData(WC_STATION_LIST, 0);
4025 } else {
4026 if (IsDriveThroughStopTile(tile)) {
4027 /* Remove the drive-through road stop */
4028 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
4029 assert(IsNormalRoadTile(tile));
4030 /* Change owner of tile and all roadtypes */
4031 ChangeTileOwner(tile, old_owner, new_owner);
4032 } else {
4033 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
4034 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4035 * Update owner of buoy if it was not removed (was in orders).
4036 * Do not update when owned by OWNER_WATER (sea and rivers). */
4037 if ((IsWaterTile(tile) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4043 * Check if a drive-through road stop tile can be cleared.
4044 * Road stops built on town-owned roads check the conditions
4045 * that would allow clearing of the original road.
4046 * @param tile road stop tile to check
4047 * @param flags command flags
4048 * @return true if the road can be cleared
4050 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
4052 /* Yeah... water can always remove stops, right? */
4053 if (_current_company == OWNER_WATER) return true;
4055 RoadTypes rts = GetRoadTypes(tile);
4056 if (HasBit(rts, ROADTYPE_TRAM)) {
4057 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
4058 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
4060 if (HasBit(rts, ROADTYPE_ROAD)) {
4061 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
4062 if (road_owner != OWNER_TOWN) {
4063 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
4064 } else {
4065 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
4069 return true;
4073 * Clear a single tile of a station.
4074 * @param tile The tile to clear.
4075 * @param flags The DoCommand flags related to the "command".
4076 * @return The cost, or error of clearing.
4078 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4080 if (flags & DC_AUTO) {
4081 switch (GetStationType(tile)) {
4082 default: break;
4083 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4084 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4085 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4086 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);
4087 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);
4088 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4089 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4090 case STATION_OILRIG:
4091 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4092 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4096 switch (GetStationType(tile)) {
4097 case STATION_RAIL: return RemoveRailStation(tile, flags);
4098 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4099 case STATION_AIRPORT: return RemoveAirport(tile, flags);
4100 case STATION_TRUCK:
4101 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4102 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4104 return RemoveRoadStop(tile, flags);
4105 case STATION_BUS:
4106 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4107 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4109 return RemoveRoadStop(tile, flags);
4110 case STATION_BUOY: return RemoveBuoy(tile, flags);
4111 case STATION_DOCK: return RemoveDock(tile, flags);
4112 default: break;
4115 return CMD_ERROR;
4118 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4120 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4121 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4122 * TTDP does not call it.
4124 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4125 switch (GetStationType(tile)) {
4126 case STATION_WAYPOINT:
4127 case STATION_RAIL: {
4128 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4129 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4130 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4131 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4134 case STATION_AIRPORT:
4135 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4137 case STATION_TRUCK:
4138 case STATION_BUS: {
4139 DiagDirection direction = GetRoadStopDir(tile);
4140 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4141 if (IsDriveThroughStopTile(tile)) {
4142 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4144 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4147 default: break;
4151 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
4155 * Get flow for a station.
4156 * @param st Station to get flow for.
4157 * @return Flow for st.
4159 uint FlowStat::GetShare(StationID st) const
4161 uint32 prev = 0;
4162 for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
4163 if (it->second == st) {
4164 return it->first - prev;
4165 } else {
4166 prev = it->first;
4169 return 0;
4173 * Get a station a package can be routed to, but exclude the given ones.
4174 * @param excluded StationID not to be selected.
4175 * @param excluded2 Another StationID not to be selected.
4176 * @return A station ID from the shares map.
4178 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4180 if (this->unrestricted == 0) return INVALID_STATION;
4181 assert(!this->shares.empty());
4182 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4183 assert(it != this->shares.end() && it->first <= this->unrestricted);
4184 if (it->second != excluded && it->second != excluded2) return it->second;
4186 /* We've hit one of the excluded stations.
4187 * Draw another share, from outside its range. */
4189 uint end = it->first;
4190 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4191 uint interval = end - begin;
4192 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4193 uint new_max = this->unrestricted - interval;
4194 uint rand = RandomRange(new_max);
4195 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4196 this->shares.upper_bound(rand + interval);
4197 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4198 if (it2->second != excluded && it2->second != excluded2) return it2->second;
4200 /* We've hit the second excluded station.
4201 * Same as before, only a bit more complicated. */
4203 uint end2 = it2->first;
4204 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4205 uint interval2 = end2 - begin2;
4206 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4207 new_max -= interval2;
4208 if (begin > begin2) {
4209 Swap(begin, begin2);
4210 Swap(end, end2);
4211 Swap(interval, interval2);
4213 rand = RandomRange(new_max);
4214 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4215 if (rand < begin) {
4216 it3 = this->shares.upper_bound(rand);
4217 } else if (rand < begin2 - interval) {
4218 it3 = this->shares.upper_bound(rand + interval);
4219 } else {
4220 it3 = this->shares.upper_bound(rand + interval + interval2);
4222 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4223 return it3->second;
4227 * Reduce all flows to minimum capacity so that they don't get in the way of
4228 * link usage statistics too much. Keep them around, though, to continue
4229 * routing any remaining cargo.
4231 void FlowStat::Invalidate()
4233 assert(!this->shares.empty());
4234 SharesMap new_shares;
4235 uint i = 0;
4236 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4237 new_shares[++i] = it->second;
4238 if (it->first == this->unrestricted) this->unrestricted = i;
4240 this->shares.swap(new_shares);
4241 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4245 * Change share for specified station. By specifing INT_MIN as parameter you
4246 * can erase a share. Newly added flows will be unrestricted.
4247 * @param st Next Hop to be removed.
4248 * @param flow Share to be added or removed.
4250 void FlowStat::ChangeShare(StationID st, int flow)
4252 /* We assert only before changing as afterwards the shares can actually
4253 * be empty. In that case the whole flow stat must be deleted then. */
4254 assert(!this->shares.empty());
4256 uint removed_shares = 0;
4257 uint added_shares = 0;
4258 uint last_share = 0;
4259 SharesMap new_shares;
4260 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4261 if (it->second == st) {
4262 if (flow < 0) {
4263 uint share = it->first - last_share;
4264 if (flow == INT_MIN || (uint)(-flow) >= share) {
4265 removed_shares += share;
4266 if (it->first <= this->unrestricted) this->unrestricted -= share;
4267 if (flow != INT_MIN) flow += share;
4268 last_share = it->first;
4269 continue; // remove the whole share
4271 removed_shares += (uint)(-flow);
4272 } else {
4273 added_shares += (uint)(flow);
4275 if (it->first <= this->unrestricted) this->unrestricted += flow;
4277 /* If we don't continue above the whole flow has been added or
4278 * removed. */
4279 flow = 0;
4281 new_shares[it->first + added_shares - removed_shares] = it->second;
4282 last_share = it->first;
4284 if (flow > 0) {
4285 new_shares[last_share + (uint)flow] = st;
4286 if (this->unrestricted < last_share) {
4287 this->ReleaseShare(st);
4288 } else {
4289 this->unrestricted += flow;
4292 this->shares.swap(new_shares);
4296 * Restrict a flow by moving it to the end of the map and decreasing the amount
4297 * of unrestricted flow.
4298 * @param st Station of flow to be restricted.
4300 void FlowStat::RestrictShare(StationID st)
4302 assert(!this->shares.empty());
4303 uint flow = 0;
4304 uint last_share = 0;
4305 SharesMap new_shares;
4306 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4307 if (flow == 0) {
4308 if (it->first > this->unrestricted) return; // Not present or already restricted.
4309 if (it->second == st) {
4310 flow = it->first - last_share;
4311 this->unrestricted -= flow;
4312 } else {
4313 new_shares[it->first] = it->second;
4315 } else {
4316 new_shares[it->first - flow] = it->second;
4318 last_share = it->first;
4320 if (flow == 0) return;
4321 new_shares[last_share + flow] = st;
4322 this->shares.swap(new_shares);
4323 assert(!this->shares.empty());
4327 * Release ("unrestrict") a flow by moving it to the begin of the map and
4328 * increasing the amount of unrestricted flow.
4329 * @param st Station of flow to be released.
4331 void FlowStat::ReleaseShare(StationID st)
4333 assert(!this->shares.empty());
4334 uint flow = 0;
4335 uint next_share = 0;
4336 bool found = false;
4337 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4338 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4339 if (found) {
4340 flow = next_share - it->first;
4341 this->unrestricted += flow;
4342 break;
4343 } else {
4344 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4345 if (it->second == st) found = true;
4347 next_share = it->first;
4349 if (flow == 0) return;
4350 SharesMap new_shares;
4351 new_shares[flow] = st;
4352 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4353 if (it->second != st) {
4354 new_shares[flow + it->first] = it->second;
4355 } else {
4356 flow = 0;
4359 this->shares.swap(new_shares);
4360 assert(!this->shares.empty());
4364 * Scale all shares from link graph's runtime to monthly values.
4365 * @param runtime Time the link graph has been running without compression.
4367 void FlowStat::ScaleToMonthly(uint runtime)
4369 SharesMap new_shares;
4370 uint share = 0;
4371 for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
4372 share = max(share + 1, i->first * 30 / runtime);
4373 new_shares[share] = i->second;
4374 if (this->unrestricted == i->first) this->unrestricted = share;
4376 this->shares.swap(new_shares);
4380 * Add some flow from "origin", going via "via".
4381 * @param origin Origin of the flow.
4382 * @param via Next hop.
4383 * @param flow Amount of flow to be added.
4385 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
4387 FlowStatMap::iterator origin_it = this->find(origin);
4388 if (origin_it == this->end()) {
4389 this->insert(std::make_pair(origin, FlowStat(via, flow)));
4390 } else {
4391 origin_it->second.ChangeShare(via, flow);
4392 assert(!origin_it->second.GetShares()->empty());
4397 * Pass on some flow, remembering it as invalid, for later subtraction from
4398 * locally consumed flow. This is necessary because we can't have negative
4399 * flows and we don't want to sort the flows before adding them up.
4400 * @param origin Origin of the flow.
4401 * @param via Next hop.
4402 * @param flow Amount of flow to be passed.
4404 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
4406 FlowStatMap::iterator prev_it = this->find(origin);
4407 if (prev_it == this->end()) {
4408 FlowStat fs(via, flow);
4409 fs.AppendShare(INVALID_STATION, flow);
4410 this->insert(std::make_pair(origin, fs));
4411 } else {
4412 prev_it->second.ChangeShare(via, flow);
4413 prev_it->second.ChangeShare(INVALID_STATION, flow);
4414 assert(!prev_it->second.GetShares()->empty());
4419 * Subtract invalid flows from locally consumed flow.
4420 * @param self ID of own station.
4422 void FlowStatMap::FinalizeLocalConsumption(StationID self)
4424 for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
4425 FlowStat &fs = i->second;
4426 uint local = fs.GetShare(INVALID_STATION);
4427 if (local > INT_MAX) { // make sure it fits in an int
4428 fs.ChangeShare(self, -INT_MAX);
4429 fs.ChangeShare(INVALID_STATION, -INT_MAX);
4430 local -= INT_MAX;
4432 fs.ChangeShare(self, -(int)local);
4433 fs.ChangeShare(INVALID_STATION, -(int)local);
4435 /* If the local share is used up there must be a share for some
4436 * remote station. */
4437 assert(!fs.GetShares()->empty());
4442 * Delete all flows at a station for specific cargo and destination.
4443 * @param via Remote station of flows to be deleted.
4444 * @return IDs of source stations for which the complete FlowStat, not only a
4445 * share, has been erased.
4447 StationIDStack FlowStatMap::DeleteFlows(StationID via)
4449 StationIDStack ret;
4450 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
4451 FlowStat &s_flows = f_it->second;
4452 s_flows.ChangeShare(via, INT_MIN);
4453 if (s_flows.GetShares()->empty()) {
4454 ret.Push(f_it->first);
4455 this->erase(f_it++);
4456 } else {
4457 ++f_it;
4460 return ret;
4464 * Restrict all flows at a station for specific cargo and destination.
4465 * @param via Remote station of flows to be restricted.
4467 void FlowStatMap::RestrictFlows(StationID via)
4469 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4470 it->second.RestrictShare(via);
4475 * Release all flows at a station for specific cargo and destination.
4476 * @param via Remote station of flows to be released.
4478 void FlowStatMap::ReleaseFlows(StationID via)
4480 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4481 it->second.ReleaseShare(via);
4486 * Get the sum of flows via a specific station from this GoodsEntry.
4487 * @param via Remote station to look for.
4488 * @return a FlowStat with all flows for 'via' added up.
4490 uint GoodsEntry::GetSumFlowVia(StationID via) const
4492 uint ret = 0;
4493 for (FlowStatMap::const_iterator i = this->flows.begin(); i != this->flows.end(); ++i) {
4494 ret += i->second.GetShare(via);
4496 return ret;
4499 extern const TileTypeProcs _tile_type_station_procs = {
4500 DrawTile_Station, // draw_tile_proc
4501 GetSlopePixelZ_Station, // get_slope_z_proc
4502 ClearTile_Station, // clear_tile_proc
4503 NULL, // add_accepted_cargo_proc
4504 GetTileDesc_Station, // get_tile_desc_proc
4505 GetTileRailwayStatus_Station, // get_tile_railway_status_proc
4506 GetTileRoadStatus_Station, // get_tile_road_status_proc
4507 GetTileWaterwayStatus_Station, // get_tile_waterway_status_proc
4508 ClickTile_Station, // click_tile_proc
4509 AnimateTile_Station, // animate_tile_proc
4510 TileLoop_Station, // tile_loop_proc
4511 ChangeTileOwner_Station, // change_tile_owner_proc
4512 NULL, // add_produced_cargo_proc
4513 GetFoundation_Station, // get_foundation_proc
4514 TerraformTile_Station, // terraform_tile_proc