Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / rail_cmd.cpp
blob89329ea6d00b63ec3998d531cb60cc239c2c18f7
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file rail_cmd.cpp Handling of rail tiles. */
10 #include "stdafx.h"
11 #include "viewport_func.h"
12 #include "command_func.h"
13 #include "depot_base.h"
14 #include "pathfinder/yapf/yapf_cache.h"
15 #include "newgrf_debug.h"
16 #include "newgrf_railtype.h"
17 #include "train.h"
18 #include "autoslope.h"
19 #include "water.h"
20 #include "tunnelbridge_map.h"
21 #include "vehicle_func.h"
22 #include "sound_func.h"
23 #include "tunnelbridge.h"
24 #include "elrail_func.h"
25 #include "town.h"
26 #include "pbs.h"
27 #include "company_base.h"
28 #include "core/backup_type.hpp"
29 #include "core/container_func.hpp"
30 #include "timer/timer_game_calendar.h"
31 #include "strings_func.h"
32 #include "company_gui.h"
33 #include "object_map.h"
34 #include "rail_cmd.h"
35 #include "landscape_cmd.h"
37 #include "table/strings.h"
38 #include "table/railtypes.h"
39 #include "table/track_land.h"
41 #include "safeguards.h"
43 /** Helper type for lists/vectors of trains */
44 typedef std::vector<Train *> TrainList;
46 RailTypeInfo _railtypes[RAILTYPE_END];
47 std::vector<RailType> _sorted_railtypes;
48 RailTypes _railtypes_hidden_mask;
50 /** Enum holding the signal offset in the sprite sheet according to the side it is representing. */
51 enum SignalOffsets {
52 SIGNAL_TO_SOUTHWEST,
53 SIGNAL_TO_NORTHEAST,
54 SIGNAL_TO_SOUTHEAST,
55 SIGNAL_TO_NORTHWEST,
56 SIGNAL_TO_EAST,
57 SIGNAL_TO_WEST,
58 SIGNAL_TO_SOUTH,
59 SIGNAL_TO_NORTH,
62 /**
63 * Reset all rail type information to its default values.
65 void ResetRailTypes()
67 static_assert(lengthof(_original_railtypes) <= lengthof(_railtypes));
69 auto insert = std::copy(std::begin(_original_railtypes), std::end(_original_railtypes), std::begin(_railtypes));
70 std::fill(insert, std::end(_railtypes), RailTypeInfo{});
72 _railtypes_hidden_mask = RAILTYPES_NONE;
75 void ResolveRailTypeGUISprites(RailTypeInfo *rti)
77 SpriteID cursors_base = GetCustomRailSprite(rti, INVALID_TILE, RTSG_CURSORS);
78 if (cursors_base != 0) {
79 rti->gui_sprites.build_ns_rail = cursors_base + 0;
80 rti->gui_sprites.build_x_rail = cursors_base + 1;
81 rti->gui_sprites.build_ew_rail = cursors_base + 2;
82 rti->gui_sprites.build_y_rail = cursors_base + 3;
83 rti->gui_sprites.auto_rail = cursors_base + 4;
84 rti->gui_sprites.build_depot = cursors_base + 5;
85 rti->gui_sprites.build_tunnel = cursors_base + 6;
86 rti->gui_sprites.convert_rail = cursors_base + 7;
87 rti->cursor.rail_ns = cursors_base + 8;
88 rti->cursor.rail_swne = cursors_base + 9;
89 rti->cursor.rail_ew = cursors_base + 10;
90 rti->cursor.rail_nwse = cursors_base + 11;
91 rti->cursor.autorail = cursors_base + 12;
92 rti->cursor.depot = cursors_base + 13;
93 rti->cursor.tunnel = cursors_base + 14;
94 rti->cursor.convert = cursors_base + 15;
97 /* Array of default GUI signal sprite numbers. */
98 const SpriteID _signal_lookup[2][SIGTYPE_END] = {
99 {SPR_IMG_SIGNAL_ELECTRIC_NORM, SPR_IMG_SIGNAL_ELECTRIC_ENTRY, SPR_IMG_SIGNAL_ELECTRIC_EXIT,
100 SPR_IMG_SIGNAL_ELECTRIC_COMBO, SPR_IMG_SIGNAL_ELECTRIC_PBS, SPR_IMG_SIGNAL_ELECTRIC_PBS_OWAY},
102 {SPR_IMG_SIGNAL_SEMAPHORE_NORM, SPR_IMG_SIGNAL_SEMAPHORE_ENTRY, SPR_IMG_SIGNAL_SEMAPHORE_EXIT,
103 SPR_IMG_SIGNAL_SEMAPHORE_COMBO, SPR_IMG_SIGNAL_SEMAPHORE_PBS, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY},
106 for (SignalType type = SIGTYPE_BLOCK; type < SIGTYPE_END; type = (SignalType)(type + 1)) {
107 for (SignalVariant var = SIG_ELECTRIC; var <= SIG_SEMAPHORE; var = (SignalVariant)(var + 1)) {
108 SpriteID red = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_RED, true);
109 SpriteID green = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_GREEN, true);
110 rti->gui_sprites.signals[type][var][0] = (red != 0) ? red + SIGNAL_TO_SOUTH : _signal_lookup[var][type];
111 rti->gui_sprites.signals[type][var][1] = (green != 0) ? green + SIGNAL_TO_SOUTH : _signal_lookup[var][type] + 1;
117 * Compare railtypes based on their sorting order.
118 * @param first The railtype to compare to.
119 * @param second The railtype to compare.
120 * @return True iff the first should be sorted before the second.
122 static bool CompareRailTypes(const RailType &first, const RailType &second)
124 return GetRailTypeInfo(first)->sorting_order < GetRailTypeInfo(second)->sorting_order;
128 * Resolve sprites of custom rail types
130 void InitRailTypes()
132 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
133 RailTypeInfo *rti = &_railtypes[rt];
134 ResolveRailTypeGUISprites(rti);
135 if (HasBit(rti->flags, RTF_HIDDEN)) SetBit(_railtypes_hidden_mask, rt);
138 _sorted_railtypes.clear();
139 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
140 if (_railtypes[rt].label != 0 && !HasBit(_railtypes_hidden_mask, rt)) {
141 _sorted_railtypes.push_back(rt);
144 std::sort(_sorted_railtypes.begin(), _sorted_railtypes.end(), CompareRailTypes);
148 * Allocate a new rail type label
150 RailType AllocateRailType(RailTypeLabel label)
152 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
153 RailTypeInfo *rti = &_railtypes[rt];
155 if (rti->label == 0) {
156 /* Set up new rail type */
157 *rti = _original_railtypes[RAILTYPE_RAIL];
158 rti->label = label;
159 rti->alternate_labels.clear();
161 /* Make us compatible with ourself. */
162 rti->powered_railtypes = (RailTypes)(1LL << rt);
163 rti->compatible_railtypes = (RailTypes)(1LL << rt);
165 /* We also introduce ourself. */
166 rti->introduces_railtypes = (RailTypes)(1LL << rt);
168 /* Default sort order; order of allocation, but with some
169 * offsets so it's easier for NewGRF to pick a spot without
170 * changing the order of other (original) rail types.
171 * The << is so you can place other railtypes in between the
172 * other railtypes, the 7 is to be able to place something
173 * before the first (default) rail type. */
174 rti->sorting_order = rt << 4 | 7;
175 return rt;
179 return INVALID_RAILTYPE;
182 static const byte _track_sloped_sprites[14] = {
183 14, 15, 22, 13,
184 0, 21, 17, 12,
185 23, 0, 18, 20,
186 19, 16
190 /* 4
191 * ---------
192 * |\ /|
193 * | \ 1/ |
194 * | \ / |
195 * | \ / |
196 * 16| \ |32
197 * | / \2 |
198 * | / \ |
199 * | / \ |
200 * |/ \|
201 * ---------
207 /* MAP2 byte: abcd???? => Signal On? Same coding as map3lo
208 * MAP3LO byte: abcd???? => Signal Exists?
209 * a and b are for diagonals, upper and left,
210 * one for each direction. (ie a == NE->SW, b ==
211 * SW->NE, or v.v., I don't know. b and c are
212 * similar for lower and right.
213 * MAP2 byte: ????abcd => Type of ground.
214 * MAP3LO byte: ????abcd => Type of rail.
215 * MAP5: 00abcdef => rail
216 * 01abcdef => rail w/ signals
217 * 10uuuuuu => unused
218 * 11uuuudd => rail depot
222 * Tests if a vehicle interacts with the specified track.
223 * All track bits interact except parallel #TRACK_BIT_HORZ or #TRACK_BIT_VERT.
225 * @param tile The tile.
226 * @param track The track.
227 * @return Succeeded command (no train found), or a failed command (a train was found).
229 static CommandCost EnsureNoTrainOnTrack(TileIndex tile, Track track)
231 TrackBits rail_bits = TrackToTrackBits(track);
232 return EnsureNoTrainOnTrackBits(tile, rail_bits);
236 * Check that the new track bits may be built.
237 * @param tile %Tile to build on.
238 * @param to_build New track bits.
239 * @return Succeeded or failed command.
241 static CommandCost CheckTrackCombination(TileIndex tile, TrackBits to_build)
243 if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
245 /* So, we have a tile with tracks on it (and possibly signals). Let's see
246 * what tracks first */
247 TrackBits current = GetTrackBits(tile); // The current track layout.
248 TrackBits future = current | to_build; // The track layout we want to build.
250 /* Are we really building something new? */
251 if (current == future) {
252 /* Nothing new is being built */
253 return_cmd_error(STR_ERROR_ALREADY_BUILT);
256 /* Normally, we may overlap and any combination is valid */
257 return CommandCost();
261 /** Valid TrackBits on a specific (non-steep)-slope without foundation */
262 static const TrackBits _valid_tracks_without_foundation[15] = {
263 TRACK_BIT_ALL,
264 TRACK_BIT_RIGHT,
265 TRACK_BIT_UPPER,
266 TRACK_BIT_X,
268 TRACK_BIT_LEFT,
269 TRACK_BIT_NONE,
270 TRACK_BIT_Y,
271 TRACK_BIT_LOWER,
273 TRACK_BIT_LOWER,
274 TRACK_BIT_Y,
275 TRACK_BIT_NONE,
276 TRACK_BIT_LEFT,
278 TRACK_BIT_X,
279 TRACK_BIT_UPPER,
280 TRACK_BIT_RIGHT,
283 /** Valid TrackBits on a specific (non-steep)-slope with leveled foundation */
284 static const TrackBits _valid_tracks_on_leveled_foundation[15] = {
285 TRACK_BIT_NONE,
286 TRACK_BIT_LEFT,
287 TRACK_BIT_LOWER,
288 TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
290 TRACK_BIT_RIGHT,
291 TRACK_BIT_ALL,
292 TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,
293 TRACK_BIT_ALL,
295 TRACK_BIT_UPPER,
296 TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_LEFT,
297 TRACK_BIT_ALL,
298 TRACK_BIT_ALL,
300 TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,
301 TRACK_BIT_ALL,
302 TRACK_BIT_ALL
306 * Checks if a track combination is valid on a specific slope and returns the needed foundation.
308 * @param tileh Tile slope.
309 * @param bits Trackbits.
310 * @return Needed foundation or FOUNDATION_INVALID if track/slope combination is not allowed.
312 Foundation GetRailFoundation(Slope tileh, TrackBits bits)
314 if (bits == TRACK_BIT_NONE) return FOUNDATION_NONE;
316 if (IsSteepSlope(tileh)) {
317 /* Test for inclined foundations */
318 if (bits == TRACK_BIT_X) return FOUNDATION_INCLINED_X;
319 if (bits == TRACK_BIT_Y) return FOUNDATION_INCLINED_Y;
321 /* Get higher track */
322 Corner highest_corner = GetHighestSlopeCorner(tileh);
323 TrackBits higher_track = CornerToTrackBits(highest_corner);
325 /* Only higher track? */
326 if (bits == higher_track) return HalftileFoundation(highest_corner);
328 /* Overlap with higher track? */
329 if (TracksOverlap(bits | higher_track)) return FOUNDATION_INVALID;
331 /* either lower track or both higher and lower track */
332 return ((bits & higher_track) != 0 ? FOUNDATION_STEEP_BOTH : FOUNDATION_STEEP_LOWER);
333 } else {
334 if ((~_valid_tracks_without_foundation[tileh] & bits) == 0) return FOUNDATION_NONE;
336 bool valid_on_leveled = ((~_valid_tracks_on_leveled_foundation[tileh] & bits) == 0);
338 Corner track_corner;
339 switch (bits) {
340 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
341 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
342 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
343 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
345 case TRACK_BIT_HORZ:
346 if (tileh == SLOPE_N) return HalftileFoundation(CORNER_N);
347 if (tileh == SLOPE_S) return HalftileFoundation(CORNER_S);
348 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
350 case TRACK_BIT_VERT:
351 if (tileh == SLOPE_W) return HalftileFoundation(CORNER_W);
352 if (tileh == SLOPE_E) return HalftileFoundation(CORNER_E);
353 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
355 case TRACK_BIT_X:
356 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_X;
357 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
359 case TRACK_BIT_Y:
360 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_Y;
361 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
363 default:
364 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
366 /* Single diagonal track */
368 /* Track must be at least valid on leveled foundation */
369 if (!valid_on_leveled) return FOUNDATION_INVALID;
371 /* If slope has three raised corners, build leveled foundation */
372 if (IsSlopeWithThreeCornersRaised(tileh)) return FOUNDATION_LEVELED;
374 /* If neighboured corners of track_corner are lowered, build halftile foundation */
375 if ((tileh & SlopeWithThreeCornersRaised(OppositeCorner(track_corner))) == SlopeWithOneCornerRaised(track_corner)) return HalftileFoundation(track_corner);
377 /* else special anti-zig-zag foundation */
378 return SpecialRailFoundation(track_corner);
384 * Tests if a track can be build on a tile.
386 * @param tileh Tile slope.
387 * @param rail_bits Tracks to build.
388 * @param existing Tracks already built.
389 * @param tile Tile (used for water test)
390 * @return Error message or cost for foundation building.
392 static CommandCost CheckRailSlope(Slope tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile)
394 /* don't allow building on the lower side of a coast */
395 if (GetFloodingBehaviour(tile) != FLOOD_NONE) {
396 if (!IsSteepSlope(tileh) && ((~_valid_tracks_on_leveled_foundation[tileh] & (rail_bits | existing)) != 0)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
399 Foundation f_new = GetRailFoundation(tileh, rail_bits | existing);
401 /* check track/slope combination */
402 if ((f_new == FOUNDATION_INVALID) ||
403 ((f_new != FOUNDATION_NONE) && (!_settings_game.construction.build_on_slopes))) {
404 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
407 Foundation f_old = GetRailFoundation(tileh, existing);
408 return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price[PR_BUILD_FOUNDATION] : (Money)0);
411 /* Validate functions for rail building */
412 static inline bool ValParamTrackOrientation(Track track)
414 return IsValidTrack(track);
418 * Build a single piece of rail
419 * @param flags operation to perform
420 * @param tile tile to build on
421 * @param railtype railtype of being built piece (normal, mono, maglev)
422 * @param track track-orientation
423 * @param auto_remove_signals false = error on signal in the way, true = auto remove signals when in the way
424 * @return the cost of this operation or an error
426 CommandCost CmdBuildSingleRail(DoCommandFlag flags, TileIndex tile, RailType railtype, Track track, bool auto_remove_signals)
428 CommandCost cost(EXPENSES_CONSTRUCTION);
430 if (!ValParamRailType(railtype) || !ValParamTrackOrientation(track)) return CMD_ERROR;
432 Slope tileh = GetTileSlope(tile);
433 TrackBits trackbit = TrackToTrackBits(track);
435 switch (GetTileType(tile)) {
436 case MP_RAILWAY: {
437 CommandCost ret = CheckTileOwnership(tile);
438 if (ret.Failed()) return ret;
440 if (!IsPlainRail(tile)) return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile); // just get appropriate error message
442 if (!IsCompatibleRail(GetRailType(tile), railtype)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
444 ret = CheckTrackCombination(tile, trackbit);
445 if (ret.Succeeded()) ret = EnsureNoTrainOnTrack(tile, track);
446 if (ret.Failed()) return ret;
448 ret = CheckRailSlope(tileh, trackbit, GetTrackBits(tile), tile);
449 if (ret.Failed()) return ret;
450 cost.AddCost(ret);
452 if (HasSignals(tile) && TracksOverlap(GetTrackBits(tile) | TrackToTrackBits(track))) {
453 /* If adding the new track causes any overlap, all signals must be removed first */
454 if (!auto_remove_signals) return_cmd_error(STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
456 for (Track track_it = TRACK_BEGIN; track_it < TRACK_END; track_it++) {
457 if (HasTrack(tile, track_it) && HasSignalOnTrack(tile, track_it)) {
458 CommandCost ret_remove_signals = Command<CMD_REMOVE_SINGLE_SIGNAL>::Do(flags, tile, track_it);
459 if (ret_remove_signals.Failed()) return ret_remove_signals;
460 cost.AddCost(ret_remove_signals);
465 /* If the rail types don't match, try to convert only if engines of
466 * the new rail type are not powered on the present rail type and engines of
467 * the present rail type are powered on the new rail type. */
468 if (GetRailType(tile) != railtype && !HasPowerOnRail(railtype, GetRailType(tile))) {
469 if (HasPowerOnRail(GetRailType(tile), railtype)) {
470 ret = Command<CMD_CONVERT_RAIL>::Do(flags, tile, tile, railtype, false);
471 if (ret.Failed()) return ret;
472 cost.AddCost(ret);
473 } else {
474 return CMD_ERROR;
478 if (flags & DC_EXEC) {
479 SetRailGroundType(tile, RAIL_GROUND_BARREN);
480 TrackBits bits = GetTrackBits(tile);
481 SetTrackBits(tile, bits | trackbit);
482 /* Subtract old infrastructure count. */
483 uint pieces = CountBits(bits);
484 if (TracksOverlap(bits)) pieces *= pieces;
485 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] -= pieces;
486 /* Add new infrastructure count. */
487 pieces = CountBits(bits | trackbit);
488 if (TracksOverlap(bits | trackbit)) pieces *= pieces;
489 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] += pieces;
490 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
492 break;
495 case MP_ROAD: {
496 /* Level crossings may only be built on these slopes */
497 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
499 if (!_settings_game.construction.crossing_with_competitor && _current_company != OWNER_DEITY) {
500 CommandCost ret = CheckTileOwnership(tile);
501 if (ret.Failed()) return ret;
504 CommandCost ret = EnsureNoVehicleOnGround(tile);
505 if (ret.Failed()) return ret;
507 if (IsNormalRoad(tile)) {
508 if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
510 if (GetDisallowedRoadDirections(tile) != DRD_NONE) return_cmd_error(STR_ERROR_CROSSING_ON_ONEWAY_ROAD);
512 if (RailNoLevelCrossings(railtype)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_RAIL);
514 RoadType roadtype_road = GetRoadTypeRoad(tile);
515 RoadType roadtype_tram = GetRoadTypeTram(tile);
517 if (roadtype_road != INVALID_ROADTYPE && RoadNoLevelCrossing(roadtype_road)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD);
518 if (roadtype_tram != INVALID_ROADTYPE && RoadNoLevelCrossing(roadtype_tram)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD);
520 RoadBits road = GetRoadBits(tile, RTT_ROAD);
521 RoadBits tram = GetRoadBits(tile, RTT_TRAM);
522 if ((track == TRACK_X && ((road | tram) & ROAD_X) == 0) ||
523 (track == TRACK_Y && ((road | tram) & ROAD_Y) == 0)) {
524 Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
525 Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
526 /* Disallow breaking end-of-line of someone else
527 * so trams can still reverse on this tile. */
528 if (Company::IsValidID(tram_owner) && HasExactlyOneBit(tram)) {
529 ret = CheckOwnership(tram_owner);
530 if (ret.Failed()) return ret;
533 uint num_new_road_pieces = (road != ROAD_NONE) ? 2 - CountBits(road) : 0;
534 if (num_new_road_pieces > 0) {
535 cost.AddCost(num_new_road_pieces * RoadBuildCost(roadtype_road));
538 uint num_new_tram_pieces = (tram != ROAD_NONE) ? 2 - CountBits(tram) : 0;
539 if (num_new_tram_pieces > 0) {
540 cost.AddCost(num_new_tram_pieces * RoadBuildCost(roadtype_tram));
543 if (flags & DC_EXEC) {
544 MakeRoadCrossing(tile, road_owner, tram_owner, _current_company, (track == TRACK_X ? AXIS_Y : AXIS_X), railtype, roadtype_road, roadtype_tram, GetTownIndex(tile));
545 UpdateLevelCrossing(tile, false);
546 MarkDirtyAdjacentLevelCrossingTiles(tile, GetCrossingRoadAxis(tile));
547 Company::Get(_current_company)->infrastructure.rail[railtype] += LEVELCROSSING_TRACKBIT_FACTOR;
548 DirtyCompanyInfrastructureWindows(_current_company);
549 if (num_new_road_pieces > 0 && Company::IsValidID(road_owner)) {
550 Company::Get(road_owner)->infrastructure.road[roadtype_road] += num_new_road_pieces;
551 DirtyCompanyInfrastructureWindows(road_owner);
553 if (num_new_tram_pieces > 0 && Company::IsValidID(tram_owner)) {
554 Company::Get(tram_owner)->infrastructure.road[roadtype_tram] += num_new_tram_pieces;
555 DirtyCompanyInfrastructureWindows(tram_owner);
558 break;
562 if (IsLevelCrossing(tile) && GetCrossingRailBits(tile) == trackbit) {
563 return_cmd_error(STR_ERROR_ALREADY_BUILT);
565 [[fallthrough]];
568 default: {
569 /* Will there be flat water on the lower halftile? */
570 bool water_ground = IsTileType(tile, MP_WATER) && IsSlopeWithOneCornerRaised(tileh);
572 CommandCost ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile);
573 if (ret.Failed()) return ret;
574 cost.AddCost(ret);
576 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
577 if (ret.Failed()) return ret;
578 cost.AddCost(ret);
580 if (water_ground) {
581 cost.AddCost(-_price[PR_CLEAR_WATER]);
582 cost.AddCost(_price[PR_CLEAR_ROUGH]);
585 if (flags & DC_EXEC) {
586 MakeRailNormal(tile, _current_company, trackbit, railtype);
587 if (water_ground) {
588 SetRailGroundType(tile, RAIL_GROUND_WATER);
589 if (IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
591 Company::Get(_current_company)->infrastructure.rail[railtype]++;
592 DirtyCompanyInfrastructureWindows(_current_company);
594 break;
598 if (flags & DC_EXEC) {
599 MarkTileDirtyByTile(tile);
600 AddTrackToSignalBuffer(tile, track, _current_company);
601 YapfNotifyTrackLayoutChange(tile, track);
604 cost.AddCost(RailBuildCost(railtype));
605 return cost;
609 * Remove a single piece of track
610 * @param flags operation to perform
611 * @param tile tile to remove track from
612 * @param track rail orientation
613 * @return the cost of this operation or an error
615 CommandCost CmdRemoveSingleRail(DoCommandFlag flags, TileIndex tile, Track track)
617 CommandCost cost(EXPENSES_CONSTRUCTION);
618 bool crossing = false;
620 if (!ValParamTrackOrientation(track)) return CMD_ERROR;
621 TrackBits trackbit = TrackToTrackBits(track);
623 /* Need to read tile owner now because it may change when the rail is removed
624 * Also, in case of floods, _current_company != owner
625 * There may be invalid tiletype even in exec run (when removing long track),
626 * so do not call GetTileOwner(tile) in any case here */
627 Owner owner = INVALID_OWNER;
629 Train *v = nullptr;
631 switch (GetTileType(tile)) {
632 case MP_ROAD: {
633 if (!IsLevelCrossing(tile) || GetCrossingRailBits(tile) != trackbit) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
635 if (_current_company != OWNER_WATER) {
636 CommandCost ret = CheckTileOwnership(tile);
637 if (ret.Failed()) return ret;
640 if (!(flags & DC_BANKRUPT)) {
641 CommandCost ret = EnsureNoVehicleOnGround(tile);
642 if (ret.Failed()) return ret;
645 cost.AddCost(RailClearCost(GetRailType(tile)));
647 if (flags & DC_EXEC) {
648 UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval(tile, GetCrossingRoadAxis(tile));
650 if (HasReservedTracks(tile, trackbit)) {
651 v = GetTrainForReservation(tile, track);
652 if (v != nullptr) FreeTrainTrackReservation(v);
655 owner = GetTileOwner(tile);
656 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
657 DirtyCompanyInfrastructureWindows(owner);
658 MakeRoadNormal(tile, GetCrossingRoadBits(tile), GetRoadTypeRoad(tile), GetRoadTypeTram(tile), GetTownIndex(tile), GetRoadOwner(tile, RTT_ROAD), GetRoadOwner(tile, RTT_TRAM));
659 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile.base());
661 break;
664 case MP_RAILWAY: {
665 TrackBits present;
666 /* There are no rails present at depots. */
667 if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
669 if (_current_company != OWNER_WATER) {
670 CommandCost ret = CheckTileOwnership(tile);
671 if (ret.Failed()) return ret;
674 CommandCost ret = EnsureNoTrainOnTrack(tile, track);
675 if (ret.Failed()) return ret;
677 present = GetTrackBits(tile);
678 if ((present & trackbit) == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
679 if (present == (TRACK_BIT_X | TRACK_BIT_Y)) crossing = true;
681 cost.AddCost(RailClearCost(GetRailType(tile)));
683 /* Charge extra to remove signals on the track, if they are there */
684 if (HasSignalOnTrack(tile, track)) {
685 cost.AddCost(Command<CMD_REMOVE_SINGLE_SIGNAL>::Do(flags, tile, track));
688 if (flags & DC_EXEC) {
689 if (HasReservedTracks(tile, trackbit)) {
690 v = GetTrainForReservation(tile, track);
691 if (v != nullptr) FreeTrainTrackReservation(v);
694 owner = GetTileOwner(tile);
696 /* Subtract old infrastructure count. */
697 uint pieces = CountBits(present);
698 if (TracksOverlap(present)) pieces *= pieces;
699 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= pieces;
700 /* Add new infrastructure count. */
701 present ^= trackbit;
702 pieces = CountBits(present);
703 if (TracksOverlap(present)) pieces *= pieces;
704 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] += pieces;
705 DirtyCompanyInfrastructureWindows(owner);
707 if (present == 0) {
708 Slope tileh = GetTileSlope(tile);
709 /* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
710 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh)) {
711 bool docking = IsDockingTile(tile);
712 MakeShore(tile);
713 SetDockingTile(tile, docking);
714 } else {
715 DoClearSquare(tile);
717 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile.base());
718 } else {
719 SetTrackBits(tile, present);
720 SetTrackReservation(tile, GetRailReservationTrackBits(tile) & present);
723 break;
726 default: return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
729 if (flags & DC_EXEC) {
730 /* if we got that far, 'owner' variable is set correctly */
731 assert(Company::IsValidID(owner));
733 MarkTileDirtyByTile(tile);
734 if (crossing) {
735 /* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
736 * are removing one of these pieces, we'll need to update signals for
737 * both directions explicitly, as after the track is removed it won't
738 * 'connect' with the other piece. */
739 AddTrackToSignalBuffer(tile, TRACK_X, owner);
740 AddTrackToSignalBuffer(tile, TRACK_Y, owner);
741 YapfNotifyTrackLayoutChange(tile, TRACK_X);
742 YapfNotifyTrackLayoutChange(tile, TRACK_Y);
743 } else {
744 AddTrackToSignalBuffer(tile, track, owner);
745 YapfNotifyTrackLayoutChange(tile, track);
748 if (v != nullptr) TryPathReserve(v, true);
751 return cost;
756 * Called from water_cmd if a non-flat rail-tile gets flooded and should be converted to shore.
757 * The function floods the lower halftile, if the tile has a halftile foundation.
759 * @param t The tile to flood.
760 * @return true if something was flooded.
762 bool FloodHalftile(TileIndex t)
764 assert(IsPlainRailTile(t));
766 bool flooded = false;
767 if (GetRailGroundType(t) == RAIL_GROUND_WATER) return flooded;
769 Slope tileh = GetTileSlope(t);
770 TrackBits rail_bits = GetTrackBits(t);
772 if (IsSlopeWithOneCornerRaised(tileh)) {
773 TrackBits lower_track = CornerToTrackBits(OppositeCorner(GetHighestSlopeCorner(tileh)));
775 TrackBits to_remove = lower_track & rail_bits;
776 if (to_remove != 0) {
777 Backup<CompanyID> cur_company(_current_company, OWNER_WATER, FILE_LINE);
778 flooded = Command<CMD_REMOVE_SINGLE_RAIL>::Do(DC_EXEC, t, FindFirstTrack(to_remove)).Succeeded();
779 cur_company.Restore();
780 if (!flooded) return flooded; // not yet floodable
781 rail_bits = rail_bits & ~to_remove;
782 if (rail_bits == 0) {
783 MakeShore(t);
784 MarkTileDirtyByTile(t);
785 return flooded;
789 if (IsNonContinuousFoundation(GetRailFoundation(tileh, rail_bits))) {
790 flooded = true;
791 SetRailGroundType(t, RAIL_GROUND_WATER);
792 MarkTileDirtyByTile(t);
794 } else {
795 /* Make shore on steep slopes and 'three-corners-raised'-slopes. */
796 if (ApplyFoundationToSlope(GetRailFoundation(tileh, rail_bits), &tileh) == 0) {
797 if (IsSteepSlope(tileh) || IsSlopeWithThreeCornersRaised(tileh)) {
798 flooded = true;
799 SetRailGroundType(t, RAIL_GROUND_WATER);
800 MarkTileDirtyByTile(t);
804 return flooded;
807 static const TileIndexDiffC _trackdelta[] = {
808 { -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
809 { 0, 0 },
810 { 0, 0 },
811 { 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
812 { 0, 0 },
813 { 0, 0 }
817 static CommandCost ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end)
819 int x = TileX(start);
820 int y = TileY(start);
821 int ex = TileX(end);
822 int ey = TileY(end);
824 if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CMD_ERROR;
826 /* calculate delta x,y from start to end tile */
827 int dx = ex - x;
828 int dy = ey - y;
830 /* calculate delta x,y for the first direction */
831 int trdx = _trackdelta[*trackdir].x;
832 int trdy = _trackdelta[*trackdir].y;
834 if (!IsDiagonalTrackdir(*trackdir)) {
835 trdx += _trackdelta[*trackdir ^ 1].x;
836 trdy += _trackdelta[*trackdir ^ 1].y;
839 /* validate the direction */
840 while ((trdx <= 0 && dx > 0) ||
841 (trdx >= 0 && dx < 0) ||
842 (trdy <= 0 && dy > 0) ||
843 (trdy >= 0 && dy < 0)) {
844 if (!HasBit(*trackdir, 3)) { // first direction is invalid, try the other
845 SetBit(*trackdir, 3); // reverse the direction
846 trdx = -trdx;
847 trdy = -trdy;
848 } else { // other direction is invalid too, invalid drag
849 return CMD_ERROR;
853 /* (for diagonal tracks, this is already made sure of by above test), but:
854 * for non-diagonal tracks, check if the start and end tile are on 1 line */
855 if (!IsDiagonalTrackdir(*trackdir)) {
856 trdx = _trackdelta[*trackdir].x;
857 trdy = _trackdelta[*trackdir].y;
858 if (abs(dx) != abs(dy) && abs(dx) + abs(trdy) != abs(dy) + abs(trdx)) return CMD_ERROR;
861 return CommandCost();
865 * Build or remove a stretch of railroad tracks.
866 * @param flags operation to perform
867 * @param tile start tile of drag
868 * @param end_tile end tile of drag
869 * @param railtype railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
870 * @param track track-orientation
871 * @param remove remove tracks?
872 * @param auto_remove_signals false = error on signal in the way, true = auto remove signals when in the way, only used for building
873 * @param fail_on_obstacle false = build starting from and up to an obstacle, true = fail if an obstacle is found (used for AIs)
874 * @return the cost of this operation or an error
876 static CommandCost CmdRailTrackHelper(DoCommandFlag flags, TileIndex tile, TileIndex end_tile, RailType railtype, Track track, bool remove, bool auto_remove_signals, bool fail_on_obstacle)
878 CommandCost total_cost(EXPENSES_CONSTRUCTION);
880 if ((!remove && !ValParamRailType(railtype)) || !ValParamTrackOrientation(track)) return CMD_ERROR;
881 if (end_tile >= Map::Size() || tile >= Map::Size()) return CMD_ERROR;
883 Trackdir trackdir = TrackToTrackdir(track);
885 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
886 if (ret.Failed()) return ret;
888 bool had_success = false;
889 bool under_tunnelbridge = false;
890 CommandCost last_error = CMD_ERROR;
891 for (;;) {
892 /* Don't try to place rail between tunnelbridge ends */
893 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
894 under_tunnelbridge = !under_tunnelbridge;
895 } else if (!under_tunnelbridge) {
896 if (remove) {
897 ret = Command<CMD_REMOVE_SINGLE_RAIL>::Do(flags, tile, TrackdirToTrack(trackdir));
898 } else {
899 ret = Command<CMD_BUILD_SINGLE_RAIL>::Do(flags, tile, railtype, TrackdirToTrack(trackdir), auto_remove_signals);
902 if (ret.Failed()) {
903 last_error = ret;
904 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT && !remove) {
905 if (fail_on_obstacle) return last_error;
906 if (had_success) break; // Keep going if we haven't constructed any rail yet, skipping the start of the drag
909 /* Ownership errors are more important. */
910 if (last_error.GetErrorMessage() == STR_ERROR_OWNED_BY && remove) break;
911 } else {
912 had_success = true;
913 total_cost.AddCost(ret);
917 if (tile == end_tile) break;
919 tile += ToTileIndexDiff(_trackdelta[trackdir]);
921 /* toggle railbit for the non-diagonal tracks */
922 if (!IsDiagonalTrackdir(trackdir)) ToggleBit(trackdir, 0);
925 if (had_success) return total_cost;
926 return last_error;
930 * Build rail on a stretch of track.
931 * Stub for the unified rail builder/remover
932 * @param flags operation to perform
933 * @param end_tile end tile of drag
934 * @param start_tile start tile of drag
935 * @param railtype railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
936 * @param track track-orientation
937 * @param auto_remove_signals false = build up to an obstacle, true = fail if an obstacle is found (used for AIs).
938 * @param fail_on_obstacle false = error on signal in the way, true = auto remove signals when in the way
940 * @see CmdRailTrackHelper
942 CommandCost CmdBuildRailroadTrack(DoCommandFlag flags, TileIndex end_tile, TileIndex start_tile, RailType railtype, Track track, bool auto_remove_signals, bool fail_on_obstacle)
944 return CmdRailTrackHelper(flags, start_tile, end_tile, railtype, track, false, auto_remove_signals, fail_on_obstacle);
948 * Build rail on a stretch of track.
949 * Stub for the unified rail builder/remover
950 * @param flags operation to perform
951 * @param end_tile end tile of drag
952 * @param start_tile start tile of drag
953 * @param track track-orientation
954 * @return the cost of this operation or an error
955 * @see CmdRailTrackHelper
957 CommandCost CmdRemoveRailroadTrack(DoCommandFlag flags, TileIndex end_tile, TileIndex start_tile, Track track)
959 return CmdRailTrackHelper(flags, start_tile, end_tile, INVALID_RAILTYPE, track, true, false, false);
963 * Build a train depot
964 * @param flags operation to perform
965 * @param tile position of the train depot
966 * @param railtype rail type
967 * @param dir entrance direction
968 * @return the cost of this operation or an error
970 * @todo When checking for the tile slope,
971 * distinguish between "Flat land required" and "land sloped in wrong direction"
973 CommandCost CmdBuildTrainDepot(DoCommandFlag flags, TileIndex tile, RailType railtype, DiagDirection dir)
975 /* check railtype and valid direction for depot (0 through 3), 4 in total */
976 if (!ValParamRailType(railtype) || !IsValidDiagDirection(dir)) return CMD_ERROR;
978 Slope tileh = GetTileSlope(tile);
980 CommandCost cost(EXPENSES_CONSTRUCTION);
982 /* Prohibit construction if
983 * The tile is non-flat AND
984 * 1) build-on-slopes is disabled
985 * 2) the tile is steep i.e. spans two height levels
986 * 3) the exit points in the wrong direction
989 if (tileh != SLOPE_FLAT) {
990 if (!_settings_game.construction.build_on_slopes || !CanBuildDepotByTileh(dir, tileh)) {
991 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
993 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
996 /* Allow the user to rotate the depot instead of having to destroy it and build it again */
997 bool rotate_existing_depot = false;
998 if (IsRailDepotTile(tile) && railtype == GetRailType(tile)) {
999 CommandCost ret = CheckTileOwnership(tile);
1000 if (ret.Failed()) return ret;
1002 if (dir == GetRailDepotDirection(tile)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
1004 ret = EnsureNoVehicleOnGround(tile);
1005 if (ret.Failed()) return ret;
1007 rotate_existing_depot = true;
1010 if (!rotate_existing_depot) {
1011 cost.AddCost(Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile));
1012 if (cost.Failed()) return cost;
1014 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1016 if (!Depot::CanAllocateItem()) return CMD_ERROR;
1019 if (flags & DC_EXEC) {
1020 if (rotate_existing_depot) {
1021 SetRailDepotExitDirection(tile, dir);
1022 } else {
1023 Depot *d = new Depot(tile);
1024 d->build_date = TimerGameCalendar::date;
1026 MakeRailDepot(tile, _current_company, d->index, dir, railtype);
1027 MakeDefaultName(d);
1029 Company::Get(_current_company)->infrastructure.rail[railtype]++;
1030 DirtyCompanyInfrastructureWindows(_current_company);
1033 MarkTileDirtyByTile(tile);
1034 AddSideToSignalBuffer(tile, INVALID_DIAGDIR, _current_company);
1035 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
1038 cost.AddCost(_price[PR_BUILD_DEPOT_TRAIN]);
1039 cost.AddCost(RailBuildCost(railtype));
1040 return cost;
1044 * Build signals, alternate between double/single, signal/semaphore,
1045 * pre/exit/combo-signals, and what-else not. If the rail piece does not
1046 * have any signals, signal cycling is ignored
1047 * @param flags operation to perform
1048 * @param tile tile where to build the signals
1049 * @param track track-orientation
1050 * @param sigtype type of the signal
1051 * @param sigvar variant of signal type (normal/semaphore)
1052 * @param ctrl_pressed true = override signal/semaphore, or pre/exit/combo signal or toggle variant (CTRL-toggle)
1053 * @param convert_signal convert the present signal type and variant
1054 * @param cycle_start start cycle from this signal type
1055 * @param cycle_stop wrap around after this signal type
1056 * @param num_dir_cycle cycle the signal direction this many times
1057 * @param skip_existing_signals true = don't modify an existing signal but don't fail either, false = always set new signal type
1058 * @param signals_copy used for CmdBuildManySignals() to copy direction of first signal
1059 * @return the cost of this operation or an error
1060 * @todo p2 should be replaced by two bits for "along" and "against" the track.
1062 CommandCost CmdBuildSingleSignal(DoCommandFlag flags, TileIndex tile, Track track, SignalType sigtype, SignalVariant sigvar, bool convert_signal, bool skip_existing_signals, bool ctrl_pressed, SignalType cycle_start, SignalType cycle_stop, uint8_t num_dir_cycle, byte signals_copy)
1064 if (sigtype > SIGTYPE_LAST || sigvar > SIG_SEMAPHORE) return CMD_ERROR;
1065 if (cycle_start > cycle_stop || cycle_stop > SIGTYPE_LAST) return CMD_ERROR;
1067 if (ctrl_pressed) sigvar = (SignalVariant)(sigvar ^ SIG_SEMAPHORE);
1069 /* You can only build signals on plain rail tiles, and the selected track must exist */
1070 if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) ||
1071 !HasTrack(tile, track)) {
1072 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1074 /* Protect against invalid signal copying */
1075 if (signals_copy != 0 && (signals_copy & SignalOnTrack(track)) == 0) return CMD_ERROR;
1077 CommandCost ret = CheckTileOwnership(tile);
1078 if (ret.Failed()) return ret;
1080 /* See if this is a valid track combination for signals (no overlap) */
1081 if (TracksOverlap(GetTrackBits(tile))) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
1083 /* In case we don't want to change an existing signal, return without error. */
1084 if (skip_existing_signals && HasSignalOnTrack(tile, track)) return CommandCost();
1086 /* you can not convert a signal if no signal is on track */
1087 if (convert_signal && !HasSignalOnTrack(tile, track)) return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1089 CommandCost cost;
1090 if (!HasSignalOnTrack(tile, track)) {
1091 /* build new signals */
1092 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS]);
1093 } else {
1094 if (signals_copy != 0 && sigvar != GetSignalVariant(tile, track)) {
1095 /* convert signals <-> semaphores */
1096 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1098 } else if (convert_signal) {
1099 /* convert button pressed */
1100 if (ctrl_pressed || GetSignalVariant(tile, track) != sigvar) {
1101 /* it costs money to change signal variant (light or semaphore) */
1102 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1103 } else {
1104 /* it is free to change signal type (block, exit, entry, combo, path, etc) */
1105 cost = CommandCost();
1108 } else {
1109 /* it is free to change orientation or number of signals on the tile (for block/presignals which allow signals in both directions) */
1110 cost = CommandCost();
1114 if (flags & DC_EXEC) {
1115 Train *v = nullptr;
1116 /* The new/changed signal could block our path. As this can lead to
1117 * stale reservations, we clear the path reservation here and try
1118 * to redo it later on. */
1119 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1120 v = GetTrainForReservation(tile, track);
1121 if (v != nullptr) FreeTrainTrackReservation(v);
1124 if (!HasSignals(tile)) {
1125 /* there are no signals at all on this tile yet */
1126 SetHasSignals(tile, true);
1127 SetSignalStates(tile, 0xF); // all signals are on
1128 SetPresentSignals(tile, 0); // no signals built by default
1129 SetSignalType(tile, track, sigtype);
1130 SetSignalVariant(tile, track, sigvar);
1133 /* Subtract old signal infrastructure count. */
1134 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1136 if (signals_copy == 0) {
1137 if (!HasSignalOnTrack(tile, track)) {
1138 /* build new signals */
1139 SetPresentSignals(tile, GetPresentSignals(tile) | (IsPbsSignal(sigtype) ? KillFirstBit(SignalOnTrack(track)) : SignalOnTrack(track)));
1140 SetSignalType(tile, track, sigtype);
1141 SetSignalVariant(tile, track, sigvar);
1142 while (num_dir_cycle-- > 0) CycleSignalSide(tile, track);
1143 } else {
1144 if (convert_signal) {
1145 /* convert signal button pressed */
1146 if (ctrl_pressed) {
1147 /* toggle the present signal variant: SIG_ELECTRIC <-> SIG_SEMAPHORE */
1148 SetSignalVariant(tile, track, (GetSignalVariant(tile, track) == SIG_ELECTRIC) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1149 /* Query current signal type so the check for PBS signals below works. */
1150 sigtype = GetSignalType(tile, track);
1151 } else {
1152 /* convert the present signal to the chosen type and variant */
1153 SetSignalType(tile, track, sigtype);
1154 SetSignalVariant(tile, track, sigvar);
1155 if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1156 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1160 } else if (ctrl_pressed) {
1161 /* cycle between cycle_start and cycle_end */
1162 sigtype = (SignalType)(GetSignalType(tile, track) + 1);
1164 if (sigtype < cycle_start || sigtype > cycle_stop) sigtype = cycle_start;
1166 SetSignalType(tile, track, sigtype);
1167 if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1168 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1170 } else {
1171 /* cycle the signal side: both -> left -> right -> both -> ... */
1172 CycleSignalSide(tile, track);
1173 /* Query current signal type so the check for PBS signals below works. */
1174 sigtype = GetSignalType(tile, track);
1177 } else {
1178 /* If CmdBuildManySignals is called with copying signals, just copy the
1179 * direction of the first signal given as parameter by CmdBuildManySignals */
1180 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | (signals_copy & SignalOnTrack(track)));
1181 SetSignalVariant(tile, track, sigvar);
1182 SetSignalType(tile, track, sigtype);
1185 /* Add new signal infrastructure count. */
1186 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1187 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1189 if (IsPbsSignal(sigtype)) {
1190 /* PBS signals should show red unless they are on reserved tiles without a train. */
1191 uint mask = GetPresentSignals(tile) & SignalOnTrack(track);
1192 SetSignalStates(tile, (GetSignalStates(tile) & ~mask) | ((HasBit(GetRailReservationTrackBits(tile), track) && EnsureNoVehicleOnGround(tile).Succeeded() ? UINT_MAX : 0) & mask));
1194 MarkTileDirtyByTile(tile);
1195 AddTrackToSignalBuffer(tile, track, _current_company);
1196 YapfNotifyTrackLayoutChange(tile, track);
1197 if (v != nullptr && v->track != TRACK_BIT_DEPOT) {
1198 /* Extend the train's path if it's not stopped or loading, or not at a safe position. */
1199 if (!(((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) || v->current_order.IsType(OT_LOADING)) ||
1200 !IsSafeWaitingPosition(v, v->tile, v->GetVehicleTrackdir(), true, _settings_game.pf.forbid_90_deg)) {
1201 TryPathReserve(v, true);
1206 return cost;
1209 static bool AdvanceSignalAutoFill(TileIndex &tile, Trackdir &trackdir, bool remove)
1211 /* We only process starting tiles of tunnels or bridges so jump to the other end before moving further. */
1212 if (IsTileType(tile, MP_TUNNELBRIDGE)) tile = GetOtherTunnelBridgeEnd(tile);
1214 tile = AddTileIndexDiffCWrap(tile, _trackdelta[trackdir]);
1215 if (tile == INVALID_TILE) return false;
1217 /* Check for track bits on the new tile */
1218 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
1220 if (TracksOverlap(TrackdirBitsToTrackBits(trackdirbits))) return false;
1221 trackdirbits &= TrackdirReachesTrackdirs(trackdir);
1223 /* No track bits, must stop */
1224 if (trackdirbits == TRACKDIR_BIT_NONE) return false;
1226 /* Get the first track dir */
1227 trackdir = RemoveFirstTrackdir(&trackdirbits);
1229 /* Any left? It's a junction so we stop */
1230 if (trackdirbits != TRACKDIR_BIT_NONE) return false;
1232 switch (GetTileType(tile)) {
1233 case MP_RAILWAY:
1234 if (IsRailDepot(tile)) return false;
1235 if (!remove && HasSignalOnTrack(tile, TrackdirToTrack(trackdir))) return false;
1236 break;
1238 case MP_ROAD:
1239 if (!IsLevelCrossing(tile)) return false;
1240 break;
1242 case MP_TUNNELBRIDGE: {
1243 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return false;
1244 if (GetTunnelBridgeDirection(tile) != TrackdirToExitdir(trackdir)) return false;
1245 break;
1248 default: return false;
1250 return true;
1254 * Build many signals by dragging; AutoSignals
1255 * @param flags operation to perform
1256 * @param tile start tile of drag
1257 * @param end_tile end tile of drag
1258 * @param track track-orientation
1259 * @param sigtype default signal type
1260 * @param sigvar signal variant to build
1261 * @param mode true = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1262 * @param remove remove signals?
1263 * @param autofill fill beyond selected stretch?
1264 * @param minimise_gaps false = keep fixed distance, true = minimise gaps between signals
1265 * @param signal_density user defined signals_density
1266 * @return the cost of this operation or an error
1268 static CommandCost CmdSignalTrackHelper(DoCommandFlag flags, TileIndex tile, TileIndex end_tile, Track track, SignalType sigtype, SignalVariant sigvar, bool mode, bool remove, bool autofill, bool minimise_gaps, int signal_density)
1270 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1272 if (end_tile >= Map::Size() || !ValParamTrackOrientation(track)) return CMD_ERROR;
1273 if (signal_density == 0 || signal_density > 20) return CMD_ERROR;
1274 if (!remove && (sigtype > SIGTYPE_LAST || sigvar > SIG_SEMAPHORE)) return CMD_ERROR;
1276 if (!IsPlainRailTile(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1277 TileIndex start_tile = tile;
1279 /* Interpret signal_density as the logical length of said amount of tiles in X/Y direction. */
1280 signal_density *= TILE_AXIAL_DISTANCE;
1282 Trackdir trackdir = TrackToTrackdir(track);
1283 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
1284 if (ret.Failed()) return ret;
1286 track = TrackdirToTrack(trackdir); // trackdir might have changed, keep track in sync
1287 Trackdir start_trackdir = trackdir;
1289 /* Must start on a valid track to be able to avoid loops */
1290 if (!HasTrack(tile, track)) return CMD_ERROR;
1292 byte signals;
1293 /* copy the signal-style of the first rail-piece if existing */
1294 if (HasSignalOnTrack(tile, track)) {
1295 signals = GetPresentSignals(tile) & SignalOnTrack(track);
1296 assert(signals != 0);
1298 /* copy signal/semaphores style (independent of CTRL) */
1299 sigvar = GetSignalVariant(tile, track);
1301 sigtype = GetSignalType(tile, track);
1302 /* Don't but copy entry or exit-signal type */
1303 if (sigtype == SIGTYPE_ENTRY || sigtype == SIGTYPE_EXIT) sigtype = SIGTYPE_BLOCK;
1304 } else { // no signals exist, drag a two-way signal stretch
1305 signals = IsPbsSignal(sigtype) ? SignalAlongTrackdir(trackdir) : SignalOnTrack(track);
1308 byte signal_dir = 0;
1309 if (signals & SignalAlongTrackdir(trackdir)) SetBit(signal_dir, 0);
1310 if (signals & SignalAgainstTrackdir(trackdir)) SetBit(signal_dir, 1);
1312 /* signal_ctr - amount of tiles already processed
1313 * last_used_ctr - amount of tiles before previously placed signal
1314 * signals_density - setting to put signal on every Nth tile (double space on |, -- tracks)
1315 * last_suitable_ctr - amount of tiles before last possible signal place
1316 * last_suitable_tile - last tile where it is possible to place a signal
1317 * last_suitable_trackdir - trackdir of the last tile
1318 **********
1319 * trackdir - trackdir to build with autorail
1320 * semaphores - semaphores or signals
1321 * signals - is there a signal/semaphore on the first tile, copy its style (two-way/single-way)
1322 * and convert all others to semaphore/signal
1323 * remove - 1 remove signals, 0 build signals */
1324 int signal_ctr = 0;
1325 int last_used_ctr = -signal_density; // to force signal at first tile
1326 int last_suitable_ctr = 0;
1327 TileIndex last_suitable_tile = INVALID_TILE;
1328 Trackdir last_suitable_trackdir = INVALID_TRACKDIR;
1329 CommandCost last_error = CMD_ERROR;
1330 bool had_success = false;
1331 auto build_signal = [&](TileIndex tile, Trackdir trackdir, bool test_only) {
1332 /* Pick the correct orientation for the track direction */
1333 byte signals = 0;
1334 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(trackdir);
1335 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(trackdir);
1337 DoCommandFlag do_flags = test_only ? flags & ~DC_EXEC : flags;
1338 CommandCost ret = remove ? Command<CMD_REMOVE_SINGLE_SIGNAL>::Do(do_flags, tile, TrackdirToTrack(trackdir)) : Command<CMD_BUILD_SINGLE_SIGNAL>::Do(do_flags, tile, TrackdirToTrack(trackdir), sigtype, sigvar, false, signal_ctr == 0, mode, SIGTYPE_BLOCK, SIGTYPE_BLOCK, 0, signals);
1340 if (test_only) return ret.Succeeded();
1342 if (ret.Succeeded()) {
1343 had_success = true;
1344 total_cost.AddCost(ret);
1345 } else {
1346 /* The "No railway" error is the least important one. */
1347 if (ret.GetErrorMessage() != STR_ERROR_THERE_IS_NO_RAILROAD_TRACK ||
1348 last_error.GetErrorMessage() == INVALID_STRING_ID) {
1349 last_error = ret;
1352 return ret.Succeeded();
1355 for (;;) {
1356 if (remove) {
1357 /* In remove mode last_* stuff doesn't matter, we simply try to clear every tile. */
1358 build_signal(tile, trackdir, false);
1359 } else if (minimise_gaps) {
1360 /* We're trying to minimize gaps wherever possible, so keep track of last suitable
1361 * position and use it if current gap exceeds required signal density. */
1363 if (signal_ctr > last_used_ctr + signal_density && last_suitable_tile != INVALID_TILE) {
1364 /* We overshot so build a signal in last good location. */
1365 if (build_signal(last_suitable_tile, last_suitable_trackdir, false)) {
1366 last_suitable_tile = INVALID_TILE;
1367 last_used_ctr = last_suitable_ctr;
1371 if (signal_ctr == last_used_ctr + signal_density) {
1372 /* Current gap matches the required density, build a signal. */
1373 if (build_signal(tile, trackdir, false)) {
1374 last_used_ctr = signal_ctr;
1375 last_suitable_tile = INVALID_TILE;
1377 } else {
1378 /* Test tile for a potential signal spot. */
1379 if (build_signal(tile, trackdir, true)) {
1380 last_suitable_tile = tile;
1381 last_suitable_ctr = signal_ctr;
1382 last_suitable_trackdir = trackdir;
1385 } else if (signal_ctr >= last_used_ctr + signal_density) {
1386 /* We're always keeping regular interval between signals so doesn't matter whether we succeed or not. */
1387 build_signal(tile, trackdir, false);
1388 last_used_ctr = signal_ctr;
1391 if (autofill) {
1392 switch (GetTileType(tile)) {
1393 case MP_RAILWAY:
1394 signal_ctr += (IsDiagonalTrackdir(trackdir) ? TILE_AXIAL_DISTANCE : TILE_CORNER_DISTANCE);
1395 break;
1397 case MP_ROAD:
1398 signal_ctr += TILE_AXIAL_DISTANCE;
1399 break;
1401 case MP_TUNNELBRIDGE: {
1402 uint len = (GetTunnelBridgeLength(tile, GetOtherTunnelBridgeEnd(tile)) + 2) * TILE_AXIAL_DISTANCE;
1403 if (remove || minimise_gaps) {
1404 signal_ctr += len;
1405 } else {
1406 /* To keep regular interval we need to emulate placing signals on a bridge.
1407 * We start with TILE_AXIAL_DISTANCE as one bridge tile gets processed in the main loop. */
1408 signal_ctr += TILE_AXIAL_DISTANCE;
1409 for (uint i = TILE_AXIAL_DISTANCE; i < len; i += TILE_AXIAL_DISTANCE) {
1410 if (signal_ctr >= last_used_ctr + signal_density) last_used_ctr = signal_ctr;
1411 signal_ctr += TILE_AXIAL_DISTANCE;
1414 break;
1417 default: break;
1420 if (!AdvanceSignalAutoFill(tile, trackdir, remove)) break;
1422 /* Prevent possible loops */
1423 if (tile == start_tile && trackdir == start_trackdir) break;
1424 } else {
1425 if (tile == end_tile) break;
1427 signal_ctr += (IsDiagonalTrackdir(trackdir) ? TILE_AXIAL_DISTANCE : TILE_CORNER_DISTANCE);
1428 /* toggle railbit for the non-diagonal tracks (|, -- tracks) */
1430 tile += ToTileIndexDiff(_trackdelta[trackdir]);
1431 if (!IsDiagonalTrackdir(trackdir)) ToggleBit(trackdir, 0);
1435 /* We may end up with the current gap exceeding the signal density so fix that if needed. */
1436 if (!remove && minimise_gaps && signal_ctr > last_used_ctr + signal_density && last_suitable_tile != INVALID_TILE) {
1437 build_signal(last_suitable_tile, last_suitable_trackdir, false);
1440 return had_success ? total_cost : last_error;
1444 * Build signals on a stretch of track.
1445 * Stub for the unified signal builder/remover
1446 * @param flags operation to perform
1447 * @param tile start tile of drag
1448 * @param end_tile end tile of drag
1449 * @param track track-orientation
1450 * @param sigtype default signal type
1451 * @param sigvar signal variant to build
1452 * @param mode true = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1453 * @param autofill fill beyond selected stretch?
1454 * @param minimise_gaps false = keep fixed distance, true = minimise gaps between signals
1455 * @param signal_density user defined signals_density
1456 * @return the cost of this operation or an error
1457 * @see CmdSignalTrackHelper
1459 CommandCost CmdBuildSignalTrack(DoCommandFlag flags, TileIndex tile, TileIndex end_tile, Track track, SignalType sigtype, SignalVariant sigvar, bool mode, bool autofill, bool minimise_gaps, byte signal_density)
1461 return CmdSignalTrackHelper(flags, tile, end_tile, track, sigtype, sigvar, mode, false, autofill, minimise_gaps, signal_density);
1465 * Remove signals
1466 * @param flags operation to perform
1467 * @param tile coordinates where signal is being deleted from
1468 * @param track track-orientation
1469 * @return the cost of this operation or an error
1471 CommandCost CmdRemoveSingleSignal(DoCommandFlag flags, TileIndex tile, Track track)
1473 if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) || !HasTrack(tile, track)) {
1474 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1476 if (!HasSignalOnTrack(tile, track)) {
1477 return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1480 /* Only water can remove signals from anyone */
1481 if (_current_company != OWNER_WATER) {
1482 CommandCost ret = CheckTileOwnership(tile);
1483 if (ret.Failed()) return ret;
1486 /* Do it? */
1487 if (flags & DC_EXEC) {
1488 Train *v = nullptr;
1489 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1490 v = GetTrainForReservation(tile, track);
1491 } else if (IsPbsSignal(GetSignalType(tile, track))) {
1492 /* PBS signal, might be the end of a path reservation. */
1493 Trackdir td = TrackToTrackdir(track);
1494 for (int i = 0; v == nullptr && i < 2; i++, td = ReverseTrackdir(td)) {
1495 /* Only test the active signal side. */
1496 if (!HasSignalOnTrackdir(tile, ReverseTrackdir(td))) continue;
1497 TileIndex next = TileAddByDiagDir(tile, TrackdirToExitdir(td));
1498 TrackBits tracks = TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(td));
1499 if (HasReservedTracks(next, tracks)) {
1500 v = GetTrainForReservation(next, TrackBitsToTrack(GetReservedTrackbits(next) & tracks));
1504 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1505 SetPresentSignals(tile, GetPresentSignals(tile) & ~SignalOnTrack(track));
1506 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1507 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1509 /* removed last signal from tile? */
1510 if (GetPresentSignals(tile) == 0) {
1511 SetSignalStates(tile, 0);
1512 SetHasSignals(tile, false);
1513 SetSignalVariant(tile, INVALID_TRACK, SIG_ELECTRIC); // remove any possible semaphores
1516 AddTrackToSignalBuffer(tile, track, GetTileOwner(tile));
1517 YapfNotifyTrackLayoutChange(tile, track);
1518 if (v != nullptr) TryPathReserve(v, false);
1520 MarkTileDirtyByTile(tile);
1523 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_SIGNALS]);
1527 * Remove signals on a stretch of track.
1528 * Stub for the unified signal builder/remover
1529 * @param flags operation to perform
1530 * @param tile start tile of drag
1531 * @param end_tile end tile of drag
1532 * @param track track-orientation
1533 * @param autofill fill beyond selected stretch?
1534 * @return the cost of this operation or an error
1535 * @see CmdSignalTrackHelper
1537 CommandCost CmdRemoveSignalTrack(DoCommandFlag flags, TileIndex tile, TileIndex end_tile, Track track, bool autofill)
1539 return CmdSignalTrackHelper(flags, tile, end_tile, track, SIGTYPE_BLOCK, SIG_ELECTRIC, false, true, autofill, false, 1); // bit 5 is remove bit
1542 /** Update power of train under which is the railtype being converted */
1543 static Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data)
1545 if (v->type != VEH_TRAIN) return nullptr;
1547 TrainList *affected_trains = static_cast<TrainList*>(data);
1548 include(*affected_trains, Train::From(v)->First());
1550 return nullptr;
1554 * Convert one rail type to the other. You can convert normal rail to
1555 * monorail/maglev easily or vice-versa.
1556 * @param flags operation to perform
1557 * @param tile end tile of rail conversion drag
1558 * @param area_start start tile of drag
1559 * @param totype new railtype to convert to.
1560 * @param diagonal build diagonally or not.
1561 * @return the cost of this operation or an error
1563 CommandCost CmdConvertRail(DoCommandFlag flags, TileIndex tile, TileIndex area_start, RailType totype, bool diagonal)
1565 TileIndex area_end = tile;
1567 if (!ValParamRailType(totype)) return CMD_ERROR;
1568 if (area_start >= Map::Size()) return CMD_ERROR;
1570 TrainList affected_trains;
1572 CommandCost cost(EXPENSES_CONSTRUCTION);
1573 CommandCost error = CommandCost(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK); // by default, there is no track to convert.
1574 bool found_convertible_track = false; // whether we actually did convert some track (see bug #7633)
1576 std::unique_ptr<TileIterator> iter = TileIterator::Create(area_start, area_end, diagonal);
1577 for (; (tile = *iter) != INVALID_TILE; ++(*iter)) {
1578 TileType tt = GetTileType(tile);
1580 /* Check if there is any track on tile */
1581 switch (tt) {
1582 case MP_RAILWAY:
1583 break;
1584 case MP_STATION:
1585 if (!HasStationRail(tile)) continue;
1586 break;
1587 case MP_ROAD:
1588 if (!IsLevelCrossing(tile)) continue;
1589 if (RailNoLevelCrossings(totype)) {
1590 error.MakeError(STR_ERROR_CROSSING_DISALLOWED_RAIL);
1591 continue;
1593 break;
1594 case MP_TUNNELBRIDGE:
1595 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) continue;
1596 break;
1597 default: continue;
1600 /* Original railtype we are converting from */
1601 RailType type = GetRailType(tile);
1603 /* Converting to the same type or converting 'hidden' elrail -> rail */
1604 if (type == totype || (_settings_game.vehicle.disable_elrails && totype == RAILTYPE_RAIL && type == RAILTYPE_ELECTRIC)) continue;
1606 /* Trying to convert other's rail */
1607 CommandCost ret = CheckTileOwnership(tile);
1608 if (ret.Failed()) {
1609 error = ret;
1610 continue;
1613 std::vector<Train *> vehicles_affected;
1615 /* Vehicle on the tile when not converting Rail <-> ElRail
1616 * Tunnels and bridges have special check later */
1617 if (tt != MP_TUNNELBRIDGE) {
1618 if (!IsCompatibleRail(type, totype)) {
1619 ret = IsPlainRailTile(tile) ? EnsureNoTrainOnTrackBits(tile, GetTrackBits(tile)) : EnsureNoVehicleOnGround(tile);
1620 if (ret.Failed()) {
1621 error = ret;
1622 continue;
1625 if (flags & DC_EXEC) { // we can safely convert, too
1626 TrackBits reserved = GetReservedTrackbits(tile);
1627 Track track;
1628 while ((track = RemoveFirstTrack(&reserved)) != INVALID_TRACK) {
1629 Train *v = GetTrainForReservation(tile, track);
1630 if (v != nullptr && !HasPowerOnRail(v->railtype, totype)) {
1631 /* No power on new rail type, reroute. */
1632 FreeTrainTrackReservation(v);
1633 vehicles_affected.push_back(v);
1637 /* Update the company infrastructure counters. */
1638 if (!IsRailStationTile(tile) || !IsStationTileBlocked(tile)) {
1639 Company *c = Company::Get(GetTileOwner(tile));
1640 uint num_pieces = IsLevelCrossingTile(tile) ? LEVELCROSSING_TRACKBIT_FACTOR : 1;
1641 if (IsPlainRailTile(tile)) {
1642 TrackBits bits = GetTrackBits(tile);
1643 num_pieces = CountBits(bits);
1644 if (TracksOverlap(bits)) num_pieces *= num_pieces;
1646 c->infrastructure.rail[type] -= num_pieces;
1647 c->infrastructure.rail[totype] += num_pieces;
1648 DirtyCompanyInfrastructureWindows(c->index);
1651 SetRailType(tile, totype);
1652 MarkTileDirtyByTile(tile);
1653 /* update power of train on this tile */
1654 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1658 switch (tt) {
1659 case MP_RAILWAY:
1660 switch (GetRailTileType(tile)) {
1661 case RAIL_TILE_DEPOT:
1662 if (flags & DC_EXEC) {
1663 /* notify YAPF about the track layout change */
1664 YapfNotifyTrackLayoutChange(tile, GetRailDepotTrack(tile));
1666 /* Update build vehicle window related to this depot */
1667 InvalidateWindowData(WC_VEHICLE_DEPOT, tile);
1668 InvalidateWindowData(WC_BUILD_VEHICLE, tile);
1670 found_convertible_track = true;
1671 cost.AddCost(RailConvertCost(type, totype));
1672 break;
1674 default: // RAIL_TILE_NORMAL, RAIL_TILE_SIGNALS
1675 if (flags & DC_EXEC) {
1676 /* notify YAPF about the track layout change */
1677 TrackBits tracks = GetTrackBits(tile);
1678 while (tracks != TRACK_BIT_NONE) {
1679 YapfNotifyTrackLayoutChange(tile, RemoveFirstTrack(&tracks));
1682 found_convertible_track = true;
1683 cost.AddCost(RailConvertCost(type, totype) * CountBits(GetTrackBits(tile)));
1684 break;
1686 break;
1688 case MP_TUNNELBRIDGE: {
1689 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
1691 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
1692 * it would cause assert because of different test and exec runs */
1693 if (endtile < tile) {
1694 if (diagonal) {
1695 if (DiagonalTileArea(area_start, area_end).Contains(endtile)) continue;
1696 } else {
1697 if (OrthogonalTileArea(area_start, area_end).Contains(endtile)) continue;
1701 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
1702 if (!IsCompatibleRail(GetRailType(tile), totype)) {
1703 ret = TunnelBridgeIsFree(tile, endtile);
1704 if (ret.Failed()) {
1705 error = ret;
1706 continue;
1710 if (flags & DC_EXEC) {
1711 Track track = DiagDirToDiagTrack(GetTunnelBridgeDirection(tile));
1712 if (HasTunnelBridgeReservation(tile)) {
1713 Train *v = GetTrainForReservation(tile, track);
1714 if (v != nullptr && !HasPowerOnRail(v->railtype, totype)) {
1715 /* No power on new rail type, reroute. */
1716 FreeTrainTrackReservation(v);
1717 vehicles_affected.push_back(v);
1721 /* Update the company infrastructure counters. */
1722 uint num_pieces = (GetTunnelBridgeLength(tile, endtile) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1723 Company *c = Company::Get(GetTileOwner(tile));
1724 c->infrastructure.rail[GetRailType(tile)] -= num_pieces;
1725 c->infrastructure.rail[totype] += num_pieces;
1726 DirtyCompanyInfrastructureWindows(c->index);
1728 SetRailType(tile, totype);
1729 SetRailType(endtile, totype);
1731 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1732 FindVehicleOnPos(endtile, &affected_trains, &UpdateTrainPowerProc);
1734 YapfNotifyTrackLayoutChange(tile, track);
1735 YapfNotifyTrackLayoutChange(endtile, track);
1737 if (IsBridge(tile)) {
1738 MarkBridgeDirty(tile);
1739 } else {
1740 MarkTileDirtyByTile(tile);
1741 MarkTileDirtyByTile(endtile);
1745 found_convertible_track = true;
1746 cost.AddCost((GetTunnelBridgeLength(tile, endtile) + 2) * RailConvertCost(type, totype));
1747 break;
1750 default: // MP_STATION, MP_ROAD
1751 if (flags & DC_EXEC) {
1752 Track track = ((tt == MP_STATION) ? GetRailStationTrack(tile) : GetCrossingRailTrack(tile));
1753 YapfNotifyTrackLayoutChange(tile, track);
1756 found_convertible_track = true;
1757 cost.AddCost(RailConvertCost(type, totype));
1758 break;
1761 for (uint i = 0; i < vehicles_affected.size(); ++i) {
1762 TryPathReserve(vehicles_affected[i], true);
1766 if (flags & DC_EXEC) {
1767 /* Railtype changed, update trains as when entering different track */
1768 for (Train *v : affected_trains) {
1769 v->ConsistChanged(CCF_TRACK);
1773 return found_convertible_track ? cost : error;
1776 static CommandCost RemoveTrainDepot(TileIndex tile, DoCommandFlag flags)
1778 if (_current_company != OWNER_WATER) {
1779 CommandCost ret = CheckTileOwnership(tile);
1780 if (ret.Failed()) return ret;
1783 CommandCost ret = EnsureNoVehicleOnGround(tile);
1784 if (ret.Failed()) return ret;
1786 if (flags & DC_EXEC) {
1787 /* read variables before the depot is removed */
1788 DiagDirection dir = GetRailDepotDirection(tile);
1789 Owner owner = GetTileOwner(tile);
1790 Train *v = nullptr;
1792 if (HasDepotReservation(tile)) {
1793 v = GetTrainForReservation(tile, DiagDirToDiagTrack(dir));
1794 if (v != nullptr) FreeTrainTrackReservation(v);
1797 Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1798 DirtyCompanyInfrastructureWindows(owner);
1800 delete Depot::GetByTile(tile);
1801 DoClearSquare(tile);
1802 AddSideToSignalBuffer(tile, dir, owner);
1803 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
1804 if (v != nullptr) TryPathReserve(v, true);
1807 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_TRAIN]);
1810 static CommandCost ClearTile_Track(TileIndex tile, DoCommandFlag flags)
1812 CommandCost cost(EXPENSES_CONSTRUCTION);
1814 if (flags & DC_AUTO) {
1815 if (!IsTileOwner(tile, _current_company)) {
1816 return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
1819 if (IsPlainRail(tile)) {
1820 return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
1821 } else {
1822 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
1826 switch (GetRailTileType(tile)) {
1827 case RAIL_TILE_SIGNALS:
1828 case RAIL_TILE_NORMAL: {
1829 Slope tileh = GetTileSlope(tile);
1830 /* Is there flat water on the lower halftile that gets cleared expensively? */
1831 bool water_ground = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh));
1833 TrackBits tracks = GetTrackBits(tile);
1834 while (tracks != TRACK_BIT_NONE) {
1835 Track track = RemoveFirstTrack(&tracks);
1836 CommandCost ret = Command<CMD_REMOVE_SINGLE_RAIL>::Do(flags, tile, track);
1837 if (ret.Failed()) return ret;
1838 cost.AddCost(ret);
1841 /* When bankrupting, don't make water dirty, there could be a ship on lower halftile.
1842 * Same holds for non-companies clearing the tile, e.g. disasters. */
1843 if (water_ground && !(flags & DC_BANKRUPT) && Company::IsValidID(_current_company)) {
1844 CommandCost ret = EnsureNoVehicleOnGround(tile);
1845 if (ret.Failed()) return ret;
1847 /* The track was removed, and left a coast tile. Now also clear the water. */
1848 if (flags & DC_EXEC) {
1849 DoClearSquare(tile);
1851 cost.AddCost(_price[PR_CLEAR_WATER]);
1854 return cost;
1857 case RAIL_TILE_DEPOT:
1858 return RemoveTrainDepot(tile, flags);
1860 default:
1861 return CMD_ERROR;
1866 * Get surface height in point (x,y)
1867 * On tiles with halftile foundations move (x,y) to a safe point wrt. track
1869 static uint GetSaveSlopeZ(uint x, uint y, Track track)
1871 switch (track) {
1872 case TRACK_UPPER: x &= ~0xF; y &= ~0xF; break;
1873 case TRACK_LOWER: x |= 0xF; y |= 0xF; break;
1874 case TRACK_LEFT: x |= 0xF; y &= ~0xF; break;
1875 case TRACK_RIGHT: x &= ~0xF; y |= 0xF; break;
1876 default: break;
1878 return GetSlopePixelZ(x, y);
1881 static void DrawSingleSignal(TileIndex tile, const RailTypeInfo *rti, Track track, SignalState condition, SignalOffsets image, uint pos)
1883 bool side;
1884 switch (_settings_game.construction.train_signal_side) {
1885 case 0: side = false; break; // left
1886 case 2: side = true; break; // right
1887 default: side = _settings_game.vehicle.road_side != 0; break; // driving side
1889 static const Point SignalPositions[2][12] = {
1890 { // Signals on the left side
1891 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1892 { 8, 5}, {14, 1}, { 1, 14}, { 9, 11}, { 1, 0}, { 3, 10},
1893 /* LOWER LOWER X X Y Y */
1894 {11, 4}, {14, 14}, {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
1895 }, { // Signals on the right side
1896 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1897 {14, 1}, {12, 10}, { 4, 6}, { 1, 14}, {10, 4}, { 0, 1},
1898 /* LOWER LOWER X X Y Y */
1899 {14, 14}, { 5, 12}, {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
1903 uint x = TileX(tile) * TILE_SIZE + SignalPositions[side][pos].x;
1904 uint y = TileY(tile) * TILE_SIZE + SignalPositions[side][pos].y;
1906 SignalType type = GetSignalType(tile, track);
1907 SignalVariant variant = GetSignalVariant(tile, track);
1909 SpriteID sprite = GetCustomSignalSprite(rti, tile, type, variant, condition);
1910 if (sprite != 0) {
1911 sprite += image;
1912 } else {
1913 /* Normal electric signals are stored in a different sprite block than all other signals. */
1914 sprite = (type == SIGTYPE_BLOCK && variant == SIG_ELECTRIC) ? SPR_ORIGINAL_SIGNALS_BASE : SPR_SIGNALS_BASE - 16;
1915 sprite += type * 16 + variant * 64 + image * 2 + condition + (type > SIGTYPE_LAST_NOPBS ? 64 : 0);
1918 AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, BB_HEIGHT_UNDER_BRIDGE, GetSaveSlopeZ(x, y, track));
1921 static uint32_t _drawtile_track_palette;
1925 /** Offsets for drawing fences */
1926 struct FenceOffset {
1927 Corner height_ref; //!< Corner to use height offset from.
1928 int x_offs; //!< Bounding box X offset.
1929 int y_offs; //!< Bounding box Y offset.
1930 int x_size; //!< Bounding box X size.
1931 int y_size; //!< Bounding box Y size.
1934 /** Offsets for drawing fences */
1935 static FenceOffset _fence_offsets[] = {
1936 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_FLAT_X_NW
1937 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_FLAT_Y_NE
1938 { CORNER_W, 8, 8, 1, 1 }, // RFO_FLAT_LEFT
1939 { CORNER_N, 8, 8, 1, 1 }, // RFO_FLAT_UPPER
1940 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_SW_NW
1941 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_SE_NE
1942 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_NE_NW
1943 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_NW_NE
1944 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_FLAT_X_SE
1945 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_FLAT_Y_SW
1946 { CORNER_E, 8, 8, 1, 1 }, // RFO_FLAT_RIGHT
1947 { CORNER_S, 8, 8, 1, 1 }, // RFO_FLAT_LOWER
1948 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_SW_SE
1949 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_SE_SW
1950 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_NE_SE
1951 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_NW_SW
1955 * Draw a track fence.
1956 * @param ti Tile drawing information.
1957 * @param base_image First fence sprite.
1958 * @param num_sprites Number of fence sprites.
1959 * @param rfo Fence to draw.
1961 static void DrawTrackFence(const TileInfo *ti, SpriteID base_image, uint num_sprites, RailFenceOffset rfo)
1963 int z = ti->z;
1964 if (_fence_offsets[rfo].height_ref != CORNER_INVALID) {
1965 z += GetSlopePixelZInCorner(RemoveHalftileSlope(ti->tileh), _fence_offsets[rfo].height_ref);
1967 AddSortableSpriteToDraw(base_image + (rfo % num_sprites), _drawtile_track_palette,
1968 ti->x + _fence_offsets[rfo].x_offs,
1969 ti->y + _fence_offsets[rfo].y_offs,
1970 _fence_offsets[rfo].x_size,
1971 _fence_offsets[rfo].y_size,
1972 4, z);
1976 * Draw fence at NW border matching the tile slope.
1978 static void DrawTrackFence_NW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1980 RailFenceOffset rfo = RFO_FLAT_X_NW;
1981 if (ti->tileh & SLOPE_NW) rfo = (ti->tileh & SLOPE_W) ? RFO_SLOPE_SW_NW : RFO_SLOPE_NE_NW;
1982 DrawTrackFence(ti, base_image, num_sprites, rfo);
1986 * Draw fence at SE border matching the tile slope.
1988 static void DrawTrackFence_SE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1990 RailFenceOffset rfo = RFO_FLAT_X_SE;
1991 if (ti->tileh & SLOPE_SE) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SW_SE : RFO_SLOPE_NE_SE;
1992 DrawTrackFence(ti, base_image, num_sprites, rfo);
1996 * Draw fence at NE border matching the tile slope.
1998 static void DrawTrackFence_NE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2000 RailFenceOffset rfo = RFO_FLAT_Y_NE;
2001 if (ti->tileh & SLOPE_NE) rfo = (ti->tileh & SLOPE_E) ? RFO_SLOPE_SE_NE : RFO_SLOPE_NW_NE;
2002 DrawTrackFence(ti, base_image, num_sprites, rfo);
2006 * Draw fence at SW border matching the tile slope.
2008 static void DrawTrackFence_SW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2010 RailFenceOffset rfo = RFO_FLAT_Y_SW;
2011 if (ti->tileh & SLOPE_SW) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SE_SW : RFO_SLOPE_NW_SW;
2012 DrawTrackFence(ti, base_image, num_sprites, rfo);
2016 * Draw track fences.
2017 * @param ti Tile drawing information.
2018 * @param rti Rail type information.
2020 static void DrawTrackDetails(const TileInfo *ti, const RailTypeInfo *rti)
2022 /* Base sprite for track fences.
2023 * Note: Halftile slopes only have fences on the upper part. */
2024 uint num_sprites = 0;
2025 SpriteID base_image = GetCustomRailSprite(rti, ti->tile, RTSG_FENCES, IsHalftileSlope(ti->tileh) ? TCX_UPPER_HALFTILE : TCX_NORMAL, &num_sprites);
2026 if (base_image == 0) {
2027 base_image = SPR_TRACK_FENCE_FLAT_X;
2028 num_sprites = 8;
2031 assert(num_sprites > 0);
2033 switch (GetRailGroundType(ti->tile)) {
2034 case RAIL_GROUND_FENCE_NW: DrawTrackFence_NW(ti, base_image, num_sprites); break;
2035 case RAIL_GROUND_FENCE_SE: DrawTrackFence_SE(ti, base_image, num_sprites); break;
2036 case RAIL_GROUND_FENCE_SENW: DrawTrackFence_NW(ti, base_image, num_sprites);
2037 DrawTrackFence_SE(ti, base_image, num_sprites); break;
2038 case RAIL_GROUND_FENCE_NE: DrawTrackFence_NE(ti, base_image, num_sprites); break;
2039 case RAIL_GROUND_FENCE_SW: DrawTrackFence_SW(ti, base_image, num_sprites); break;
2040 case RAIL_GROUND_FENCE_NESW: DrawTrackFence_NE(ti, base_image, num_sprites);
2041 DrawTrackFence_SW(ti, base_image, num_sprites); break;
2042 case RAIL_GROUND_FENCE_VERT1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2043 case RAIL_GROUND_FENCE_VERT2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2044 case RAIL_GROUND_FENCE_HORIZ1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2045 case RAIL_GROUND_FENCE_HORIZ2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2046 case RAIL_GROUND_WATER: {
2047 Corner track_corner;
2048 if (IsHalftileSlope(ti->tileh)) {
2049 /* Steep slope or one-corner-raised slope with halftile foundation */
2050 track_corner = GetHalftileSlopeCorner(ti->tileh);
2051 } else {
2052 /* Three-corner-raised slope */
2053 track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2055 switch (track_corner) {
2056 case CORNER_W: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2057 case CORNER_S: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2058 case CORNER_E: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2059 case CORNER_N: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2060 default: NOT_REACHED();
2062 break;
2064 default: break;
2068 /* SubSprite for drawing the track halftile of 'three-corners-raised'-sloped rail sprites. */
2069 static const int INF = 1000; // big number compared to tilesprite size
2070 static const SubSprite _halftile_sub_sprite[4] = {
2071 { -INF , -INF , 32 - 33, INF }, // CORNER_W, clip 33 pixels from right
2072 { -INF , 0 + 7, INF , INF }, // CORNER_S, clip 7 pixels from top
2073 { -31 + 33, -INF , INF , INF }, // CORNER_E, clip 33 pixels from left
2074 { -INF , -INF , INF , 30 - 23 } // CORNER_N, clip 23 pixels from bottom
2077 static inline void DrawTrackSprite(SpriteID sprite, PaletteID pal, const TileInfo *ti, Slope s)
2079 DrawGroundSprite(sprite, pal, nullptr, 0, (ti->tileh & s) ? -8 : 0);
2082 static void DrawTrackBitsOverlay(TileInfo *ti, TrackBits track, const RailTypeInfo *rti)
2084 RailGroundType rgt = GetRailGroundType(ti->tile);
2085 Foundation f = GetRailFoundation(ti->tileh, track);
2086 Corner halftile_corner = CORNER_INVALID;
2088 if (IsNonContinuousFoundation(f)) {
2089 /* Save halftile corner */
2090 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2091 /* Draw lower part first */
2092 track &= ~CornerToTrackBits(halftile_corner);
2093 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2096 DrawFoundation(ti, f);
2097 /* DrawFoundation modifies ti */
2099 /* Draw ground */
2100 if (rgt == RAIL_GROUND_WATER) {
2101 if (track != TRACK_BIT_NONE || IsSteepSlope(ti->tileh)) {
2102 /* three-corner-raised slope or steep slope with track on upper part */
2103 DrawShoreTile(ti->tileh);
2104 } else {
2105 /* single-corner-raised slope with track on upper part */
2106 DrawGroundSprite(SPR_FLAT_WATER_TILE, PAL_NONE);
2108 } else {
2109 SpriteID image;
2111 switch (rgt) {
2112 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2113 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2114 default: image = SPR_FLAT_GRASS_TILE; break;
2117 image += SlopeToSpriteOffset(ti->tileh);
2119 DrawGroundSprite(image, PAL_NONE);
2122 bool no_combine = ti->tileh == SLOPE_FLAT && HasBit(rti->flags, RTF_NO_SPRITE_COMBINE);
2123 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2124 SpriteID ground = GetCustomRailSprite(rti, ti->tile, no_combine ? RTSG_GROUND_COMPLETE : RTSG_GROUND);
2125 TrackBits pbs = _settings_client.gui.show_track_reservation ? GetRailReservationTrackBits(ti->tile) : TRACK_BIT_NONE;
2127 if (track == TRACK_BIT_NONE) {
2128 /* Half-tile foundation, no track here? */
2129 } else if (no_combine) {
2130 /* Use trackbits as direct index from ground sprite, subtract 1
2131 * because there is no sprite for no bits. */
2132 DrawGroundSprite(ground + track - 1, PAL_NONE);
2134 /* Draw reserved track bits */
2135 if (pbs & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2136 if (pbs & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2137 if (pbs & TRACK_BIT_UPPER) DrawTrackSprite(overlay + RTO_N, PALETTE_CRASH, ti, SLOPE_N);
2138 if (pbs & TRACK_BIT_LOWER) DrawTrackSprite(overlay + RTO_S, PALETTE_CRASH, ti, SLOPE_S);
2139 if (pbs & TRACK_BIT_RIGHT) DrawTrackSprite(overlay + RTO_E, PALETTE_CRASH, ti, SLOPE_E);
2140 if (pbs & TRACK_BIT_LEFT) DrawTrackSprite(overlay + RTO_W, PALETTE_CRASH, ti, SLOPE_W);
2141 } else if (ti->tileh == SLOPE_NW && track == TRACK_BIT_Y) {
2142 DrawGroundSprite(ground + RTO_SLOPE_NW, PAL_NONE);
2143 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NW, PALETTE_CRASH);
2144 } else if (ti->tileh == SLOPE_NE && track == TRACK_BIT_X) {
2145 DrawGroundSprite(ground + RTO_SLOPE_NE, PAL_NONE);
2146 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NE, PALETTE_CRASH);
2147 } else if (ti->tileh == SLOPE_SE && track == TRACK_BIT_Y) {
2148 DrawGroundSprite(ground + RTO_SLOPE_SE, PAL_NONE);
2149 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SE, PALETTE_CRASH);
2150 } else if (ti->tileh == SLOPE_SW && track == TRACK_BIT_X) {
2151 DrawGroundSprite(ground + RTO_SLOPE_SW, PAL_NONE);
2152 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SW, PALETTE_CRASH);
2153 } else {
2154 switch (track) {
2155 /* Draw single ground sprite when not overlapping. No track overlay
2156 * is necessary for these sprites. */
2157 case TRACK_BIT_X: DrawGroundSprite(ground + RTO_X, PAL_NONE); break;
2158 case TRACK_BIT_Y: DrawGroundSprite(ground + RTO_Y, PAL_NONE); break;
2159 case TRACK_BIT_UPPER: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N); break;
2160 case TRACK_BIT_LOWER: DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2161 case TRACK_BIT_RIGHT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E); break;
2162 case TRACK_BIT_LEFT: DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2163 case TRACK_BIT_CROSS: DrawGroundSprite(ground + RTO_CROSSING_XY, PAL_NONE); break;
2164 case TRACK_BIT_HORZ: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N);
2165 DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2166 case TRACK_BIT_VERT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E);
2167 DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2169 default:
2170 /* We're drawing a junction tile */
2171 if ((track & TRACK_BIT_3WAY_NE) == 0) {
2172 DrawGroundSprite(ground + RTO_JUNCTION_SW, PAL_NONE);
2173 } else if ((track & TRACK_BIT_3WAY_SW) == 0) {
2174 DrawGroundSprite(ground + RTO_JUNCTION_NE, PAL_NONE);
2175 } else if ((track & TRACK_BIT_3WAY_NW) == 0) {
2176 DrawGroundSprite(ground + RTO_JUNCTION_SE, PAL_NONE);
2177 } else if ((track & TRACK_BIT_3WAY_SE) == 0) {
2178 DrawGroundSprite(ground + RTO_JUNCTION_NW, PAL_NONE);
2179 } else {
2180 DrawGroundSprite(ground + RTO_JUNCTION_NSEW, PAL_NONE);
2183 /* Mask out PBS bits as we shall draw them afterwards anyway. */
2184 track &= ~pbs;
2186 /* Draw regular track bits */
2187 if (track & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PAL_NONE);
2188 if (track & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PAL_NONE);
2189 if (track & TRACK_BIT_UPPER) DrawGroundSprite(overlay + RTO_N, PAL_NONE);
2190 if (track & TRACK_BIT_LOWER) DrawGroundSprite(overlay + RTO_S, PAL_NONE);
2191 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(overlay + RTO_E, PAL_NONE);
2192 if (track & TRACK_BIT_LEFT) DrawGroundSprite(overlay + RTO_W, PAL_NONE);
2195 /* Draw reserved track bits */
2196 if (pbs & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2197 if (pbs & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2198 if (pbs & TRACK_BIT_UPPER) DrawTrackSprite(overlay + RTO_N, PALETTE_CRASH, ti, SLOPE_N);
2199 if (pbs & TRACK_BIT_LOWER) DrawTrackSprite(overlay + RTO_S, PALETTE_CRASH, ti, SLOPE_S);
2200 if (pbs & TRACK_BIT_RIGHT) DrawTrackSprite(overlay + RTO_E, PALETTE_CRASH, ti, SLOPE_E);
2201 if (pbs & TRACK_BIT_LEFT) DrawTrackSprite(overlay + RTO_W, PALETTE_CRASH, ti, SLOPE_W);
2204 if (IsValidCorner(halftile_corner)) {
2205 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2206 overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY, TCX_UPPER_HALFTILE);
2207 ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND, TCX_UPPER_HALFTILE);
2209 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2210 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2212 SpriteID image;
2213 switch (rgt) {
2214 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2215 case RAIL_GROUND_ICE_DESERT:
2216 case RAIL_GROUND_HALF_SNOW: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2217 default: image = SPR_FLAT_GRASS_TILE; break;
2220 image += SlopeToSpriteOffset(fake_slope);
2222 DrawGroundSprite(image, PAL_NONE, &(_halftile_sub_sprite[halftile_corner]));
2224 track = CornerToTrackBits(halftile_corner);
2226 int offset;
2227 switch (track) {
2228 default: NOT_REACHED();
2229 case TRACK_BIT_UPPER: offset = RTO_N; break;
2230 case TRACK_BIT_LOWER: offset = RTO_S; break;
2231 case TRACK_BIT_RIGHT: offset = RTO_E; break;
2232 case TRACK_BIT_LEFT: offset = RTO_W; break;
2235 DrawTrackSprite(ground + offset, PAL_NONE, ti, fake_slope);
2236 if (_settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, track)) {
2237 DrawTrackSprite(overlay + offset, PALETTE_CRASH, ti, fake_slope);
2243 * Draw ground sprite and track bits
2244 * @param ti TileInfo
2245 * @param track TrackBits to draw
2247 static void DrawTrackBits(TileInfo *ti, TrackBits track)
2249 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2251 if (rti->UsesOverlay()) {
2252 DrawTrackBitsOverlay(ti, track, rti);
2253 return;
2256 RailGroundType rgt = GetRailGroundType(ti->tile);
2257 Foundation f = GetRailFoundation(ti->tileh, track);
2258 Corner halftile_corner = CORNER_INVALID;
2260 if (IsNonContinuousFoundation(f)) {
2261 /* Save halftile corner */
2262 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2263 /* Draw lower part first */
2264 track &= ~CornerToTrackBits(halftile_corner);
2265 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2268 DrawFoundation(ti, f);
2269 /* DrawFoundation modifies ti */
2271 SpriteID image;
2272 PaletteID pal = PAL_NONE;
2273 const SubSprite *sub = nullptr;
2274 bool junction = false;
2276 /* Select the sprite to use. */
2277 if (track == 0) {
2278 /* Clear ground (only track on halftile foundation) */
2279 if (rgt == RAIL_GROUND_WATER) {
2280 if (IsSteepSlope(ti->tileh)) {
2281 DrawShoreTile(ti->tileh);
2282 image = 0;
2283 } else {
2284 image = SPR_FLAT_WATER_TILE;
2286 } else {
2287 switch (rgt) {
2288 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2289 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2290 default: image = SPR_FLAT_GRASS_TILE; break;
2292 image += SlopeToSpriteOffset(ti->tileh);
2294 } else {
2295 if (ti->tileh != SLOPE_FLAT) {
2296 /* track on non-flat ground */
2297 image = _track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.track_y;
2298 } else {
2299 /* track on flat ground */
2300 switch (track) {
2301 /* single track, select combined track + ground sprite*/
2302 case TRACK_BIT_Y: image = rti->base_sprites.track_y; break;
2303 case TRACK_BIT_X: image = rti->base_sprites.track_y + 1; break;
2304 case TRACK_BIT_UPPER: image = rti->base_sprites.track_y + 2; break;
2305 case TRACK_BIT_LOWER: image = rti->base_sprites.track_y + 3; break;
2306 case TRACK_BIT_RIGHT: image = rti->base_sprites.track_y + 4; break;
2307 case TRACK_BIT_LEFT: image = rti->base_sprites.track_y + 5; break;
2308 case TRACK_BIT_CROSS: image = rti->base_sprites.track_y + 6; break;
2310 /* double diagonal track, select combined track + ground sprite*/
2311 case TRACK_BIT_HORZ: image = rti->base_sprites.track_ns; break;
2312 case TRACK_BIT_VERT: image = rti->base_sprites.track_ns + 1; break;
2314 /* junction, select only ground sprite, handle track sprite later */
2315 default:
2316 junction = true;
2317 if ((track & TRACK_BIT_3WAY_NE) == 0) { image = rti->base_sprites.ground; break; }
2318 if ((track & TRACK_BIT_3WAY_SW) == 0) { image = rti->base_sprites.ground + 1; break; }
2319 if ((track & TRACK_BIT_3WAY_NW) == 0) { image = rti->base_sprites.ground + 2; break; }
2320 if ((track & TRACK_BIT_3WAY_SE) == 0) { image = rti->base_sprites.ground + 3; break; }
2321 image = rti->base_sprites.ground + 4;
2322 break;
2326 switch (rgt) {
2327 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2328 case RAIL_GROUND_ICE_DESERT: image += rti->snow_offset; break;
2329 case RAIL_GROUND_WATER: {
2330 /* three-corner-raised slope */
2331 DrawShoreTile(ti->tileh);
2332 Corner track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2333 sub = &(_halftile_sub_sprite[track_corner]);
2334 break;
2336 default: break;
2340 if (image != 0) DrawGroundSprite(image, pal, sub);
2342 /* Draw track pieces individually for junction tiles */
2343 if (junction) {
2344 if (track & TRACK_BIT_X) DrawGroundSprite(rti->base_sprites.single_x, PAL_NONE);
2345 if (track & TRACK_BIT_Y) DrawGroundSprite(rti->base_sprites.single_y, PAL_NONE);
2346 if (track & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PAL_NONE);
2347 if (track & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PAL_NONE);
2348 if (track & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PAL_NONE);
2349 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PAL_NONE);
2352 /* PBS debugging, draw reserved tracks darker */
2353 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation) {
2354 /* Get reservation, but mask track on halftile slope */
2355 TrackBits pbs = GetRailReservationTrackBits(ti->tile) & track;
2356 if (pbs & TRACK_BIT_X) {
2357 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2358 DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
2359 } else {
2360 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2363 if (pbs & TRACK_BIT_Y) {
2364 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2365 DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
2366 } else {
2367 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2370 if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_N ? -(int)TILE_HEIGHT : 0);
2371 if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_S ? -(int)TILE_HEIGHT : 0);
2372 if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_W ? -(int)TILE_HEIGHT : 0);
2373 if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_E ? -(int)TILE_HEIGHT : 0);
2376 if (IsValidCorner(halftile_corner)) {
2377 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2379 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2380 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2381 image = _track_sloped_sprites[fake_slope - 1] + rti->base_sprites.track_y;
2382 pal = PAL_NONE;
2383 switch (rgt) {
2384 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2385 case RAIL_GROUND_ICE_DESERT:
2386 case RAIL_GROUND_HALF_SNOW: image += rti->snow_offset; break; // higher part has snow in this case too
2387 default: break;
2389 DrawGroundSprite(image, pal, &(_halftile_sub_sprite[halftile_corner]));
2391 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
2392 static const byte _corner_to_track_sprite[] = {3, 1, 2, 0};
2393 DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, -(int)TILE_HEIGHT);
2398 static void DrawSignals(TileIndex tile, TrackBits rails, const RailTypeInfo *rti)
2400 auto MAYBE_DRAW_SIGNAL = [&](byte signalbit, SignalOffsets image, uint pos, Track track) {
2401 if (IsSignalPresent(tile, signalbit)) DrawSingleSignal(tile, rti, track, GetSingleSignalState(tile, signalbit), image, pos);
2404 if (!(rails & TRACK_BIT_Y)) {
2405 if (!(rails & TRACK_BIT_X)) {
2406 if (rails & TRACK_BIT_LEFT) {
2407 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTH, 0, TRACK_LEFT);
2408 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTH, 1, TRACK_LEFT);
2410 if (rails & TRACK_BIT_RIGHT) {
2411 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_NORTH, 2, TRACK_RIGHT);
2412 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_SOUTH, 3, TRACK_RIGHT);
2414 if (rails & TRACK_BIT_UPPER) {
2415 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_WEST, 4, TRACK_UPPER);
2416 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_EAST, 5, TRACK_UPPER);
2418 if (rails & TRACK_BIT_LOWER) {
2419 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_WEST, 6, TRACK_LOWER);
2420 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_EAST, 7, TRACK_LOWER);
2422 } else {
2423 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHWEST, 8, TRACK_X);
2424 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHEAST, 9, TRACK_X);
2426 } else {
2427 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHEAST, 10, TRACK_Y);
2428 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHWEST, 11, TRACK_Y);
2432 static void DrawTile_Track(TileInfo *ti)
2434 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2436 _drawtile_track_palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
2438 if (IsPlainRail(ti->tile)) {
2439 TrackBits rails = GetTrackBits(ti->tile);
2441 DrawTrackBits(ti, rails);
2443 if (HasBit(_display_opt, DO_FULL_DETAIL)) DrawTrackDetails(ti, rti);
2445 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2447 if (HasSignals(ti->tile)) DrawSignals(ti->tile, rails, rti);
2448 } else {
2449 /* draw depot */
2450 const DrawTileSprites *dts;
2451 PaletteID pal = PAL_NONE;
2452 SpriteID relocation;
2454 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
2456 if (IsInvisibilitySet(TO_BUILDINGS)) {
2457 /* Draw rail instead of depot */
2458 dts = &_depot_invisible_gfx_table[GetRailDepotDirection(ti->tile)];
2459 } else {
2460 dts = &_depot_gfx_table[GetRailDepotDirection(ti->tile)];
2463 SpriteID image;
2464 if (rti->UsesOverlay()) {
2465 image = SPR_FLAT_GRASS_TILE;
2466 } else {
2467 image = dts->ground.sprite;
2468 if (image != SPR_FLAT_GRASS_TILE) image += rti->GetRailtypeSpriteOffset();
2471 /* Adjust ground tile for desert and snow. */
2472 if (IsSnowRailGround(ti->tile)) {
2473 if (image != SPR_FLAT_GRASS_TILE) {
2474 image += rti->snow_offset; // tile with tracks
2475 } else {
2476 image = SPR_FLAT_SNOW_DESERT_TILE; // flat ground
2480 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, _drawtile_track_palette));
2482 if (rti->UsesOverlay()) {
2483 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2485 switch (GetRailDepotDirection(ti->tile)) {
2486 case DIAGDIR_NE:
2487 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2488 [[fallthrough]];
2489 case DIAGDIR_SW:
2490 DrawGroundSprite(ground + RTO_X, PAL_NONE);
2491 break;
2492 case DIAGDIR_NW:
2493 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2494 [[fallthrough]];
2495 case DIAGDIR_SE:
2496 DrawGroundSprite(ground + RTO_Y, PAL_NONE);
2497 break;
2498 default:
2499 break;
2502 if (_settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2503 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2505 switch (GetRailDepotDirection(ti->tile)) {
2506 case DIAGDIR_NE:
2507 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2508 [[fallthrough]];
2509 case DIAGDIR_SW:
2510 DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2511 break;
2512 case DIAGDIR_NW:
2513 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2514 [[fallthrough]];
2515 case DIAGDIR_SE:
2516 DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2517 break;
2518 default:
2519 break;
2522 } else {
2523 /* PBS debugging, draw reserved tracks darker */
2524 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2525 switch (GetRailDepotDirection(ti->tile)) {
2526 case DIAGDIR_NE:
2527 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2528 [[fallthrough]];
2529 case DIAGDIR_SW:
2530 DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
2531 break;
2532 case DIAGDIR_NW:
2533 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2534 [[fallthrough]];
2535 case DIAGDIR_SE:
2536 DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
2537 break;
2538 default:
2539 break;
2543 int depot_sprite = GetCustomRailSprite(rti, ti->tile, RTSG_DEPOT);
2544 relocation = depot_sprite != 0 ? depot_sprite - SPR_RAIL_DEPOT_SE_1 : rti->GetRailtypeSpriteOffset();
2546 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2548 DrawRailTileSeq(ti, dts, TO_BUILDINGS, relocation, 0, _drawtile_track_palette);
2550 DrawBridgeMiddle(ti);
2553 void DrawTrainDepotSprite(int x, int y, int dir, RailType railtype)
2555 const DrawTileSprites *dts = &_depot_gfx_table[dir];
2556 const RailTypeInfo *rti = GetRailTypeInfo(railtype);
2557 SpriteID image = rti->UsesOverlay() ? SPR_FLAT_GRASS_TILE : dts->ground.sprite;
2558 uint32_t offset = rti->GetRailtypeSpriteOffset();
2560 if (image != SPR_FLAT_GRASS_TILE) image += offset;
2561 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
2563 DrawSprite(image, PAL_NONE, x, y);
2565 if (rti->UsesOverlay()) {
2566 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
2568 switch (dir) {
2569 case DIAGDIR_SW: DrawSprite(ground + RTO_X, PAL_NONE, x, y); break;
2570 case DIAGDIR_SE: DrawSprite(ground + RTO_Y, PAL_NONE, x, y); break;
2571 default: break;
2574 int depot_sprite = GetCustomRailSprite(rti, INVALID_TILE, RTSG_DEPOT);
2575 if (depot_sprite != 0) offset = depot_sprite - SPR_RAIL_DEPOT_SE_1;
2577 DrawRailTileSeqInGUI(x, y, dts, offset, 0, palette);
2580 static int GetSlopePixelZ_Track(TileIndex tile, uint x, uint y, bool)
2582 if (IsPlainRail(tile)) {
2583 int z;
2584 Slope tileh = GetTilePixelSlope(tile, &z);
2585 if (tileh == SLOPE_FLAT) return z;
2587 z += ApplyPixelFoundationToSlope(GetRailFoundation(tileh, GetTrackBits(tile)), &tileh);
2588 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
2589 } else {
2590 return GetTileMaxPixelZ(tile);
2594 static Foundation GetFoundation_Track(TileIndex tile, Slope tileh)
2596 return IsPlainRail(tile) ? GetRailFoundation(tileh, GetTrackBits(tile)) : FlatteningFoundation(tileh);
2599 static void TileLoop_Track(TileIndex tile)
2601 RailGroundType old_ground = GetRailGroundType(tile);
2602 RailGroundType new_ground;
2604 if (old_ground == RAIL_GROUND_WATER) {
2605 TileLoop_Water(tile);
2606 return;
2609 switch (_settings_game.game_creation.landscape) {
2610 case LT_ARCTIC: {
2611 int z;
2612 Slope slope = GetTileSlope(tile, &z);
2613 bool half = false;
2615 /* for non-flat track, use lower part of track
2616 * in other cases, use the highest part with track */
2617 if (IsPlainRail(tile)) {
2618 TrackBits track = GetTrackBits(tile);
2619 Foundation f = GetRailFoundation(slope, track);
2621 switch (f) {
2622 case FOUNDATION_NONE:
2623 /* no foundation - is the track on the upper side of three corners raised tile? */
2624 if (IsSlopeWithThreeCornersRaised(slope)) z++;
2625 break;
2627 case FOUNDATION_INCLINED_X:
2628 case FOUNDATION_INCLINED_Y:
2629 /* sloped track - is it on a steep slope? */
2630 if (IsSteepSlope(slope)) z++;
2631 break;
2633 case FOUNDATION_STEEP_LOWER:
2634 /* only lower part of steep slope */
2635 z++;
2636 break;
2638 default:
2639 /* if it is a steep slope, then there is a track on higher part */
2640 if (IsSteepSlope(slope)) z++;
2641 z++;
2642 break;
2645 half = IsInsideMM(f, FOUNDATION_STEEP_BOTH, FOUNDATION_HALFTILE_N + 1);
2646 } else {
2647 /* is the depot on a non-flat tile? */
2648 if (slope != SLOPE_FLAT) z++;
2651 /* 'z' is now the lowest part of the highest track bit -
2652 * for sloped track, it is 'z' of lower part
2653 * for two track bits, it is 'z' of higher track bit
2654 * For non-continuous foundations (and STEEP_BOTH), 'half' is set */
2655 if (z > GetSnowLine()) {
2656 if (half && z - GetSnowLine() == 1) {
2657 /* track on non-continuous foundation, lower part is not under snow */
2658 new_ground = RAIL_GROUND_HALF_SNOW;
2659 } else {
2660 new_ground = RAIL_GROUND_ICE_DESERT;
2662 goto set_ground;
2664 break;
2667 case LT_TROPIC:
2668 if (GetTropicZone(tile) == TROPICZONE_DESERT) {
2669 new_ground = RAIL_GROUND_ICE_DESERT;
2670 goto set_ground;
2672 break;
2675 new_ground = RAIL_GROUND_GRASS;
2677 if (IsPlainRail(tile) && old_ground != RAIL_GROUND_BARREN) { // wait until bottom is green
2678 /* determine direction of fence */
2679 TrackBits rail = GetTrackBits(tile);
2681 Owner owner = GetTileOwner(tile);
2682 byte fences = 0;
2684 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
2685 static const TrackBits dir_to_trackbits[DIAGDIR_END] = {TRACK_BIT_3WAY_NE, TRACK_BIT_3WAY_SE, TRACK_BIT_3WAY_SW, TRACK_BIT_3WAY_NW};
2687 /* Track bit on this edge => no fence. */
2688 if ((rail & dir_to_trackbits[d]) != TRACK_BIT_NONE) continue;
2690 TileIndex tile2 = tile + TileOffsByDiagDir(d);
2692 /* Show fences if it's a house, industry, object, road, tunnelbridge or not owned by us. */
2693 if (!IsValidTile(tile2) || IsTileType(tile2, MP_HOUSE) || IsTileType(tile2, MP_INDUSTRY) ||
2694 IsTileType(tile2, MP_ROAD) || (IsTileType(tile2, MP_OBJECT) && !IsObjectType(tile2, OBJECT_OWNED_LAND)) || IsTileType(tile2, MP_TUNNELBRIDGE) || !IsTileOwner(tile2, owner)) {
2695 fences |= 1 << d;
2699 switch (fences) {
2700 case 0: break;
2701 case (1 << DIAGDIR_NE): new_ground = RAIL_GROUND_FENCE_NE; break;
2702 case (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_SE; break;
2703 case (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_SW; break;
2704 case (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_NW; break;
2705 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_NESW; break;
2706 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_SENW; break;
2707 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_VERT1; break;
2708 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_HORIZ2; break;
2709 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_HORIZ1; break;
2710 case (1 << DIAGDIR_SW) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_VERT2; break;
2711 default: NOT_REACHED();
2715 set_ground:
2716 if (old_ground != new_ground) {
2717 SetRailGroundType(tile, new_ground);
2718 MarkTileDirtyByTile(tile);
2723 static TrackStatus GetTileTrackStatus_Track(TileIndex tile, TransportType mode, uint, DiagDirection side)
2725 /* Case of half tile slope with water. */
2726 if (mode == TRANSPORT_WATER && IsPlainRail(tile) && GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(GetTileSlope(tile))) {
2727 TrackBits tb = GetTrackBits(tile);
2728 switch (tb) {
2729 default: NOT_REACHED();
2730 case TRACK_BIT_UPPER: tb = TRACK_BIT_LOWER; break;
2731 case TRACK_BIT_LOWER: tb = TRACK_BIT_UPPER; break;
2732 case TRACK_BIT_LEFT: tb = TRACK_BIT_RIGHT; break;
2733 case TRACK_BIT_RIGHT: tb = TRACK_BIT_LEFT; break;
2735 return CombineTrackStatus(TrackBitsToTrackdirBits(tb), TRACKDIR_BIT_NONE);
2738 if (mode != TRANSPORT_RAIL) return 0;
2740 TrackBits trackbits = TRACK_BIT_NONE;
2741 TrackdirBits red_signals = TRACKDIR_BIT_NONE;
2743 switch (GetRailTileType(tile)) {
2744 default: NOT_REACHED();
2745 case RAIL_TILE_NORMAL:
2746 trackbits = GetTrackBits(tile);
2747 break;
2749 case RAIL_TILE_SIGNALS: {
2750 trackbits = GetTrackBits(tile);
2751 byte a = GetPresentSignals(tile);
2752 uint b = GetSignalStates(tile);
2754 b &= a;
2756 /* When signals are not present (in neither direction),
2757 * we pretend them to be green. Otherwise, it depends on
2758 * the signal type. For signals that are only active from
2759 * one side, we set the missing signals explicitly to
2760 * `green'. Otherwise, they implicitly become `red'. */
2761 if (!IsOnewaySignal(tile, TRACK_UPPER) || (a & SignalOnTrack(TRACK_UPPER)) == 0) b |= ~a & SignalOnTrack(TRACK_UPPER);
2762 if (!IsOnewaySignal(tile, TRACK_LOWER) || (a & SignalOnTrack(TRACK_LOWER)) == 0) b |= ~a & SignalOnTrack(TRACK_LOWER);
2764 if ((b & 0x8) == 0) red_signals |= (TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_UPPER_E);
2765 if ((b & 0x4) == 0) red_signals |= (TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_UPPER_W);
2766 if ((b & 0x2) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_E);
2767 if ((b & 0x1) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LOWER_W);
2769 break;
2772 case RAIL_TILE_DEPOT: {
2773 DiagDirection dir = GetRailDepotDirection(tile);
2775 if (side != INVALID_DIAGDIR && side != dir) break;
2777 trackbits = DiagDirToDiagTrackBits(dir);
2778 break;
2782 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), red_signals);
2785 static bool ClickTile_Track(TileIndex tile)
2787 if (!IsRailDepot(tile)) return false;
2789 ShowDepotWindow(tile, VEH_TRAIN);
2790 return true;
2793 static void GetTileDesc_Track(TileIndex tile, TileDesc *td)
2795 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
2796 td->rail_speed = rti->max_speed;
2797 td->railtype = rti->strings.name;
2798 td->owner[0] = GetTileOwner(tile);
2799 switch (GetRailTileType(tile)) {
2800 case RAIL_TILE_NORMAL:
2801 td->str = STR_LAI_RAIL_DESCRIPTION_TRACK;
2802 break;
2804 case RAIL_TILE_SIGNALS: {
2805 static const StringID signal_type[6][6] = {
2807 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_SIGNALS,
2808 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
2809 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
2810 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
2811 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
2812 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS
2815 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
2816 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRESIGNALS,
2817 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
2818 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
2819 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
2820 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS
2823 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
2824 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
2825 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXITSIGNALS,
2826 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
2827 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
2828 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS
2831 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
2832 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
2833 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
2834 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBOSIGNALS,
2835 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
2836 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS
2839 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
2840 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
2841 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
2842 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
2843 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBSSIGNALS,
2844 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS
2847 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS,
2848 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS,
2849 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS,
2850 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS,
2851 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS,
2852 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRYSIGNALS
2856 SignalType primary_signal;
2857 SignalType secondary_signal;
2858 if (HasSignalOnTrack(tile, TRACK_UPPER)) {
2859 primary_signal = GetSignalType(tile, TRACK_UPPER);
2860 secondary_signal = HasSignalOnTrack(tile, TRACK_LOWER) ? GetSignalType(tile, TRACK_LOWER) : primary_signal;
2861 } else {
2862 secondary_signal = primary_signal = GetSignalType(tile, TRACK_LOWER);
2865 td->str = signal_type[secondary_signal][primary_signal];
2866 break;
2869 case RAIL_TILE_DEPOT:
2870 td->str = STR_LAI_RAIL_DESCRIPTION_TRAIN_DEPOT;
2871 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) {
2872 if (td->rail_speed > 0) {
2873 td->rail_speed = std::min<uint16_t>(td->rail_speed, 61);
2874 } else {
2875 td->rail_speed = 61;
2878 td->build_date = Depot::GetByTile(tile)->build_date;
2879 break;
2881 default:
2882 NOT_REACHED();
2886 static void ChangeTileOwner_Track(TileIndex tile, Owner old_owner, Owner new_owner)
2888 if (!IsTileOwner(tile, old_owner)) return;
2890 if (new_owner != INVALID_OWNER) {
2891 /* Update company infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
2892 uint num_pieces = 1;
2893 if (IsPlainRail(tile)) {
2894 TrackBits bits = GetTrackBits(tile);
2895 num_pieces = CountBits(bits);
2896 if (TracksOverlap(bits)) num_pieces *= num_pieces;
2898 RailType rt = GetRailType(tile);
2899 Company::Get(old_owner)->infrastructure.rail[rt] -= num_pieces;
2900 Company::Get(new_owner)->infrastructure.rail[rt] += num_pieces;
2902 if (HasSignals(tile)) {
2903 uint num_sigs = CountBits(GetPresentSignals(tile));
2904 Company::Get(old_owner)->infrastructure.signal -= num_sigs;
2905 Company::Get(new_owner)->infrastructure.signal += num_sigs;
2908 SetTileOwner(tile, new_owner);
2909 } else {
2910 Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_BANKRUPT, tile);
2914 static const byte _fractcoords_behind[4] = { 0x8F, 0x8, 0x80, 0xF8 };
2915 static const byte _fractcoords_enter[4] = { 0x8A, 0x48, 0x84, 0xA8 };
2916 static const int8_t _deltacoord_leaveoffset[8] = {
2917 -1, 0, 1, 0, /* x */
2918 0, 1, 0, -1 /* y */
2923 * Compute number of ticks when next wagon will leave a depot.
2924 * Negative means next wagon should have left depot n ticks before.
2925 * @param v vehicle outside (leaving) the depot
2926 * @return number of ticks when the next wagon will leave
2928 int TicksToLeaveDepot(const Train *v)
2930 DiagDirection dir = GetRailDepotDirection(v->tile);
2931 int length = v->CalcNextVehicleOffset();
2933 switch (dir) {
2934 case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) - (length + 1)));
2935 case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) + (length + 1)));
2936 case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) + (length + 1)));
2937 case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) - (length + 1)));
2938 default: NOT_REACHED();
2943 * Tile callback routine when vehicle enters tile
2944 * @see vehicle_enter_tile_proc
2946 static VehicleEnterTileStatus VehicleEnter_Track(Vehicle *u, TileIndex tile, int x, int y)
2948 /* This routine applies only to trains in depot tiles. */
2949 if (u->type != VEH_TRAIN || !IsRailDepotTile(tile)) return VETSB_CONTINUE;
2951 /* Depot direction. */
2952 DiagDirection dir = GetRailDepotDirection(tile);
2954 byte fract_coord = (x & 0xF) + ((y & 0xF) << 4);
2956 /* Make sure a train is not entering the tile from behind. */
2957 if (_fractcoords_behind[dir] == fract_coord) return VETSB_CANNOT_ENTER;
2959 Train *v = Train::From(u);
2961 /* Leaving depot? */
2962 if (v->direction == DiagDirToDir(dir)) {
2963 /* Calculate the point where the following wagon should be activated. */
2964 int length = v->CalcNextVehicleOffset();
2966 byte fract_coord_leave =
2967 ((_fractcoords_enter[dir] & 0x0F) + // x
2968 (length + 1) * _deltacoord_leaveoffset[dir]) +
2969 (((_fractcoords_enter[dir] >> 4) + // y
2970 ((length + 1) * _deltacoord_leaveoffset[dir + 4])) << 4);
2972 if (fract_coord_leave == fract_coord) {
2973 /* Leave the depot. */
2974 if ((v = v->Next()) != nullptr) {
2975 v->vehstatus &= ~VS_HIDDEN;
2976 v->track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
2979 } else if (_fractcoords_enter[dir] == fract_coord) {
2980 /* Entering depot. */
2981 assert(DiagDirToDir(ReverseDiagDir(dir)) == v->direction);
2982 v->track = TRACK_BIT_DEPOT,
2983 v->vehstatus |= VS_HIDDEN;
2984 v->direction = ReverseDir(v->direction);
2985 if (v->Next() == nullptr) VehicleEnterDepot(v->First());
2986 v->tile = tile;
2988 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2989 return VETSB_ENTERED_WORMHOLE;
2992 return VETSB_CONTINUE;
2996 * Tests if autoslope is allowed.
2998 * @param tile The tile.
2999 * @param flags Terraform command flags.
3000 * @param z_old Old TileZ.
3001 * @param tileh_old Old TileSlope.
3002 * @param z_new New TileZ.
3003 * @param tileh_new New TileSlope.
3004 * @param rail_bits Trackbits.
3006 static CommandCost TestAutoslopeOnRailTile(TileIndex tile, uint flags, int z_old, Slope tileh_old, int z_new, Slope tileh_new, TrackBits rail_bits)
3008 if (!_settings_game.construction.build_on_slopes || !AutoslopeEnabled()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3010 /* Is the slope-rail_bits combination valid in general? I.e. is it safe to call GetRailFoundation() ? */
3011 if (CheckRailSlope(tileh_new, rail_bits, TRACK_BIT_NONE, tile).Failed()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3013 /* Get the slopes on top of the foundations */
3014 z_old += ApplyFoundationToSlope(GetRailFoundation(tileh_old, rail_bits), &tileh_old);
3015 z_new += ApplyFoundationToSlope(GetRailFoundation(tileh_new, rail_bits), &tileh_new);
3017 Corner track_corner;
3018 switch (rail_bits) {
3019 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
3020 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
3021 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
3022 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
3024 /* Surface slope must not be changed */
3025 default:
3026 if (z_old != z_new || tileh_old != tileh_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3027 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3030 /* The height of the track_corner must not be changed. The rest ensures GetRailFoundation() already. */
3031 z_old += GetSlopeZInCorner(RemoveHalftileSlope(tileh_old), track_corner);
3032 z_new += GetSlopeZInCorner(RemoveHalftileSlope(tileh_new), track_corner);
3033 if (z_old != z_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3035 CommandCost cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3036 /* Make the ground dirty, if surface slope has changed */
3037 if (tileh_old != tileh_new) {
3038 /* If there is flat water on the lower halftile add the cost for clearing it */
3039 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old)) cost.AddCost(_price[PR_CLEAR_WATER]);
3040 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
3042 return cost;
3046 * Test-procedure for HasVehicleOnPos to check for a ship.
3048 static Vehicle *EnsureNoShipProc(Vehicle *v, void *)
3050 return v->type == VEH_SHIP ? v : nullptr;
3053 static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3055 int z_old;
3056 Slope tileh_old = GetTileSlope(tile, &z_old);
3057 if (IsPlainRail(tile)) {
3058 TrackBits rail_bits = GetTrackBits(tile);
3059 /* Is there flat water on the lower halftile that must be cleared expensively? */
3060 bool was_water = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old));
3062 /* Allow clearing the water only if there is no ship */
3063 if (was_water && HasVehicleOnPos(tile, nullptr, &EnsureNoShipProc)) return_cmd_error(STR_ERROR_SHIP_IN_THE_WAY);
3065 /* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
3066 CommandCost autoslope_result = TestAutoslopeOnRailTile(tile, flags, z_old, tileh_old, z_new, tileh_new, rail_bits);
3068 /* When there is only a single horizontal/vertical track, one corner can be terraformed. */
3069 Corner allowed_corner;
3070 switch (rail_bits) {
3071 case TRACK_BIT_RIGHT: allowed_corner = CORNER_W; break;
3072 case TRACK_BIT_UPPER: allowed_corner = CORNER_S; break;
3073 case TRACK_BIT_LEFT: allowed_corner = CORNER_E; break;
3074 case TRACK_BIT_LOWER: allowed_corner = CORNER_N; break;
3075 default: return autoslope_result;
3078 Foundation f_old = GetRailFoundation(tileh_old, rail_bits);
3080 /* Do not allow terraforming if allowed_corner is part of anti-zig-zag foundations */
3081 if (tileh_old != SLOPE_NS && tileh_old != SLOPE_EW && IsSpecialRailFoundation(f_old)) return autoslope_result;
3083 /* Everything is valid, which only changes allowed_corner */
3084 for (Corner corner = (Corner)0; corner < CORNER_END; corner = (Corner)(corner + 1)) {
3085 if (allowed_corner == corner) continue;
3086 if (z_old + GetSlopeZInCorner(tileh_old, corner) != z_new + GetSlopeZInCorner(tileh_new, corner)) return autoslope_result;
3089 /* Make the ground dirty */
3090 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
3092 /* allow terraforming */
3093 return CommandCost(EXPENSES_CONSTRUCTION, was_water ? _price[PR_CLEAR_WATER] : (Money)0);
3094 } else if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() &&
3095 AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRailDepotDirection(tile))) {
3096 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3098 return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
3102 extern const TileTypeProcs _tile_type_rail_procs = {
3103 DrawTile_Track, // draw_tile_proc
3104 GetSlopePixelZ_Track, // get_slope_z_proc
3105 ClearTile_Track, // clear_tile_proc
3106 nullptr, // add_accepted_cargo_proc
3107 GetTileDesc_Track, // get_tile_desc_proc
3108 GetTileTrackStatus_Track, // get_tile_track_status_proc
3109 ClickTile_Track, // click_tile_proc
3110 nullptr, // animate_tile_proc
3111 TileLoop_Track, // tile_loop_proc
3112 ChangeTileOwner_Track, // change_tile_owner_proc
3113 nullptr, // add_produced_cargo_proc
3114 VehicleEnter_Track, // vehicle_enter_tile_proc
3115 GetFoundation_Track, // get_foundation_proc
3116 TerraformTile_Track, // terraform_tile_proc