OpenTTD: src/rail_cmd.cpp Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

rail_cmd.cpp
Go to the documentation of this file.
1 /* $Id: rail_cmd.cpp 27343 2015-07-26 12:28:34Z frosch $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
9
12 #include "stdafx.h"
13 #include "cmd_helper.h"
14 #include "viewport_func.h"
15 #include "command_func.h"
16 #include "depot_base.h"
17 #include "pathfinder/yapf/yapf_cache.h"
18 #include "newgrf_debug.h"
19 #include "newgrf_railtype.h"
20 #include "train.h"
21 #include "autoslope.h"
22 #include "water.h"
23 #include "tunnelbridge_map.h"
24 #include "vehicle_func.h"
25 #include "sound_func.h"
26 #include "tunnelbridge.h"
27 #include "elrail_func.h"
28 #include "town.h"
29 #include "pbs.h"
30 #include "company_base.h"
31 #include "core/backup_type.hpp"
32 #include "date_func.h"
33 #include "strings_func.h"
34 #include "company_gui.h"
35 #include "object_map.h"
36
37 #include "table/strings.h"
38 #include "table/railtypes.h"
39 #include "table/track_land.h"
40
41 #include "safeguards.h"
42
44 typedef SmallVector<Train *, 16> TrainList;
45
46 RailtypeInfo _railtypes[RAILTYPE_END];
47
48 assert_compile(sizeof(_original_railtypes) <= sizeof(_railtypes));
49
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,
60 };
61
65 void ResetRailTypes()
66 {
67 memset(_railtypes, 0, sizeof(_railtypes));
68 memcpy(_railtypes, _original_railtypes, sizeof(_original_railtypes));
69 }
70
71 void ResolveRailTypeGUISprites(RailtypeInfo *rti)
72 {
73 SpriteID cursors_base = GetCustomRailSprite(rti, INVALID_TILE, RTSG_CURSORS);
74 if (cursors_base != 0) {
75 rti->gui_sprites.build_ns_rail = cursors_base + 0;
76 rti->gui_sprites.build_x_rail = cursors_base + 1;
77 rti->gui_sprites.build_ew_rail = cursors_base + 2;
78 rti->gui_sprites.build_y_rail = cursors_base + 3;
79 rti->gui_sprites.auto_rail = cursors_base + 4;
80 rti->gui_sprites.build_depot = cursors_base + 5;
81 rti->gui_sprites.build_tunnel = cursors_base + 6;
82 rti->gui_sprites.convert_rail = cursors_base + 7;
83 rti->cursor.rail_ns = cursors_base + 8;
84 rti->cursor.rail_swne = cursors_base + 9;
85 rti->cursor.rail_ew = cursors_base + 10;
86 rti->cursor.rail_nwse = cursors_base + 11;
87 rti->cursor.autorail = cursors_base + 12;
88 rti->cursor.depot = cursors_base + 13;
89 rti->cursor.tunnel = cursors_base + 14;
90 rti->cursor.convert = cursors_base + 15;
91 }
92
93 /* Array of default GUI signal sprite numbers. */
94 const SpriteID _signal_lookup[2][SIGTYPE_END] = {
95 {SPR_IMG_SIGNAL_ELECTRIC_NORM, SPR_IMG_SIGNAL_ELECTRIC_ENTRY, SPR_IMG_SIGNAL_ELECTRIC_EXIT,
96 SPR_IMG_SIGNAL_ELECTRIC_COMBO, SPR_IMG_SIGNAL_ELECTRIC_PBS, SPR_IMG_SIGNAL_ELECTRIC_PBS_OWAY},
97
98 {SPR_IMG_SIGNAL_SEMAPHORE_NORM, SPR_IMG_SIGNAL_SEMAPHORE_ENTRY, SPR_IMG_SIGNAL_SEMAPHORE_EXIT,
99 SPR_IMG_SIGNAL_SEMAPHORE_COMBO, SPR_IMG_SIGNAL_SEMAPHORE_PBS, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY},
100 };
101
102 for (SignalType type = SIGTYPE_NORMAL; type < SIGTYPE_END; type = (SignalType)(type + 1)) {
103 for (SignalVariant var = SIG_ELECTRIC; var <= SIG_SEMAPHORE; var = (SignalVariant)(var + 1)) {
104 SpriteID red = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_RED, true);
105 SpriteID green = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_GREEN, true);
106 rti->gui_sprites.signals[type][var][0] = (red != 0) ? red + SIGNAL_TO_SOUTH : _signal_lookup[var][type];
107 rti->gui_sprites.signals[type][var][1] = (green != 0) ? green + SIGNAL_TO_SOUTH : _signal_lookup[var][type] + 1;
108 }
109 }
110 }
111
115 void InitRailTypes()
116 {
117 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
118 RailtypeInfo *rti = &_railtypes[rt];
119 ResolveRailTypeGUISprites(rti);
120 }
121 }
122
126 RailType AllocateRailType(RailTypeLabel label)
127 {
128 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
129 RailtypeInfo *rti = &_railtypes[rt];
130
131 if (rti->label == 0) {
132 /* Set up new rail type */
133 memcpy(rti, &_railtypes[RAILTYPE_RAIL], sizeof(*rti));
134 rti->label = label;
135 /* Clear alternate label list. Can't use Reset() here as that would free
136 * the data pointer of RAILTYPE_RAIL and not our new rail type. */
137 new (&rti->alternate_labels) RailTypeLabelList;
138
139 /* Make us compatible with ourself. */
140 rti->powered_railtypes = (RailTypes)(1 << rt);
141 rti->compatible_railtypes = (RailTypes)(1 << rt);
142
143 /* We also introduce ourself. */
144 rti->introduces_railtypes = (RailTypes)(1 << rt);
145
146 /* Default sort order; order of allocation, but with some
147 * offsets so it's easier for NewGRF to pick a spot without
148 * changing the order of other (original) rail types.
149 * The << is so you can place other railtypes in between the
150 * other railtypes, the 7 is to be able to place something
151 * before the first (default) rail type. */
152 rti->sorting_order = rt << 4 | 7;
153 return rt;
154 }
155 }
156
157 return INVALID_RAILTYPE;
158 }
159
160 static const byte _track_sloped_sprites[14] = {
161 14, 15, 22, 13,
162 0, 21, 17, 12,
163 23, 0, 18, 20,
164 19, 16
165 };
166
167
168 /* 4
169 * ---------
170 * |\ /|
171 * | \ 1/ |
172 * | \ / |
173 * | \ / |
174 * 16| \ |32
175 * | / \2 |
176 * | / \ |
177 * | / \ |
178 * |/ \|
179 * ---------
180 * 8
181 */
182
183
184
185 /* MAP2 byte: abcd???? => Signal On? Same coding as map3lo
186 * MAP3LO byte: abcd???? => Signal Exists?
187 * a and b are for diagonals, upper and left,
188 * one for each direction. (ie a == NE->SW, b ==
189 * SW->NE, or v.v., I don't know. b and c are
190 * similar for lower and right.
191 * MAP2 byte: ????abcd => Type of ground.
192 * MAP3LO byte: ????abcd => Type of rail.
193 * MAP5: 00abcdef => rail
194 * 01abcdef => rail w/ signals
195 * 10uuuuuu => unused
196 * 11uuuudd => rail depot
197 */
198
207 static CommandCost EnsureNoTrainOnTrack(TileIndex tile, Track track)
208 {
209 TrackBits rail_bits = TrackToTrackBits(track);
210 return EnsureNoTrainOnTrackBits(tile, rail_bits);
211 }
212
220 static CommandCost CheckTrackCombination(TileIndex tile, TrackBits to_build, uint flags)
221 {
222 if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
223
224 /* So, we have a tile with tracks on it (and possibly signals). Let's see
225 * what tracks first */
226 TrackBits current = GetTrackBits(tile); // The current track layout.
227 TrackBits future = current | to_build; // The track layout we want to build.
228
229 /* Are we really building something new? */
230 if (current == future) {
231 /* Nothing new is being built */
232 return_cmd_error(STR_ERROR_ALREADY_BUILT);
233 }
234
235 /* Let's see if we may build this */
236 if ((flags & DC_NO_RAIL_OVERLAP) || HasSignals(tile)) {
237 /* If we are not allowed to overlap (flag is on for ai companies or we have
238 * signals on the tile), check that */
239 if (future != TRACK_BIT_HORZ && future != TRACK_BIT_VERT) {
240 return_cmd_error((flags & DC_NO_RAIL_OVERLAP) ? STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION : STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
241 }
242 }
243 /* Normally, we may overlap and any combination is valid */
244 return CommandCost();
245 }
246
247
249 static const TrackBits _valid_tracks_without_foundation[15] = {
250 TRACK_BIT_ALL,
251 TRACK_BIT_RIGHT,
252 TRACK_BIT_UPPER,
253 TRACK_BIT_X,
254
255 TRACK_BIT_LEFT,
256 TRACK_BIT_NONE,
257 TRACK_BIT_Y,
258 TRACK_BIT_LOWER,
259
260 TRACK_BIT_LOWER,
261 TRACK_BIT_Y,
262 TRACK_BIT_NONE,
263 TRACK_BIT_LEFT,
264
265 TRACK_BIT_X,
266 TRACK_BIT_UPPER,
267 TRACK_BIT_RIGHT,
268 };
269
271 static const TrackBits _valid_tracks_on_leveled_foundation[15] = {
272 TRACK_BIT_NONE,
273 TRACK_BIT_LEFT,
274 TRACK_BIT_LOWER,
275 TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
276
277 TRACK_BIT_RIGHT,
278 TRACK_BIT_ALL,
279 TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,
280 TRACK_BIT_ALL,
281
282 TRACK_BIT_UPPER,
283 TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_LEFT,
284 TRACK_BIT_ALL,
285 TRACK_BIT_ALL,
286
287 TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,
288 TRACK_BIT_ALL,
289 TRACK_BIT_ALL
290 };
291
299 Foundation GetRailFoundation(Slope tileh, TrackBits bits)
300 {
301 if (bits == TRACK_BIT_NONE) return FOUNDATION_NONE;
302
303 if (IsSteepSlope(tileh)) {
304 /* Test for inclined foundations */
305 if (bits == TRACK_BIT_X) return FOUNDATION_INCLINED_X;
306 if (bits == TRACK_BIT_Y) return FOUNDATION_INCLINED_Y;
307
308 /* Get higher track */
309 Corner highest_corner = GetHighestSlopeCorner(tileh);
310 TrackBits higher_track = CornerToTrackBits(highest_corner);
311
312 /* Only higher track? */
313 if (bits == higher_track) return HalftileFoundation(highest_corner);
314
315 /* Overlap with higher track? */
316 if (TracksOverlap(bits | higher_track)) return FOUNDATION_INVALID;
317
318 /* either lower track or both higher and lower track */
319 return ((bits & higher_track) != 0 ? FOUNDATION_STEEP_BOTH : FOUNDATION_STEEP_LOWER);
320 } else {
321 if ((~_valid_tracks_without_foundation[tileh] & bits) == 0) return FOUNDATION_NONE;
322
323 bool valid_on_leveled = ((~_valid_tracks_on_leveled_foundation[tileh] & bits) == 0);
324
325 Corner track_corner;
326 switch (bits) {
327 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
328 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
329 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
330 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
331
332 case TRACK_BIT_HORZ:
333 if (tileh == SLOPE_N) return HalftileFoundation(CORNER_N);
334 if (tileh == SLOPE_S) return HalftileFoundation(CORNER_S);
335 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
336
337 case TRACK_BIT_VERT:
338 if (tileh == SLOPE_W) return HalftileFoundation(CORNER_W);
339 if (tileh == SLOPE_E) return HalftileFoundation(CORNER_E);
340 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
341
342 case TRACK_BIT_X:
343 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_X;
344 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
345
346 case TRACK_BIT_Y:
347 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_Y;
348 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
349
350 default:
351 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
352 }
353 /* Single diagonal track */
354
355 /* Track must be at least valid on leveled foundation */
356 if (!valid_on_leveled) return FOUNDATION_INVALID;
357
358 /* If slope has three raised corners, build leveled foundation */
359 if (IsSlopeWithThreeCornersRaised(tileh)) return FOUNDATION_LEVELED;
360
361 /* If neighboured corners of track_corner are lowered, build halftile foundation */
362 if ((tileh & SlopeWithThreeCornersRaised(OppositeCorner(track_corner))) == SlopeWithOneCornerRaised(track_corner)) return HalftileFoundation(track_corner);
363
364 /* else special anti-zig-zag foundation */
365 return SpecialRailFoundation(track_corner);
366 }
367 }
368
369
379 static CommandCost CheckRailSlope(Slope tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile)
380 {
381 /* don't allow building on the lower side of a coast */
382 if (GetFloodingBehaviour(tile) != FLOOD_NONE) {
383 if (!IsSteepSlope(tileh) && ((~_valid_tracks_on_leveled_foundation[tileh] & (rail_bits | existing)) != 0)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
384 }
385
386 Foundation f_new = GetRailFoundation(tileh, rail_bits | existing);
387
388 /* check track/slope combination */
389 if ((f_new == FOUNDATION_INVALID) ||
390 ((f_new != FOUNDATION_NONE) && (!_settings_game.construction.build_on_slopes))) {
391 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
392 }
393
394 Foundation f_old = GetRailFoundation(tileh, existing);
395 return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price[PR_BUILD_FOUNDATION] : (Money)0);
396 }
397
398 /* Validate functions for rail building */
399 static inline bool ValParamTrackOrientation(Track track)
400 {
401 return IsValidTrack(track);
402 }
403
413 CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
414 {
415 RailType railtype = Extract<RailType, 0, 4>(p1);
416 Track track = Extract<Track, 0, 3>(p2);
417 CommandCost cost(EXPENSES_CONSTRUCTION);
418
419 if (!ValParamRailtype(railtype) || !ValParamTrackOrientation(track)) return CMD_ERROR;
420
421 Slope tileh = GetTileSlope(tile);
422 TrackBits trackbit = TrackToTrackBits(track);
423
424 switch (GetTileType(tile)) {
425 case MP_RAILWAY: {
426 CommandCost ret = CheckTileOwnership(tile);
427 if (ret.Failed()) return ret;
428
429 if (!IsPlainRail(tile)) return CMD_ERROR;
430
431 if (!IsCompatibleRail(GetRailType(tile), railtype)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
432
433 ret = CheckTrackCombination(tile, trackbit, flags);
434 if (ret.Succeeded()) ret = EnsureNoTrainOnTrack(tile, track);
435 if (ret.Failed()) return ret;
436
437 ret = CheckRailSlope(tileh, trackbit, GetTrackBits(tile), tile);
438 if (ret.Failed()) return ret;
439 cost.AddCost(ret);
440
441 /* If the rail types don't match, try to convert only if engines of
442 * the new rail type are not powered on the present rail type and engines of
443 * the present rail type are powered on the new rail type. */
444 if (GetRailType(tile) != railtype && !HasPowerOnRail(railtype, GetRailType(tile))) {
445 if (HasPowerOnRail(GetRailType(tile), railtype)) {
446 ret = DoCommand(tile, tile, railtype, flags, CMD_CONVERT_RAIL);
447 if (ret.Failed()) return ret;
448 cost.AddCost(ret);
449 } else {
450 return CMD_ERROR;
451 }
452 }
453
454 if (flags & DC_EXEC) {
455 SetRailGroundType(tile, RAIL_GROUND_BARREN);
456 TrackBits bits = GetTrackBits(tile);
457 SetTrackBits(tile, bits | trackbit);
458 /* Subtract old infrastructure count. */
459 uint pieces = CountBits(bits);
460 if (TracksOverlap(bits)) pieces *= pieces;
461 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] -= pieces;
462 /* Add new infrastructure count. */
463 pieces = CountBits(bits | trackbit);
464 if (TracksOverlap(bits | trackbit)) pieces *= pieces;
465 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] += pieces;
466 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
467 }
468 break;
469 }
470
471 case MP_ROAD: {
472 /* Level crossings may only be built on these slopes */
473 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
474
475 CommandCost ret = EnsureNoVehicleOnGround(tile);
476 if (ret.Failed()) return ret;
477
478 if (IsNormalRoad(tile)) {
479 if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
480
481 if (GetDisallowedRoadDirections(tile) != DRD_NONE) return_cmd_error(STR_ERROR_CROSSING_ON_ONEWAY_ROAD);
482
483 if (RailNoLevelCrossings(railtype)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED);
484
485 RoadTypes roadtypes = GetRoadTypes(tile);
486 RoadBits road = GetRoadBits(tile, ROADTYPE_ROAD);
487 RoadBits tram = GetRoadBits(tile, ROADTYPE_TRAM);
488 if ((track == TRACK_X && ((road | tram) & ROAD_X) == 0) ||
489 (track == TRACK_Y && ((road | tram) & ROAD_Y) == 0)) {
490 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
491 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
492 /* Disallow breaking end-of-line of someone else
493 * so trams can still reverse on this tile. */
494 if (Company::IsValidID(tram_owner) && HasExactlyOneBit(tram)) {
495 CommandCost ret = CheckOwnership(tram_owner);
496 if (ret.Failed()) return ret;
497 }
498 /* Crossings must always have a road... */
499 uint num_new_road_pieces = 2 - CountBits(road);
500 if (road == ROAD_NONE) road_owner = _current_company;
501 roadtypes |= ROADTYPES_ROAD;
502 /* ...but tram is not required. */
503 uint num_new_tram_pieces = (tram != ROAD_NONE) ? 2 - CountBits(tram) : 0;
504
505 cost.AddCost((num_new_road_pieces + num_new_tram_pieces) * _price[PR_BUILD_ROAD]);
506
507 if (flags & DC_EXEC) {
508 MakeRoadCrossing(tile, road_owner, tram_owner, _current_company, (track == TRACK_X ? AXIS_Y : AXIS_X), railtype, roadtypes, GetTownIndex(tile));
509 UpdateLevelCrossing(tile, false);
510 Company::Get(_current_company)->infrastructure.rail[railtype] += LEVELCROSSING_TRACKBIT_FACTOR;
511 DirtyCompanyInfrastructureWindows(_current_company);
512 if (num_new_road_pieces > 0 && Company::IsValidID(road_owner)) {
513 Company::Get(road_owner)->infrastructure.road[ROADTYPE_ROAD] += num_new_road_pieces;
514 DirtyCompanyInfrastructureWindows(road_owner);
515 }
516 if (num_new_tram_pieces > 0 && Company::IsValidID(tram_owner)) {
517 Company::Get(tram_owner)->infrastructure.road[ROADTYPE_TRAM] += num_new_tram_pieces;
518 DirtyCompanyInfrastructureWindows(tram_owner);
519 }
520 }
521 break;
522 }
523 }
524
525 if (IsLevelCrossing(tile) && GetCrossingRailBits(tile) == trackbit) {
526 return_cmd_error(STR_ERROR_ALREADY_BUILT);
527 }
528 /* FALL THROUGH */
529 }
530
531 default: {
532 /* Will there be flat water on the lower halftile? */
533 bool water_ground = IsTileType(tile, MP_WATER) && IsSlopeWithOneCornerRaised(tileh);
534
535 CommandCost ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile);
536 if (ret.Failed()) return ret;
537 cost.AddCost(ret);
538
539 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
540 if (ret.Failed()) return ret;
541 cost.AddCost(ret);
542
543 if (water_ground) {
544 cost.AddCost(-_price[PR_CLEAR_WATER]);
545 cost.AddCost(_price[PR_CLEAR_ROUGH]);
546 }
547
548 if (flags & DC_EXEC) {
549 MakeRailNormal(tile, _current_company, trackbit, railtype);
550 if (water_ground) SetRailGroundType(tile, RAIL_GROUND_WATER);
551 Company::Get(_current_company)->infrastructure.rail[railtype]++;
552 DirtyCompanyInfrastructureWindows(_current_company);
553 }
554 break;
555 }
556 }
557
558 if (flags & DC_EXEC) {
559 MarkTileDirtyByTile(tile);
560 AddTrackToSignalBuffer(tile, track, _current_company);
561 YapfNotifyTrackLayoutChange(tile, track);
562 }
563
564 cost.AddCost(RailBuildCost(railtype));
565 return cost;
566 }
567
577 CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
578 {
579 Track track = Extract<Track, 0, 3>(p2);
580 CommandCost cost(EXPENSES_CONSTRUCTION);
581 bool crossing = false;
582
583 if (!ValParamTrackOrientation(track)) return CMD_ERROR;
584 TrackBits trackbit = TrackToTrackBits(track);
585
586 /* Need to read tile owner now because it may change when the rail is removed
587 * Also, in case of floods, _current_company != owner
588 * There may be invalid tiletype even in exec run (when removing long track),
589 * so do not call GetTileOwner(tile) in any case here */
590 Owner owner = INVALID_OWNER;
591
592 Train *v = NULL;
593
594 switch (GetTileType(tile)) {
595 case MP_ROAD: {
596 if (!IsLevelCrossing(tile) || GetCrossingRailBits(tile) != trackbit) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
597
598 if (_current_company != OWNER_WATER) {
599 CommandCost ret = CheckTileOwnership(tile);
600 if (ret.Failed()) return ret;
601 }
602
603 if (!(flags & DC_BANKRUPT)) {
604 CommandCost ret = EnsureNoVehicleOnGround(tile);
605 if (ret.Failed()) return ret;
606 }
607
608 cost.AddCost(RailClearCost(GetRailType(tile)));
609
610 if (flags & DC_EXEC) {
611 if (HasReservedTracks(tile, trackbit)) {
612 v = GetTrainForReservation(tile, track);
613 if (v != NULL) FreeTrainTrackReservation(v);
614 }
615 owner = GetTileOwner(tile);
616 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
617 DirtyCompanyInfrastructureWindows(owner);
618 MakeRoadNormal(tile, GetCrossingRoadBits(tile), GetRoadTypes(tile), GetTownIndex(tile), GetRoadOwner(tile, ROADTYPE_ROAD), GetRoadOwner(tile, ROADTYPE_TRAM));
619 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
620 }
621 break;
622 }
623
624 case MP_RAILWAY: {
625 TrackBits present;
626 /* There are no rails present at depots. */
627 if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
628
629 if (_current_company != OWNER_WATER) {
630 CommandCost ret = CheckTileOwnership(tile);
631 if (ret.Failed()) return ret;
632 }
633
634 CommandCost ret = EnsureNoTrainOnTrack(tile, track);
635 if (ret.Failed()) return ret;
636
637 present = GetTrackBits(tile);
638 if ((present & trackbit) == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
639 if (present == (TRACK_BIT_X | TRACK_BIT_Y)) crossing = true;
640
641 cost.AddCost(RailClearCost(GetRailType(tile)));
642
643 /* Charge extra to remove signals on the track, if they are there */
644 if (HasSignalOnTrack(tile, track)) {
645 cost.AddCost(DoCommand(tile, track, 0, flags, CMD_REMOVE_SIGNALS));
646 }
647
648 if (flags & DC_EXEC) {
649 if (HasReservedTracks(tile, trackbit)) {
650 v = GetTrainForReservation(tile, track);
651 if (v != NULL) FreeTrainTrackReservation(v);
652 }
653
654 owner = GetTileOwner(tile);
655
656 /* Subtract old infrastructure count. */
657 uint pieces = CountBits(present);
658 if (TracksOverlap(present)) pieces *= pieces;
659 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= pieces;
660 /* Add new infrastructure count. */
661 present ^= trackbit;
662 pieces = CountBits(present);
663 if (TracksOverlap(present)) pieces *= pieces;
664 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] += pieces;
665 DirtyCompanyInfrastructureWindows(owner);
666
667 if (present == 0) {
668 Slope tileh = GetTileSlope(tile);
669 /* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
670 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh)) {
671 MakeShore(tile);
672 } else {
673 DoClearSquare(tile);
674 }
675 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
676 } else {
677 SetTrackBits(tile, present);
678 SetTrackReservation(tile, GetRailReservationTrackBits(tile) & present);
679 }
680 }
681 break;
682 }
683
684 default: return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
685 }
686
687 if (flags & DC_EXEC) {
688 /* if we got that far, 'owner' variable is set correctly */
689 assert(Company::IsValidID(owner));
690
691 MarkTileDirtyByTile(tile);
692 if (crossing) {
693 /* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
694 * are removing one of these pieces, we'll need to update signals for
695 * both directions explicitly, as after the track is removed it won't
696 * 'connect' with the other piece. */
697 AddTrackToSignalBuffer(tile, TRACK_X, owner);
698 AddTrackToSignalBuffer(tile, TRACK_Y, owner);
699 YapfNotifyTrackLayoutChange(tile, TRACK_X);
700 YapfNotifyTrackLayoutChange(tile, TRACK_Y);
701 } else {
702 AddTrackToSignalBuffer(tile, track, owner);
703 YapfNotifyTrackLayoutChange(tile, track);
704 }
705
706 if (v != NULL) TryPathReserve(v, true);
707 }
708
709 return cost;
710 }
711
712
720 bool FloodHalftile(TileIndex t)
721 {
722 assert(IsPlainRailTile(t));
723
724 bool flooded = false;
725 if (GetRailGroundType(t) == RAIL_GROUND_WATER) return flooded;
726
727 Slope tileh = GetTileSlope(t);
728 TrackBits rail_bits = GetTrackBits(t);
729
730 if (IsSlopeWithOneCornerRaised(tileh)) {
731 TrackBits lower_track = CornerToTrackBits(OppositeCorner(GetHighestSlopeCorner(tileh)));
732
733 TrackBits to_remove = lower_track & rail_bits;
734 if (to_remove != 0) {
735 Backup<CompanyByte> cur_company(_current_company, OWNER_WATER, FILE_LINE);
736 flooded = DoCommand(t, 0, FIND_FIRST_BIT(to_remove), DC_EXEC, CMD_REMOVE_SINGLE_RAIL).Succeeded();
737 cur_company.Restore();
738 if (!flooded) return flooded; // not yet floodable
739 rail_bits = rail_bits & ~to_remove;
740 if (rail_bits == 0) {
741 MakeShore(t);
742 MarkTileDirtyByTile(t);
743 return flooded;
744 }
745 }
746
747 if (IsNonContinuousFoundation(GetRailFoundation(tileh, rail_bits))) {
748 flooded = true;
749 SetRailGroundType(t, RAIL_GROUND_WATER);
750 MarkTileDirtyByTile(t);
751 }
752 } else {
753 /* Make shore on steep slopes and 'three-corners-raised'-slopes. */
754 if (ApplyFoundationToSlope(GetRailFoundation(tileh, rail_bits), &tileh) == 0) {
755 if (IsSteepSlope(tileh) || IsSlopeWithThreeCornersRaised(tileh)) {
756 flooded = true;
757 SetRailGroundType(t, RAIL_GROUND_WATER);
758 MarkTileDirtyByTile(t);
759 }
760 }
761 }
762 return flooded;
763 }
764
765 static const TileIndexDiffC _trackdelta[] = {
766 { -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
767 { 0, 0 },
768 { 0, 0 },
769 { 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
770 { 0, 0 },
771 { 0, 0 }
772 };
773
774
775 static CommandCost ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end)
776 {
777 int x = TileX(start);
778 int y = TileY(start);
779 int ex = TileX(end);
780 int ey = TileY(end);
781
782 if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CMD_ERROR;
783
784 /* calculate delta x,y from start to end tile */
785 int dx = ex - x;
786 int dy = ey - y;
787
788 /* calculate delta x,y for the first direction */
789 int trdx = _trackdelta[*trackdir].x;
790 int trdy = _trackdelta[*trackdir].y;
791
792 if (!IsDiagonalTrackdir(*trackdir)) {
793 trdx += _trackdelta[*trackdir ^ 1].x;
794 trdy += _trackdelta[*trackdir ^ 1].y;
795 }
796
797 /* validate the direction */
798 while ((trdx <= 0 && dx > 0) ||
799 (trdx >= 0 && dx < 0) ||
800 (trdy <= 0 && dy > 0) ||
801 (trdy >= 0 && dy < 0)) {
802 if (!HasBit(*trackdir, 3)) { // first direction is invalid, try the other
803 SetBit(*trackdir, 3); // reverse the direction
804 trdx = -trdx;
805 trdy = -trdy;
806 } else { // other direction is invalid too, invalid drag
807 return CMD_ERROR;
808 }
809 }
810
811 /* (for diagonal tracks, this is already made sure of by above test), but:
812 * for non-diagonal tracks, check if the start and end tile are on 1 line */
813 if (!IsDiagonalTrackdir(*trackdir)) {
814 trdx = _trackdelta[*trackdir].x;
815 trdy = _trackdelta[*trackdir].y;
816 if (abs(dx) != abs(dy) && abs(dx) + abs(trdy) != abs(dy) + abs(trdx)) return CMD_ERROR;
817 }
818
819 return CommandCost();
820 }
821
835 static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
836 {
837 CommandCost total_cost(EXPENSES_CONSTRUCTION);
838 Track track = Extract<Track, 4, 3>(p2);
839 bool remove = HasBit(p2, 7);
840 RailType railtype = Extract<RailType, 0, 4>(p2);
841
842 if ((!remove && !ValParamRailtype(railtype)) || !ValParamTrackOrientation(track)) return CMD_ERROR;
843 if (p1 >= MapSize()) return CMD_ERROR;
844 TileIndex end_tile = p1;
845 Trackdir trackdir = TrackToTrackdir(track);
846
847 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
848 if (ret.Failed()) return ret;
849
850 bool had_success = false;
851 CommandCost last_error = CMD_ERROR;
852 for (;;) {
853 CommandCost ret = DoCommand(tile, remove ? 0 : railtype, TrackdirToTrack(trackdir), flags, remove ? CMD_REMOVE_SINGLE_RAIL : CMD_BUILD_SINGLE_RAIL);
854
855 if (ret.Failed()) {
856 last_error = ret;
857 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT && !remove) {
858 if (HasBit(p2, 8)) return last_error;
859 break;
860 }
861
862 /* Ownership errors are more important. */
863 if (last_error.GetErrorMessage() == STR_ERROR_OWNED_BY && remove) break;
864 } else {
865 had_success = true;
866 total_cost.AddCost(ret);
867 }
868
869 if (tile == end_tile) break;
870
871 tile += ToTileIndexDiff(_trackdelta[trackdir]);
872
873 /* toggle railbit for the non-diagonal tracks */
874 if (!IsDiagonalTrackdir(trackdir)) ToggleBit(trackdir, 0);
875 }
876
877 if (had_success) return total_cost;
878 return last_error;
879 }
880
895 CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
896 {
897 return CmdRailTrackHelper(tile, flags, p1, ClrBit(p2, 7), text);
898 }
899
914 CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
915 {
916 return CmdRailTrackHelper(tile, flags, p1, SetBit(p2, 7), text);
917 }
918
931 CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
932 {
933 /* check railtype and valid direction for depot (0 through 3), 4 in total */
934 RailType railtype = Extract<RailType, 0, 4>(p1);
935 if (!ValParamRailtype(railtype)) return CMD_ERROR;
936
937 Slope tileh = GetTileSlope(tile);
938
939 DiagDirection dir = Extract<DiagDirection, 0, 2>(p2);
940
941 /* Prohibit construction if
942 * The tile is non-flat AND
943 * 1) build-on-slopes is disabled
944 * 2) the tile is steep i.e. spans two height levels
945 * 3) the exit points in the wrong direction
946 */
947
948 if (tileh != SLOPE_FLAT && (
949 !_settings_game.construction.build_on_slopes ||
950 !CanBuildDepotByTileh(dir, tileh)
951 )) {
952 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
953 }
954
955 CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
956 if (cost.Failed()) return cost;
957
958 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
959
960 if (!Depot::CanAllocateItem()) return CMD_ERROR;
961
962 if (flags & DC_EXEC) {
963 Depot *d = new Depot(tile);
964 d->build_date = _date;
965
966 MakeRailDepot(tile, _current_company, d->index, dir, railtype);
967 MarkTileDirtyByTile(tile);
968 MakeDefaultName(d);
969
970 Company::Get(_current_company)->infrastructure.rail[railtype]++;
971 DirtyCompanyInfrastructureWindows(_current_company);
972
973 AddSideToSignalBuffer(tile, INVALID_DIAGDIR, _current_company);
974 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
975 }
976
977 cost.AddCost(_price[PR_BUILD_DEPOT_TRAIN]);
978 cost.AddCost(RailBuildCost(railtype));
979 return cost;
980 }
981
1003 CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1004 {
1005 Track track = Extract<Track, 0, 3>(p1);
1006 bool ctrl_pressed = HasBit(p1, 3); // was the CTRL button pressed
1007 SignalVariant sigvar = (ctrl_pressed ^ HasBit(p1, 4)) ? SIG_SEMAPHORE : SIG_ELECTRIC; // the signal variant of the new signal
1008 SignalType sigtype = Extract<SignalType, 5, 3>(p1); // the signal type of the new signal
1009 bool convert_signal = HasBit(p1, 8); // convert button pressed
1010 SignalType cycle_start = Extract<SignalType, 9, 3>(p1);
1011 SignalType cycle_stop = Extract<SignalType, 12, 3>(p1);
1012 uint num_dir_cycle = GB(p1, 15, 2);
1013
1014 if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
1015 if (cycle_start > cycle_stop || cycle_stop > SIGTYPE_LAST) return CMD_ERROR;
1016
1017 /* You can only build signals on plain rail tiles, and the selected track must exist */
1018 if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) ||
1019 !HasTrack(tile, track)) {
1020 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1021 }
1022 /* Protect against invalid signal copying */
1023 if (p2 != 0 && (p2 & SignalOnTrack(track)) == 0) return CMD_ERROR;
1024
1025 CommandCost ret = CheckTileOwnership(tile);
1026 if (ret.Failed()) return ret;
1027
1028 /* See if this is a valid track combination for signals (no overlap) */
1029 if (TracksOverlap(GetTrackBits(tile))) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
1030
1031 /* In case we don't want to change an existing signal, return without error. */
1032 if (HasBit(p1, 17) && HasSignalOnTrack(tile, track)) return CommandCost();
1033
1034 /* you can not convert a signal if no signal is on track */
1035 if (convert_signal && !HasSignalOnTrack(tile, track)) return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1036
1037 CommandCost cost;
1038 if (!HasSignalOnTrack(tile, track)) {
1039 /* build new signals */
1040 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS]);
1041 } else {
1042 if (p2 != 0 && sigvar != GetSignalVariant(tile, track)) {
1043 /* convert signals <-> semaphores */
1044 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1045
1046 } else if (convert_signal) {
1047 /* convert button pressed */
1048 if (ctrl_pressed || GetSignalVariant(tile, track) != sigvar) {
1049 /* convert electric <-> semaphore */
1050 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1051 } else {
1052 /* it is free to change signal type: normal-pre-exit-combo */
1053 cost = CommandCost();
1054 }
1055
1056 } else {
1057 /* it is free to change orientation/pre-exit-combo signals */
1058 cost = CommandCost();
1059 }
1060 }
1061
1062 if (flags & DC_EXEC) {
1063 Train *v = NULL;
1064 /* The new/changed signal could block our path. As this can lead to
1065 * stale reservations, we clear the path reservation here and try
1066 * to redo it later on. */
1067 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1068 v = GetTrainForReservation(tile, track);
1069 if (v != NULL) FreeTrainTrackReservation(v);
1070 }
1071
1072 if (!HasSignals(tile)) {
1073 /* there are no signals at all on this tile yet */
1074 SetHasSignals(tile, true);
1075 SetSignalStates(tile, 0xF); // all signals are on
1076 SetPresentSignals(tile, 0); // no signals built by default
1077 SetSignalType(tile, track, sigtype);
1078 SetSignalVariant(tile, track, sigvar);
1079 }
1080
1081 /* Subtract old signal infrastructure count. */
1082 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1083
1084 if (p2 == 0) {
1085 if (!HasSignalOnTrack(tile, track)) {
1086 /* build new signals */
1087 SetPresentSignals(tile, GetPresentSignals(tile) | (IsPbsSignal(sigtype) ? KillFirstBit(SignalOnTrack(track)) : SignalOnTrack(track)));
1088 SetSignalType(tile, track, sigtype);
1089 SetSignalVariant(tile, track, sigvar);
1090 while (num_dir_cycle-- > 0) CycleSignalSide(tile, track);
1091 } else {
1092 if (convert_signal) {
1093 /* convert signal button pressed */
1094 if (ctrl_pressed) {
1095 /* toggle the present signal variant: SIG_ELECTRIC <-> SIG_SEMAPHORE */
1096 SetSignalVariant(tile, track, (GetSignalVariant(tile, track) == SIG_ELECTRIC) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1097 /* Query current signal type so the check for PBS signals below works. */
1098 sigtype = GetSignalType(tile, track);
1099 } else {
1100 /* convert the present signal to the chosen type and variant */
1101 SetSignalType(tile, track, sigtype);
1102 SetSignalVariant(tile, track, sigvar);
1103 if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1104 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1105 }
1106 }
1107
1108 } else if (ctrl_pressed) {
1109 /* cycle between cycle_start and cycle_end */
1110 sigtype = (SignalType)(GetSignalType(tile, track) + 1);
1111
1112 if (sigtype < cycle_start || sigtype > cycle_stop) sigtype = cycle_start;
1113
1114 SetSignalType(tile, track, sigtype);
1115 if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1116 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1117 }
1118 } else {
1119 /* cycle the signal side: both -> left -> right -> both -> ... */
1120 CycleSignalSide(tile, track);
1121 /* Query current signal type so the check for PBS signals below works. */
1122 sigtype = GetSignalType(tile, track);
1123 }
1124 }
1125 } else {
1126 /* If CmdBuildManySignals is called with copying signals, just copy the
1127 * direction of the first signal given as parameter by CmdBuildManySignals */
1128 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | (p2 & SignalOnTrack(track)));
1129 SetSignalVariant(tile, track, sigvar);
1130 SetSignalType(tile, track, sigtype);
1131 }
1132
1133 /* Add new signal infrastructure count. */
1134 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1135 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1136
1137 if (IsPbsSignal(sigtype)) {
1138 /* PBS signals should show red unless they are on reserved tiles without a train. */
1139 uint mask = GetPresentSignals(tile) & SignalOnTrack(track);
1140 SetSignalStates(tile, (GetSignalStates(tile) & ~mask) | ((HasBit(GetRailReservationTrackBits(tile), track) && EnsureNoVehicleOnGround(tile).Succeeded() ? UINT_MAX : 0) & mask));
1141 }
1142 MarkTileDirtyByTile(tile);
1143 AddTrackToSignalBuffer(tile, track, _current_company);
1144 YapfNotifyTrackLayoutChange(tile, track);
1145 if (v != NULL) {
1146 /* Extend the train's path if it's not stopped or loading, or not at a safe position. */
1147 if (!(((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) || v->current_order.IsType(OT_LOADING)) ||
1148 !IsSafeWaitingPosition(v, v->tile, v->GetVehicleTrackdir(), true, _settings_game.pf.forbid_90_deg)) {
1149 TryPathReserve(v, true);
1150 }
1151 }
1152 }
1153
1154 return cost;
1155 }
1156
1157 static bool CheckSignalAutoFill(TileIndex &tile, Trackdir &trackdir, int &signal_ctr, bool remove)
1158 {
1159 tile = AddTileIndexDiffCWrap(tile, _trackdelta[trackdir]);
1160 if (tile == INVALID_TILE) return false;
1161
1162 /* Check for track bits on the new tile */
1163 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
1164
1165 if (TracksOverlap(TrackdirBitsToTrackBits(trackdirbits))) return false;
1166 trackdirbits &= TrackdirReachesTrackdirs(trackdir);
1167
1168 /* No track bits, must stop */
1169 if (trackdirbits == TRACKDIR_BIT_NONE) return false;
1170
1171 /* Get the first track dir */
1172 trackdir = RemoveFirstTrackdir(&trackdirbits);
1173
1174 /* Any left? It's a junction so we stop */
1175 if (trackdirbits != TRACKDIR_BIT_NONE) return false;
1176
1177 switch (GetTileType(tile)) {
1178 case MP_RAILWAY:
1179 if (IsRailDepot(tile)) return false;
1180 if (!remove && HasSignalOnTrack(tile, TrackdirToTrack(trackdir))) return false;
1181 signal_ctr++;
1182 if (IsDiagonalTrackdir(trackdir)) {
1183 signal_ctr++;
1184 /* Ensure signal_ctr even so X and Y pieces get signals */
1185 ClrBit(signal_ctr, 0);
1186 }
1187 return true;
1188
1189 case MP_ROAD:
1190 if (!IsLevelCrossing(tile)) return false;
1191 signal_ctr += 2;
1192 return true;
1193
1194 case MP_TUNNELBRIDGE: {
1195 TileIndex orig_tile = tile; // backup old value
1196
1197 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return false;
1198 if (GetTunnelBridgeDirection(tile) != TrackdirToExitdir(trackdir)) return false;
1199
1200 /* Skip to end of tunnel or bridge
1201 * note that tile is a parameter by reference, so it must be updated */
1202 tile = GetOtherTunnelBridgeEnd(tile);
1203
1204 signal_ctr += (GetTunnelBridgeLength(orig_tile, tile) + 2) * 2;
1205 return true;
1206 }
1207
1208 default: return false;
1209 }
1210 }
1211
1229 static CommandCost CmdSignalTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1230 {
1231 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1232 TileIndex start_tile = tile;
1233
1234 Track track = Extract<Track, 0, 3>(p2);
1235 bool mode = HasBit(p2, 3);
1236 bool semaphores = HasBit(p2, 4);
1237 bool remove = HasBit(p2, 5);
1238 bool autofill = HasBit(p2, 6);
1239 bool minimise_gaps = HasBit(p2, 10);
1240 byte signal_density = GB(p2, 24, 8);
1241
1242 if (p1 >= MapSize() || !ValParamTrackOrientation(track)) return CMD_ERROR;
1243 TileIndex end_tile = p1;
1244 if (signal_density == 0 || signal_density > 20) return CMD_ERROR;
1245
1246 if (!IsPlainRailTile(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1247
1248 /* for vertical/horizontal tracks, double the given signals density
1249 * since the original amount will be too dense (shorter tracks) */
1250 signal_density *= 2;
1251
1252 Trackdir trackdir = TrackToTrackdir(track);
1253 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
1254 if (ret.Failed()) return ret;
1255
1256 track = TrackdirToTrack(trackdir); // trackdir might have changed, keep track in sync
1257 Trackdir start_trackdir = trackdir;
1258
1259 /* Must start on a valid track to be able to avoid loops */
1260 if (!HasTrack(tile, track)) return CMD_ERROR;
1261
1262 SignalType sigtype = (SignalType)GB(p2, 7, 3);
1263 if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
1264
1265 byte signals;
1266 /* copy the signal-style of the first rail-piece if existing */
1267 if (HasSignalOnTrack(tile, track)) {
1268 signals = GetPresentSignals(tile) & SignalOnTrack(track);
1269 assert(signals != 0);
1270
1271 /* copy signal/semaphores style (independent of CTRL) */
1272 semaphores = GetSignalVariant(tile, track) != SIG_ELECTRIC;
1273
1274 sigtype = GetSignalType(tile, track);
1275 /* Don't but copy entry or exit-signal type */
1276 if (sigtype == SIGTYPE_ENTRY || sigtype == SIGTYPE_EXIT) sigtype = SIGTYPE_NORMAL;
1277 } else { // no signals exist, drag a two-way signal stretch
1278 signals = IsPbsSignal(sigtype) ? SignalAlongTrackdir(trackdir) : SignalOnTrack(track);
1279 }
1280
1281 byte signal_dir = 0;
1282 if (signals & SignalAlongTrackdir(trackdir)) SetBit(signal_dir, 0);
1283 if (signals & SignalAgainstTrackdir(trackdir)) SetBit(signal_dir, 1);
1284
1285 /* signal_ctr - amount of tiles already processed
1286 * last_used_ctr - amount of tiles before previously placed signal
1287 * signals_density - setting to put signal on every Nth tile (double space on |, -- tracks)
1288 * last_suitable_ctr - amount of tiles before last possible signal place
1289 * last_suitable_tile - last tile where it is possible to place a signal
1290 * last_suitable_trackdir - trackdir of the last tile
1291 **********
1292 * trackdir - trackdir to build with autorail
1293 * semaphores - semaphores or signals
1294 * signals - is there a signal/semaphore on the first tile, copy its style (two-way/single-way)
1295 * and convert all others to semaphore/signal
1296 * remove - 1 remove signals, 0 build signals */
1297 int signal_ctr = 0;
1298 int last_used_ctr = INT_MIN; // initially INT_MIN to force building/removing at the first tile
1299 int last_suitable_ctr = 0;
1300 TileIndex last_suitable_tile = INVALID_TILE;
1301 Trackdir last_suitable_trackdir = INVALID_TRACKDIR;
1302 CommandCost last_error = CMD_ERROR;
1303 bool had_success = false;
1304 for (;;) {
1305 /* only build/remove signals with the specified density */
1306 if (remove || minimise_gaps || signal_ctr % signal_density == 0) {
1307 uint32 p1 = GB(TrackdirToTrack(trackdir), 0, 3);
1308 SB(p1, 3, 1, mode);
1309 SB(p1, 4, 1, semaphores);
1310 SB(p1, 5, 3, sigtype);
1311 if (!remove && signal_ctr == 0) SetBit(p1, 17);
1312
1313 /* Pick the correct orientation for the track direction */
1314 signals = 0;
1315 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(trackdir);
1316 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(trackdir);
1317
1318 /* Test tiles in between for suitability as well if minimising gaps. */
1319 bool test_only = !remove && minimise_gaps && signal_ctr < (last_used_ctr + signal_density);
1320 CommandCost ret = DoCommand(tile, p1, signals, test_only ? flags & ~DC_EXEC : flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1321
1322 if (ret.Succeeded()) {
1323 /* Remember last track piece where we can place a signal. */
1324 last_suitable_ctr = signal_ctr;
1325 last_suitable_tile = tile;
1326 last_suitable_trackdir = trackdir;
1327 } else if (!test_only && last_suitable_tile != INVALID_TILE) {
1328 /* If a signal can't be placed, place it at the last possible position. */
1329 SB(p1, 0, 3, TrackdirToTrack(last_suitable_trackdir));
1330 ClrBit(p1, 17);
1331
1332 /* Pick the correct orientation for the track direction. */
1333 signals = 0;
1334 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(last_suitable_trackdir);
1335 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(last_suitable_trackdir);
1336
1337 ret = DoCommand(last_suitable_tile, p1, signals, flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1338 }
1339
1340 /* Collect cost. */
1341 if (!test_only) {
1342 /* Be user-friendly and try placing signals as much as possible */
1343 if (ret.Succeeded()) {
1344 had_success = true;
1345 total_cost.AddCost(ret);
1346 last_used_ctr = last_suitable_ctr;
1347 last_suitable_tile = INVALID_TILE;
1348 } else {
1349 /* The "No railway" error is the least important one. */
1350 if (ret.GetErrorMessage() != STR_ERROR_THERE_IS_NO_RAILROAD_TRACK ||
1351 last_error.GetErrorMessage() == INVALID_STRING_ID) {
1352 last_error = ret;
1353 }
1354 }
1355 }
1356 }
1357
1358 if (autofill) {
1359 if (!CheckSignalAutoFill(tile, trackdir, signal_ctr, remove)) break;
1360
1361 /* Prevent possible loops */
1362 if (tile == start_tile && trackdir == start_trackdir) break;
1363 } else {
1364 if (tile == end_tile) break;
1365
1366 tile += ToTileIndexDiff(_trackdelta[trackdir]);
1367 signal_ctr++;
1368
1369 /* toggle railbit for the non-diagonal tracks (|, -- tracks) */
1370 if (IsDiagonalTrackdir(trackdir)) {
1371 signal_ctr++;
1372 } else {
1373 ToggleBit(trackdir, 0);
1374 }
1375 }
1376 }
1377
1378 return had_success ? total_cost : last_error;
1379 }
1380
1399 CommandCost CmdBuildSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1400 {
1401 return CmdSignalTrackHelper(tile, flags, p1, p2, text);
1402 }
1403
1416 CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1417 {
1418 Track track = Extract<Track, 0, 3>(p1);
1419
1420 if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) || !HasTrack(tile, track)) {
1421 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1422 }
1423 if (!HasSignalOnTrack(tile, track)) {
1424 return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1425 }
1426
1427 /* Only water can remove signals from anyone */
1428 if (_current_company != OWNER_WATER) {
1429 CommandCost ret = CheckTileOwnership(tile);
1430 if (ret.Failed()) return ret;
1431 }
1432
1433 /* Do it? */
1434 if (flags & DC_EXEC) {
1435 Train *v = NULL;
1436 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1437 v = GetTrainForReservation(tile, track);
1438 } else if (IsPbsSignal(GetSignalType(tile, track))) {
1439 /* PBS signal, might be the end of a path reservation. */
1440 Trackdir td = TrackToTrackdir(track);
1441 for (int i = 0; v == NULL && i < 2; i++, td = ReverseTrackdir(td)) {
1442 /* Only test the active signal side. */
1443 if (!HasSignalOnTrackdir(tile, ReverseTrackdir(td))) continue;
1444 TileIndex next = TileAddByDiagDir(tile, TrackdirToExitdir(td));
1445 TrackBits tracks = TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(td));
1446 if (HasReservedTracks(next, tracks)) {
1447 v = GetTrainForReservation(next, TrackBitsToTrack(GetReservedTrackbits(next) & tracks));
1448 }
1449 }
1450 }
1451 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1452 SetPresentSignals(tile, GetPresentSignals(tile) & ~SignalOnTrack(track));
1453 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1454 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1455
1456 /* removed last signal from tile? */
1457 if (GetPresentSignals(tile) == 0) {
1458 SetSignalStates(tile, 0);
1459 SetHasSignals(tile, false);
1460 SetSignalVariant(tile, INVALID_TRACK, SIG_ELECTRIC); // remove any possible semaphores
1461 }
1462
1463 AddTrackToSignalBuffer(tile, track, GetTileOwner(tile));
1464 YapfNotifyTrackLayoutChange(tile, track);
1465 if (v != NULL) TryPathReserve(v, false);
1466
1467 MarkTileDirtyByTile(tile);
1468 }
1469
1470 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_SIGNALS]);
1471 }
1472
1491 CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1492 {
1493 return CmdSignalTrackHelper(tile, flags, p1, SetBit(p2, 5), text); // bit 5 is remove bit
1494 }
1495
1497 static Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data)
1498 {
1499 if (v->type != VEH_TRAIN) return NULL;
1500
1501 TrainList *affected_trains = static_cast<TrainList*>(data);
1502 affected_trains->Include(Train::From(v)->First());
1503
1504 return NULL;
1505 }
1506
1519 CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1520 {
1521 RailType totype = Extract<RailType, 0, 4>(p2);
1522 TileIndex area_start = p1;
1523 TileIndex area_end = tile;
1524 bool diagonal = HasBit(p2, 4);
1525
1526 if (!ValParamRailtype(totype)) return CMD_ERROR;
1527 if (area_start >= MapSize()) return CMD_ERROR;
1528
1529 TrainList affected_trains;
1530
1531 CommandCost cost(EXPENSES_CONSTRUCTION);
1532 CommandCost error = CommandCost(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK); // by default, there is no track to convert.
1533
1534 TileIterator *iter = diagonal ? (TileIterator *)new DiagonalTileIterator(area_start, area_end) : new OrthogonalTileIterator(area_start, area_end);
1535 for (; (tile = *iter) != INVALID_TILE; ++(*iter)) {
1536 TileType tt = GetTileType(tile);
1537
1538 /* Check if there is any track on tile */
1539 switch (tt) {
1540 case MP_RAILWAY:
1541 break;
1542 case MP_STATION:
1543 if (!HasStationRail(tile)) continue;
1544 break;
1545 case MP_ROAD:
1546 if (!IsLevelCrossing(tile)) continue;
1547 if (RailNoLevelCrossings(totype)) {
1548 error.MakeError(STR_ERROR_CROSSING_DISALLOWED);
1549 continue;
1550 }
1551 break;
1552 case MP_TUNNELBRIDGE:
1553 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) continue;
1554 break;
1555 default: continue;
1556 }
1557
1558 /* Original railtype we are converting from */
1559 RailType type = GetRailType(tile);
1560
1561 /* Converting to the same type or converting 'hidden' elrail -> rail */
1562 if (type == totype || (_settings_game.vehicle.disable_elrails && totype == RAILTYPE_RAIL && type == RAILTYPE_ELECTRIC)) continue;
1563
1564 /* Trying to convert other's rail */
1565 CommandCost ret = CheckTileOwnership(tile);
1566 if (ret.Failed()) {
1567 error = ret;
1568 continue;
1569 }
1570
1571 SmallVector<Train *, 2> vehicles_affected;
1572
1573 /* Vehicle on the tile when not converting Rail <-> ElRail
1574 * Tunnels and bridges have special check later */
1575 if (tt != MP_TUNNELBRIDGE) {
1576 if (!IsCompatibleRail(type, totype)) {
1577 CommandCost ret = EnsureNoVehicleOnGround(tile);
1578 if (ret.Failed()) {
1579 error = ret;
1580 continue;
1581 }
1582 }
1583 if (flags & DC_EXEC) { // we can safely convert, too
1584 TrackBits reserved = GetReservedTrackbits(tile);
1585 Track track;
1586 while ((track = RemoveFirstTrack(&reserved)) != INVALID_TRACK) {
1587 Train *v = GetTrainForReservation(tile, track);
1588 if (v != NULL && !HasPowerOnRail(v->railtype, totype)) {
1589 /* No power on new rail type, reroute. */
1590 FreeTrainTrackReservation(v);
1591 *vehicles_affected.Append() = v;
1592 }
1593 }
1594
1595 /* Update the company infrastructure counters. */
1596 if (!IsRailStationTile(tile) || !IsStationTileBlocked(tile)) {
1597 Company *c = Company::Get(GetTileOwner(tile));
1598 uint num_pieces = IsLevelCrossingTile(tile) ? LEVELCROSSING_TRACKBIT_FACTOR : 1;
1599 if (IsPlainRailTile(tile)) {
1600 TrackBits bits = GetTrackBits(tile);
1601 num_pieces = CountBits(bits);
1602 if (TracksOverlap(bits)) num_pieces *= num_pieces;
1603 }
1604 c->infrastructure.rail[type] -= num_pieces;
1605 c->infrastructure.rail[totype] += num_pieces;
1606 DirtyCompanyInfrastructureWindows(c->index);
1607 }
1608
1609 SetRailType(tile, totype);
1610 MarkTileDirtyByTile(tile);
1611 /* update power of train on this tile */
1612 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1613 }
1614 }
1615
1616 switch (tt) {
1617 case MP_RAILWAY:
1618 switch (GetRailTileType(tile)) {
1619 case RAIL_TILE_DEPOT:
1620 if (flags & DC_EXEC) {
1621 /* notify YAPF about the track layout change */
1622 YapfNotifyTrackLayoutChange(tile, GetRailDepotTrack(tile));
1623
1624 /* Update build vehicle window related to this depot */
1625 InvalidateWindowData(WC_VEHICLE_DEPOT, tile);
1626 InvalidateWindowData(WC_BUILD_VEHICLE, tile);
1627 }
1628 cost.AddCost(RailConvertCost(type, totype));
1629 break;
1630
1631 default: // RAIL_TILE_NORMAL, RAIL_TILE_SIGNALS
1632 if (flags & DC_EXEC) {
1633 /* notify YAPF about the track layout change */
1634 TrackBits tracks = GetTrackBits(tile);
1635 while (tracks != TRACK_BIT_NONE) {
1636 YapfNotifyTrackLayoutChange(tile, RemoveFirstTrack(&tracks));
1637 }
1638 }
1639 cost.AddCost(RailConvertCost(type, totype) * CountBits(GetTrackBits(tile)));
1640 break;
1641 }
1642 break;
1643
1644 case MP_TUNNELBRIDGE: {
1645 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
1646
1647 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
1648 * it would cause assert because of different test and exec runs */
1649 if (endtile < tile) {
1650 if (diagonal) {
1651 if (DiagonalTileArea(area_start, area_end).Contains(endtile)) continue;
1652 } else {
1653 if (OrthogonalTileArea(area_start, area_end).Contains(endtile)) continue;
1654 }
1655 }
1656
1657 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
1658 if (!IsCompatibleRail(GetRailType(tile), totype)) {
1659 CommandCost ret = TunnelBridgeIsFree(tile, endtile);
1660 if (ret.Failed()) {
1661 error = ret;
1662 continue;
1663 }
1664 }
1665
1666 if (flags & DC_EXEC) {
1667 Track track = DiagDirToDiagTrack(GetTunnelBridgeDirection(tile));
1668 if (HasTunnelBridgeReservation(tile)) {
1669 Train *v = GetTrainForReservation(tile, track);
1670 if (v != NULL && !HasPowerOnRail(v->railtype, totype)) {
1671 /* No power on new rail type, reroute. */
1672 FreeTrainTrackReservation(v);
1673 *vehicles_affected.Append() = v;
1674 }
1675 }
1676
1677 /* Update the company infrastructure counters. */
1678 uint num_pieces = (GetTunnelBridgeLength(tile, endtile) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1679 Company *c = Company::Get(GetTileOwner(tile));
1680 c->infrastructure.rail[GetRailType(tile)] -= num_pieces;
1681 c->infrastructure.rail[totype] += num_pieces;
1682 DirtyCompanyInfrastructureWindows(c->index);
1683
1684 SetRailType(tile, totype);
1685 SetRailType(endtile, totype);
1686
1687 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1688 FindVehicleOnPos(endtile, &affected_trains, &UpdateTrainPowerProc);
1689
1690 YapfNotifyTrackLayoutChange(tile, track);
1691 YapfNotifyTrackLayoutChange(endtile, track);
1692
1693 if (IsBridge(tile)) {
1694 MarkBridgeDirty(tile);
1695 } else {
1696 MarkTileDirtyByTile(tile);
1697 MarkTileDirtyByTile(endtile);
1698 }
1699 }
1700
1701 cost.AddCost((GetTunnelBridgeLength(tile, endtile) + 2) * RailConvertCost(type, totype));
1702 break;
1703 }
1704
1705 default: // MP_STATION, MP_ROAD
1706 if (flags & DC_EXEC) {
1707 Track track = ((tt == MP_STATION) ? GetRailStationTrack(tile) : GetCrossingRailTrack(tile));
1708 YapfNotifyTrackLayoutChange(tile, track);
1709 }
1710
1711 cost.AddCost(RailConvertCost(type, totype));
1712 break;
1713 }
1714
1715 for (uint i = 0; i < vehicles_affected.Length(); ++i) {
1716 TryPathReserve(vehicles_affected[i], true);
1717 }
1718 }
1719
1720 if (flags & DC_EXEC) {
1721 /* Railtype changed, update trains as when entering different track */
1722 for (Train **v = affected_trains.Begin(); v != affected_trains.End(); v++) {
1723 (*v)->ConsistChanged(CCF_TRACK);
1724 }
1725 }
1726
1727 delete iter;
1728 return (cost.GetCost() == 0) ? error : cost;
1729 }
1730
1731 static CommandCost RemoveTrainDepot(TileIndex tile, DoCommandFlag flags)
1732 {
1733 if (_current_company != OWNER_WATER) {
1734 CommandCost ret = CheckTileOwnership(tile);
1735 if (ret.Failed()) return ret;
1736 }
1737
1738 CommandCost ret = EnsureNoVehicleOnGround(tile);
1739 if (ret.Failed()) return ret;
1740
1741 if (flags & DC_EXEC) {
1742 /* read variables before the depot is removed */
1743 DiagDirection dir = GetRailDepotDirection(tile);
1744 Owner owner = GetTileOwner(tile);
1745 Train *v = NULL;
1746
1747 if (HasDepotReservation(tile)) {
1748 v = GetTrainForReservation(tile, DiagDirToDiagTrack(dir));
1749 if (v != NULL) FreeTrainTrackReservation(v);
1750 }
1751
1752 Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1753 DirtyCompanyInfrastructureWindows(owner);
1754
1755 delete Depot::GetByTile(tile);
1756 DoClearSquare(tile);
1757 AddSideToSignalBuffer(tile, dir, owner);
1758 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
1759 if (v != NULL) TryPathReserve(v, true);
1760 }
1761
1762 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_TRAIN]);
1763 }
1764
1765 static CommandCost ClearTile_Track(TileIndex tile, DoCommandFlag flags)
1766 {
1767 CommandCost cost(EXPENSES_CONSTRUCTION);
1768
1769 if (flags & DC_AUTO) {
1770 if (!IsTileOwner(tile, _current_company)) {
1771 return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
1772 }
1773
1774 if (IsPlainRail(tile)) {
1775 return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
1776 } else {
1777 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
1778 }
1779 }
1780
1781 switch (GetRailTileType(tile)) {
1782 case RAIL_TILE_SIGNALS:
1783 case RAIL_TILE_NORMAL: {
1784 Slope tileh = GetTileSlope(tile);
1785 /* Is there flat water on the lower halftile that gets cleared expensively? */
1786 bool water_ground = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh));
1787
1788 TrackBits tracks = GetTrackBits(tile);
1789 while (tracks != TRACK_BIT_NONE) {
1790 Track track = RemoveFirstTrack(&tracks);
1791 CommandCost ret = DoCommand(tile, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
1792 if (ret.Failed()) return ret;
1793 cost.AddCost(ret);
1794 }
1795
1796 /* When bankrupting, don't make water dirty, there could be a ship on lower halftile.
1797 * Same holds for non-companies clearing the tile, e.g. disasters. */
1798 if (water_ground && !(flags & DC_BANKRUPT) && Company::IsValidID(_current_company)) {
1799 CommandCost ret = EnsureNoVehicleOnGround(tile);
1800 if (ret.Failed()) return ret;
1801
1802 /* The track was removed, and left a coast tile. Now also clear the water. */
1803 if (flags & DC_EXEC) DoClearSquare(tile);
1804 cost.AddCost(_price[PR_CLEAR_WATER]);
1805 }
1806
1807 return cost;
1808 }
1809
1810 case RAIL_TILE_DEPOT:
1811 return RemoveTrainDepot(tile, flags);
1812
1813 default:
1814 return CMD_ERROR;
1815 }
1816 }
1817
1822 static uint GetSaveSlopeZ(uint x, uint y, Track track)
1823 {
1824 switch (track) {
1825 case TRACK_UPPER: x &= ~0xF; y &= ~0xF; break;
1826 case TRACK_LOWER: x |= 0xF; y |= 0xF; break;
1827 case TRACK_LEFT: x |= 0xF; y &= ~0xF; break;
1828 case TRACK_RIGHT: x &= ~0xF; y |= 0xF; break;
1829 default: break;
1830 }
1831 return GetSlopePixelZ(x, y);
1832 }
1833
1834 static void DrawSingleSignal(TileIndex tile, const RailtypeInfo *rti, Track track, SignalState condition, SignalOffsets image, uint pos)
1835 {
1836 bool side;
1837 switch (_settings_game.construction.train_signal_side) {
1838 case 0: side = false; break; // left
1839 case 2: side = true; break; // right
1840 default: side = _settings_game.vehicle.road_side != 0; break; // driving side
1841 }
1842 static const Point SignalPositions[2][12] = {
1843 { // Signals on the left side
1844 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1845 { 8, 5}, {14, 1}, { 1, 14}, { 9, 11}, { 1, 0}, { 3, 10},
1846 /* LOWER LOWER X X Y Y */
1847 {11, 4}, {14, 14}, {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
1848 }, { // Signals on the right side
1849 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1850 {14, 1}, {12, 10}, { 4, 6}, { 1, 14}, {10, 4}, { 0, 1},
1851 /* LOWER LOWER X X Y Y */
1852 {14, 14}, { 5, 12}, {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
1853 }
1854 };
1855
1856 uint x = TileX(tile) * TILE_SIZE + SignalPositions[side][pos].x;
1857 uint y = TileY(tile) * TILE_SIZE + SignalPositions[side][pos].y;
1858
1859 SignalType type = GetSignalType(tile, track);
1860 SignalVariant variant = GetSignalVariant(tile, track);
1861
1862 SpriteID sprite = GetCustomSignalSprite(rti, tile, type, variant, condition);
1863 if (sprite != 0) {
1864 sprite += image;
1865 } else {
1866 /* Normal electric signals are stored in a different sprite block than all other signals. */
1867 sprite = (type == SIGTYPE_NORMAL && variant == SIG_ELECTRIC) ? SPR_ORIGINAL_SIGNALS_BASE : SPR_SIGNALS_BASE - 16;
1868 sprite += type * 16 + variant * 64 + image * 2 + condition + (type > SIGTYPE_LAST_NOPBS ? 64 : 0);
1869 }
1870
1871 AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, BB_HEIGHT_UNDER_BRIDGE, GetSaveSlopeZ(x, y, track));
1872 }
1873
1874 static uint32 _drawtile_track_palette;
1875
1876
1877
1879 struct FenceOffset {
1880 Corner height_ref;
1881 int x_offs;
1882 int y_offs;
1883 int x_size;
1884 int y_size;
1885 };
1886
1888 static FenceOffset _fence_offsets[] = {
1889 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_FLAT_X_NW
1890 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_FLAT_Y_NE
1891 { CORNER_W, 8, 8, 1, 1 }, // RFO_FLAT_LEFT
1892 { CORNER_N, 8, 8, 1, 1 }, // RFO_FLAT_UPPER
1893 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_SW_NW
1894 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_SE_NE
1895 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_NE_NW
1896 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_NW_NE
1897 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_FLAT_X_SE
1898 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_FLAT_Y_SW
1899 { CORNER_E, 8, 8, 1, 1 }, // RFO_FLAT_RIGHT
1900 { CORNER_S, 8, 8, 1, 1 }, // RFO_FLAT_LOWER
1901 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_SW_SE
1902 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_SE_SW
1903 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_NE_SE
1904 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_NW_SW
1905 };
1906
1914 static void DrawTrackFence(const TileInfo *ti, SpriteID base_image, uint num_sprites, RailFenceOffset rfo)
1915 {
1916 int z = ti->z;
1917 if (_fence_offsets[rfo].height_ref != CORNER_INVALID) {
1918 z += GetSlopePixelZInCorner(RemoveHalftileSlope(ti->tileh), _fence_offsets[rfo].height_ref);
1919 }
1920 AddSortableSpriteToDraw(base_image + (rfo % num_sprites), _drawtile_track_palette,
1921 ti->x + _fence_offsets[rfo].x_offs,
1922 ti->y + _fence_offsets[rfo].y_offs,
1923 _fence_offsets[rfo].x_size,
1924 _fence_offsets[rfo].y_size,
1925 4, z);
1926 }
1927
1931 static void DrawTrackFence_NW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1932 {
1933 RailFenceOffset rfo = RFO_FLAT_X_NW;
1934 if (ti->tileh & SLOPE_NW) rfo = (ti->tileh & SLOPE_W) ? RFO_SLOPE_SW_NW : RFO_SLOPE_NE_NW;
1935 DrawTrackFence(ti, base_image, num_sprites, rfo);
1936 }
1937
1941 static void DrawTrackFence_SE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1942 {
1943 RailFenceOffset rfo = RFO_FLAT_X_SE;
1944 if (ti->tileh & SLOPE_SE) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SW_SE : RFO_SLOPE_NE_SE;
1945 DrawTrackFence(ti, base_image, num_sprites, rfo);
1946 }
1947
1951 static void DrawTrackFence_NE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1952 {
1953 RailFenceOffset rfo = RFO_FLAT_Y_NE;
1954 if (ti->tileh & SLOPE_NE) rfo = (ti->tileh & SLOPE_E) ? RFO_SLOPE_SE_NE : RFO_SLOPE_NW_NE;
1955 DrawTrackFence(ti, base_image, num_sprites, rfo);
1956 }
1957
1961 static void DrawTrackFence_SW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1962 {
1963 RailFenceOffset rfo = RFO_FLAT_Y_SW;
1964 if (ti->tileh & SLOPE_SW) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SE_SW : RFO_SLOPE_NW_SW;
1965 DrawTrackFence(ti, base_image, num_sprites, rfo);
1966 }
1967
1973 static void DrawTrackDetails(const TileInfo *ti, const RailtypeInfo *rti)
1974 {
1975 /* Base sprite for track fences.
1976 * Note: Halftile slopes only have fences on the upper part. */
1977 uint num_sprites = 0;
1978 SpriteID base_image = GetCustomRailSprite(rti, ti->tile, RTSG_FENCES, IsHalftileSlope(ti->tileh) ? TCX_UPPER_HALFTILE : TCX_NORMAL);
1979 if (base_image == 0) {
1980 base_image = SPR_TRACK_FENCE_FLAT_X;
1981 num_sprites = 8;
1982 }
1983
1984 assert(num_sprites > 0);
1985
1986 switch (GetRailGroundType(ti->tile)) {
1987 case RAIL_GROUND_FENCE_NW: DrawTrackFence_NW(ti, base_image, num_sprites); break;
1988 case RAIL_GROUND_FENCE_SE: DrawTrackFence_SE(ti, base_image, num_sprites); break;
1989 case RAIL_GROUND_FENCE_SENW: DrawTrackFence_NW(ti, base_image, num_sprites);
1990 DrawTrackFence_SE(ti, base_image, num_sprites); break;
1991 case RAIL_GROUND_FENCE_NE: DrawTrackFence_NE(ti, base_image, num_sprites); break;
1992 case RAIL_GROUND_FENCE_SW: DrawTrackFence_SW(ti, base_image, num_sprites); break;
1993 case RAIL_GROUND_FENCE_NESW: DrawTrackFence_NE(ti, base_image, num_sprites);
1994 DrawTrackFence_SW(ti, base_image, num_sprites); break;
1995 case RAIL_GROUND_FENCE_VERT1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
1996 case RAIL_GROUND_FENCE_VERT2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
1997 case RAIL_GROUND_FENCE_HORIZ1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
1998 case RAIL_GROUND_FENCE_HORIZ2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
1999 case RAIL_GROUND_WATER: {
2000 Corner track_corner;
2001 if (IsHalftileSlope(ti->tileh)) {
2002 /* Steep slope or one-corner-raised slope with halftile foundation */
2003 track_corner = GetHalftileSlopeCorner(ti->tileh);
2004 } else {
2005 /* Three-corner-raised slope */
2006 track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2007 }
2008 switch (track_corner) {
2009 case CORNER_W: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2010 case CORNER_S: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2011 case CORNER_E: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2012 case CORNER_N: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2013 default: NOT_REACHED();
2014 }
2015 break;
2016 }
2017 default: break;
2018 }
2019 }
2020
2021 /* SubSprite for drawing the track halftile of 'three-corners-raised'-sloped rail sprites. */
2022 static const int INF = 1000; // big number compared to tilesprite size
2023 static const SubSprite _halftile_sub_sprite[4] = {
2024 { -INF , -INF , 32 - 33, INF }, // CORNER_W, clip 33 pixels from right
2025 { -INF , 0 + 7, INF , INF }, // CORNER_S, clip 7 pixels from top
2026 { -31 + 33, -INF , INF , INF }, // CORNER_E, clip 33 pixels from left
2027 { -INF , -INF , INF , 30 - 23 } // CORNER_N, clip 23 pixels from bottom
2028 };
2029
2030 static inline void DrawTrackSprite(SpriteID sprite, PaletteID pal, const TileInfo *ti, Slope s)
2031 {
2032 DrawGroundSprite(sprite, pal, NULL, 0, (ti->tileh & s) ? -8 : 0);
2033 }
2034
2035 static void DrawTrackBitsOverlay(TileInfo *ti, TrackBits track, const RailtypeInfo *rti)
2036 {
2037 RailGroundType rgt = GetRailGroundType(ti->tile);
2038 Foundation f = GetRailFoundation(ti->tileh, track);
2039 Corner halftile_corner = CORNER_INVALID;
2040
2041 if (IsNonContinuousFoundation(f)) {
2042 /* Save halftile corner */
2043 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2044 /* Draw lower part first */
2045 track &= ~CornerToTrackBits(halftile_corner);
2046 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2047 }
2048
2049 DrawFoundation(ti, f);
2050 /* DrawFoundation modifies ti */
2051
2052 /* Draw ground */
2053 if (rgt == RAIL_GROUND_WATER) {
2054 if (track != TRACK_BIT_NONE || IsSteepSlope(ti->tileh)) {
2055 /* three-corner-raised slope or steep slope with track on upper part */
2056 DrawShoreTile(ti->tileh);
2057 } else {
2058 /* single-corner-raised slope with track on upper part */
2059 DrawGroundSprite(SPR_FLAT_WATER_TILE, PAL_NONE);
2060 }
2061 } else {
2062 SpriteID image;
2063
2064 switch (rgt) {
2065 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2066 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2067 default: image = SPR_FLAT_GRASS_TILE; break;
2068 }
2069
2070 image += SlopeToSpriteOffset(ti->tileh);
2071
2072 DrawGroundSprite(image, PAL_NONE);
2073 }
2074
2075 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2076 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2077 TrackBits pbs = _settings_client.gui.show_track_reservation ? GetRailReservationTrackBits(ti->tile) : TRACK_BIT_NONE;
2078
2079 if (track == TRACK_BIT_NONE) {
2080 /* Half-tile foundation, no track here? */
2081 } else if (ti->tileh == SLOPE_NW && track == TRACK_BIT_Y) {
2082 DrawGroundSprite(ground + RTO_SLOPE_NW, PAL_NONE);
2083 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NW, PALETTE_CRASH);
2084 } else if (ti->tileh == SLOPE_NE && track == TRACK_BIT_X) {
2085 DrawGroundSprite(ground + RTO_SLOPE_NE, PAL_NONE);
2086 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NE, PALETTE_CRASH);
2087 } else if (ti->tileh == SLOPE_SE && track == TRACK_BIT_Y) {
2088 DrawGroundSprite(ground + RTO_SLOPE_SE, PAL_NONE);
2089 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SE, PALETTE_CRASH);
2090 } else if (ti->tileh == SLOPE_SW && track == TRACK_BIT_X) {
2091 DrawGroundSprite(ground + RTO_SLOPE_SW, PAL_NONE);
2092 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SW, PALETTE_CRASH);
2093 } else {
2094 switch (track) {
2095 /* Draw single ground sprite when not overlapping. No track overlay
2096 * is necessary for these sprites. */
2097 case TRACK_BIT_X: DrawGroundSprite(ground + RTO_X, PAL_NONE); break;
2098 case TRACK_BIT_Y: DrawGroundSprite(ground + RTO_Y, PAL_NONE); break;
2099 case TRACK_BIT_UPPER: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N); break;
2100 case TRACK_BIT_LOWER: DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2101 case TRACK_BIT_RIGHT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E); break;
2102 case TRACK_BIT_LEFT: DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2103 case TRACK_BIT_CROSS: DrawGroundSprite(ground + RTO_CROSSING_XY, PAL_NONE); break;
2104 case TRACK_BIT_HORZ: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N);
2105 DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2106 case TRACK_BIT_VERT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E);
2107 DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2108
2109 default:
2110 /* We're drawing a junction tile */
2111 if ((track & TRACK_BIT_3WAY_NE) == 0) {
2112 DrawGroundSprite(ground + RTO_JUNCTION_SW, PAL_NONE);
2113 } else if ((track & TRACK_BIT_3WAY_SW) == 0) {
2114 DrawGroundSprite(ground + RTO_JUNCTION_NE, PAL_NONE);
2115 } else if ((track & TRACK_BIT_3WAY_NW) == 0) {
2116 DrawGroundSprite(ground + RTO_JUNCTION_SE, PAL_NONE);
2117 } else if ((track & TRACK_BIT_3WAY_SE) == 0) {
2118 DrawGroundSprite(ground + RTO_JUNCTION_NW, PAL_NONE);
2119 } else {
2120 DrawGroundSprite(ground + RTO_JUNCTION_NSEW, PAL_NONE);
2121 }
2122
2123 /* Mask out PBS bits as we shall draw them afterwards anyway. */
2124 track &= ~pbs;
2125
2126 /* Draw regular track bits */
2127 if (track & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PAL_NONE);
2128 if (track & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PAL_NONE);
2129 if (track & TRACK_BIT_UPPER) DrawGroundSprite(overlay + RTO_N, PAL_NONE);
2130 if (track & TRACK_BIT_LOWER) DrawGroundSprite(overlay + RTO_S, PAL_NONE);
2131 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(overlay + RTO_E, PAL_NONE);
2132 if (track & TRACK_BIT_LEFT) DrawGroundSprite(overlay + RTO_W, PAL_NONE);
2133 }
2134
2135 /* Draw reserved track bits */
2136 if (pbs & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2137 if (pbs & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2138 if (pbs & TRACK_BIT_UPPER) DrawTrackSprite(overlay + RTO_N, PALETTE_CRASH, ti, SLOPE_N);
2139 if (pbs & TRACK_BIT_LOWER) DrawTrackSprite(overlay + RTO_S, PALETTE_CRASH, ti, SLOPE_S);
2140 if (pbs & TRACK_BIT_RIGHT) DrawTrackSprite(overlay + RTO_E, PALETTE_CRASH, ti, SLOPE_E);
2141 if (pbs & TRACK_BIT_LEFT) DrawTrackSprite(overlay + RTO_W, PALETTE_CRASH, ti, SLOPE_W);
2142 }
2143
2144 if (IsValidCorner(halftile_corner)) {
2145 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2146 overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY, TCX_UPPER_HALFTILE);
2147 ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND, TCX_UPPER_HALFTILE);
2148
2149 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2150 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2151
2152 SpriteID image;
2153 switch (rgt) {
2154 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2155 case RAIL_GROUND_ICE_DESERT:
2156 case RAIL_GROUND_HALF_SNOW: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2157 default: image = SPR_FLAT_GRASS_TILE; break;
2158 }
2159
2160 image += SlopeToSpriteOffset(fake_slope);
2161
2162 DrawGroundSprite(image, PAL_NONE, &(_halftile_sub_sprite[halftile_corner]));
2163
2164 track = CornerToTrackBits(halftile_corner);
2165
2166 int offset;
2167 switch (track) {
2168 default: NOT_REACHED();
2169 case TRACK_BIT_UPPER: offset = RTO_N; break;
2170 case TRACK_BIT_LOWER: offset = RTO_S; break;
2171 case TRACK_BIT_RIGHT: offset = RTO_E; break;
2172 case TRACK_BIT_LEFT: offset = RTO_W; break;
2173 }
2174
2175 DrawTrackSprite(ground + offset, PAL_NONE, ti, fake_slope);
2176 if (_settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, track)) {
2177 DrawTrackSprite(overlay + offset, PALETTE_CRASH, ti, fake_slope);
2178 }
2179 }
2180 }
2181
2187 static void DrawTrackBits(TileInfo *ti, TrackBits track)
2188 {
2189 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2190
2191 if (rti->UsesOverlay()) {
2192 DrawTrackBitsOverlay(ti, track, rti);
2193 return;
2194 }
2195
2196 RailGroundType rgt = GetRailGroundType(ti->tile);
2197 Foundation f = GetRailFoundation(ti->tileh, track);
2198 Corner halftile_corner = CORNER_INVALID;
2199
2200 if (IsNonContinuousFoundation(f)) {
2201 /* Save halftile corner */
2202 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2203 /* Draw lower part first */
2204 track &= ~CornerToTrackBits(halftile_corner);
2205 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2206 }
2207
2208 DrawFoundation(ti, f);
2209 /* DrawFoundation modifies ti */
2210
2211 SpriteID image;
2212 PaletteID pal = PAL_NONE;
2213 const SubSprite *sub = NULL;
2214 bool junction = false;
2215
2216 /* Select the sprite to use. */
2217 if (track == 0) {
2218 /* Clear ground (only track on halftile foundation) */
2219 if (rgt == RAIL_GROUND_WATER) {
2220 if (IsSteepSlope(ti->tileh)) {
2221 DrawShoreTile(ti->tileh);
2222 image = 0;
2223 } else {
2224 image = SPR_FLAT_WATER_TILE;
2225 }
2226 } else {
2227 switch (rgt) {
2228 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2229 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2230 default: image = SPR_FLAT_GRASS_TILE; break;
2231 }
2232 image += SlopeToSpriteOffset(ti->tileh);
2233 }
2234 } else {
2235 if (ti->tileh != SLOPE_FLAT) {
2236 /* track on non-flat ground */
2237 image = _track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.track_y;
2238 } else {
2239 /* track on flat ground */
2240 (image = rti->base_sprites.track_y, track == TRACK_BIT_Y) ||
2241 (image++, track == TRACK_BIT_X) ||
2242 (image++, track == TRACK_BIT_UPPER) ||
2243 (image++, track == TRACK_BIT_LOWER) ||
2244 (image++, track == TRACK_BIT_RIGHT) ||
2245 (image++, track == TRACK_BIT_LEFT) ||
2246 (image++, track == TRACK_BIT_CROSS) ||
2247
2248 (image = rti->base_sprites.track_ns, track == TRACK_BIT_HORZ) ||
2249 (image++, track == TRACK_BIT_VERT) ||
2250
2251 (junction = true, false) ||
2252 (image = rti->base_sprites.ground, (track & TRACK_BIT_3WAY_NE) == 0) ||
2253 (image++, (track & TRACK_BIT_3WAY_SW) == 0) ||
2254 (image++, (track & TRACK_BIT_3WAY_NW) == 0) ||
2255 (image++, (track & TRACK_BIT_3WAY_SE) == 0) ||
2256 (image++, true);
2257 }
2258
2259 switch (rgt) {
2260 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2261 case RAIL_GROUND_ICE_DESERT: image += rti->snow_offset; break;
2262 case RAIL_GROUND_WATER: {
2263 /* three-corner-raised slope */
2264 DrawShoreTile(ti->tileh);
2265 Corner track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2266 sub = &(_halftile_sub_sprite[track_corner]);
2267 break;
2268 }
2269 default: break;
2270 }
2271 }
2272
2273 if (image != 0) DrawGroundSprite(image, pal, sub);
2274
2275 /* Draw track pieces individually for junction tiles */
2276 if (junction) {
2277 if (track & TRACK_BIT_X) DrawGroundSprite(rti->base_sprites.single_x, PAL_NONE);
2278 if (track & TRACK_BIT_Y) DrawGroundSprite(rti->base_sprites.single_y, PAL_NONE);
2279 if (track & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PAL_NONE);
2280 if (track & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PAL_NONE);
2281 if (track & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PAL_NONE);
2282 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PAL_NONE);
2283 }
2284
2285 /* PBS debugging, draw reserved tracks darker */
2286 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation) {
2287 /* Get reservation, but mask track on halftile slope */
2288 TrackBits pbs = GetRailReservationTrackBits(ti->tile) & track;
2289 if (pbs & TRACK_BIT_X) {
2290 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2291 DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
2292 } else {
2293 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2294 }
2295 }
2296 if (pbs & TRACK_BIT_Y) {
2297 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2298 DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
2299 } else {
2300 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2301 }
2302 }
2303 if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_N ? -(int)TILE_HEIGHT : 0);
2304 if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_S ? -(int)TILE_HEIGHT : 0);
2305 if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_W ? -(int)TILE_HEIGHT : 0);
2306 if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_E ? -(int)TILE_HEIGHT : 0);
2307 }
2308
2309 if (IsValidCorner(halftile_corner)) {
2310 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2311
2312 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2313 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2314 image = _track_sloped_sprites[fake_slope - 1] + rti->base_sprites.track_y;
2315 pal = PAL_NONE;
2316 switch (rgt) {
2317 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2318 case RAIL_GROUND_ICE_DESERT:
2319 case RAIL_GROUND_HALF_SNOW: image += rti->snow_offset; break; // higher part has snow in this case too
2320 default: break;
2321 }
2322 DrawGroundSprite(image, pal, &(_halftile_sub_sprite[halftile_corner]));
2323
2324 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
2325 static const byte _corner_to_track_sprite[] = {3, 1, 2, 0};
2326 DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, -(int)TILE_HEIGHT);
2327 }
2328 }
2329 }
2330
2331 static void DrawSignals(TileIndex tile, TrackBits rails, const RailtypeInfo *rti)
2332 {
2333 #define MAYBE_DRAW_SIGNAL(x, y, z, t) if (IsSignalPresent(tile, x)) DrawSingleSignal(tile, rti, t, GetSingleSignalState(tile, x), y, z)
2334
2335 if (!(rails & TRACK_BIT_Y)) {
2336 if (!(rails & TRACK_BIT_X)) {
2337 if (rails & TRACK_BIT_LEFT) {
2338 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTH, 0, TRACK_LEFT);
2339 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTH, 1, TRACK_LEFT);
2340 }
2341 if (rails & TRACK_BIT_RIGHT) {
2342 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_NORTH, 2, TRACK_RIGHT);
2343 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_SOUTH, 3, TRACK_RIGHT);
2344 }
2345 if (rails & TRACK_BIT_UPPER) {
2346 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_WEST, 4, TRACK_UPPER);
2347 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_EAST, 5, TRACK_UPPER);
2348 }
2349 if (rails & TRACK_BIT_LOWER) {
2350 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_WEST, 6, TRACK_LOWER);
2351 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_EAST, 7, TRACK_LOWER);
2352 }
2353 } else {
2354 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHWEST, 8, TRACK_X);
2355 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHEAST, 9, TRACK_X);
2356 }
2357 } else {
2358 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHEAST, 10, TRACK_Y);
2359 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHWEST, 11, TRACK_Y);
2360 }
2361 }
2362
2363 static void DrawTile_Track(TileInfo *ti)
2364 {
2365 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2366
2367 _drawtile_track_palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
2368
2369 if (IsPlainRail(ti->tile)) {
2370 TrackBits rails = GetTrackBits(ti->tile);
2371
2372 DrawTrackBits(ti, rails);
2373
2374 if (HasBit(_display_opt, DO_FULL_DETAIL)) DrawTrackDetails(ti, rti);
2375
2376 if (HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
2377
2378 if (HasSignals(ti->tile)) DrawSignals(ti->tile, rails, rti);
2379 } else {
2380 /* draw depot */
2381 const DrawTileSprites *dts;
2382 PaletteID pal = PAL_NONE;
2383 SpriteID relocation;
2384
2385 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
2386
2387 if (IsInvisibilitySet(TO_BUILDINGS)) {
2388 /* Draw rail instead of depot */
2389 dts = &_depot_invisible_gfx_table[GetRailDepotDirection(ti->tile)];
2390 } else {
2391 dts = &_depot_gfx_table[GetRailDepotDirection(ti->tile)];
2392 }
2393
2394 SpriteID image;
2395 if (rti->UsesOverlay()) {
2396 image = SPR_FLAT_GRASS_TILE;
2397 } else {
2398 image = dts->ground.sprite;
2399 if (image != SPR_FLAT_GRASS_TILE) image += rti->GetRailtypeSpriteOffset();
2400 }
2401
2402 /* adjust ground tile for desert
2403 * don't adjust for snow, because snow in depots looks weird */
2404 if (IsSnowRailGround(ti->tile) && _settings_game.game_creation.landscape == LT_TROPIC) {
2405 if (image != SPR_FLAT_GRASS_TILE) {
2406 image += rti->snow_offset; // tile with tracks
2407 } else {
2408 image = SPR_FLAT_SNOW_DESERT_TILE; // flat ground
2409 }
2410 }
2411
2412 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, _drawtile_track_palette));
2413
2414 if (rti->UsesOverlay()) {
2415 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2416
2417 switch (GetRailDepotDirection(ti->tile)) {
2418 case DIAGDIR_NE: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2419 case DIAGDIR_SW: DrawGroundSprite(ground + RTO_X, PAL_NONE); break;
2420 case DIAGDIR_NW: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2421 case DIAGDIR_SE: DrawGroundSprite(ground + RTO_Y, PAL_NONE); break;
2422 default: break;
2423 }
2424
2425 if (_settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2426 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2427
2428 switch (GetRailDepotDirection(ti->tile)) {
2429 case DIAGDIR_NE: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2430 case DIAGDIR_SW: DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH); break;
2431 case DIAGDIR_NW: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2432 case DIAGDIR_SE: DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH); break;
2433 default: break;
2434 }
2435 }
2436 } else {
2437 /* PBS debugging, draw reserved tracks darker */
2438 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2439 switch (GetRailDepotDirection(ti->tile)) {
2440 case DIAGDIR_NE: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2441 case DIAGDIR_SW: DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH); break;
2442 case DIAGDIR_NW: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2443 case DIAGDIR_SE: DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH); break;
2444 default: break;
2445 }
2446 }
2447 }
2448 int depot_sprite = GetCustomRailSprite(rti, ti->tile, RTSG_DEPOT);
2449 relocation = depot_sprite != 0 ? depot_sprite - SPR_RAIL_DEPOT_SE_1 : rti->GetRailtypeSpriteOffset();
2450
2451 if (HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
2452
2453 DrawRailTileSeq(ti, dts, TO_BUILDINGS, relocation, 0, _drawtile_track_palette);
2454 }
2455 DrawBridgeMiddle(ti);
2456 }
2457
2458 void DrawTrainDepotSprite(int x, int y, int dir, RailType railtype)
2459 {
2460 const DrawTileSprites *dts = &_depot_gfx_table[dir];
2461 const RailtypeInfo *rti = GetRailTypeInfo(railtype);
2462 SpriteID image = rti->UsesOverlay() ? SPR_FLAT_GRASS_TILE : dts->ground.sprite;
2463 uint32 offset = rti->GetRailtypeSpriteOffset();
2464
2465 if (image != SPR_FLAT_GRASS_TILE) image += offset;
2466 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
2467
2468 DrawSprite(image, PAL_NONE, x, y);
2469
2470 if (rti->UsesOverlay()) {
2471 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
2472
2473 switch (dir) {
2474 case DIAGDIR_SW: DrawSprite(ground + RTO_X, PAL_NONE, x, y); break;
2475 case DIAGDIR_SE: DrawSprite(ground + RTO_Y, PAL_NONE, x, y); break;
2476 default: break;
2477 }
2478 }
2479 int depot_sprite = GetCustomRailSprite(rti, INVALID_TILE, RTSG_DEPOT);
2480 if (depot_sprite != 0) offset = depot_sprite - SPR_RAIL_DEPOT_SE_1;
2481
2482 DrawRailTileSeqInGUI(x, y, dts, offset, 0, palette);
2483 }
2484
2485 static int GetSlopePixelZ_Track(TileIndex tile, uint x, uint y)
2486 {
2487 if (IsPlainRail(tile)) {
2488 int z;
2489 Slope tileh = GetTilePixelSlope(tile, &z);
2490 if (tileh == SLOPE_FLAT) return z;
2491
2492 z += ApplyPixelFoundationToSlope(GetRailFoundation(tileh, GetTrackBits(tile)), &tileh);
2493 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
2494 } else {
2495 return GetTileMaxPixelZ(tile);
2496 }
2497 }
2498
2499 static Foundation GetFoundation_Track(TileIndex tile, Slope tileh)
2500 {
2501 return IsPlainRail(tile) ? GetRailFoundation(tileh, GetTrackBits(tile)) : FlatteningFoundation(tileh);
2502 }
2503
2504 static void TileLoop_Track(TileIndex tile)
2505 {
2506 RailGroundType old_ground = GetRailGroundType(tile);
2507 RailGroundType new_ground;
2508
2509 if (old_ground == RAIL_GROUND_WATER) {
2510 TileLoop_Water(tile);
2511 return;
2512 }
2513
2514 switch (_settings_game.game_creation.landscape) {
2515 case LT_ARCTIC: {
2516 int z;
2517 Slope slope = GetTileSlope(tile, &z);
2518 bool half = false;
2519
2520 /* for non-flat track, use lower part of track
2521 * in other cases, use the highest part with track */
2522 if (IsPlainRail(tile)) {
2523 TrackBits track = GetTrackBits(tile);
2524 Foundation f = GetRailFoundation(slope, track);
2525
2526 switch (f) {
2527 case FOUNDATION_NONE:
2528 /* no foundation - is the track on the upper side of three corners raised tile? */
2529 if (IsSlopeWithThreeCornersRaised(slope)) z++;
2530 break;
2531
2532 case FOUNDATION_INCLINED_X:
2533 case FOUNDATION_INCLINED_Y:
2534 /* sloped track - is it on a steep slope? */
2535 if (IsSteepSlope(slope)) z++;
2536 break;
2537
2538 case FOUNDATION_STEEP_LOWER:
2539 /* only lower part of steep slope */
2540 z++;
2541 break;
2542
2543 default:
2544 /* if it is a steep slope, then there is a track on higher part */
2545 if (IsSteepSlope(slope)) z++;
2546 z++;
2547 break;
2548 }
2549
2550 half = IsInsideMM(f, FOUNDATION_STEEP_BOTH, FOUNDATION_HALFTILE_N + 1);
2551 } else {
2552 /* is the depot on a non-flat tile? */
2553 if (slope != SLOPE_FLAT) z++;
2554 }
2555
2556 /* 'z' is now the lowest part of the highest track bit -
2557 * for sloped track, it is 'z' of lower part
2558 * for two track bits, it is 'z' of higher track bit
2559 * For non-continuous foundations (and STEEP_BOTH), 'half' is set */
2560 if (z > GetSnowLine()) {
2561 if (half && z - GetSnowLine() == 1) {
2562 /* track on non-continuous foundation, lower part is not under snow */
2563 new_ground = RAIL_GROUND_HALF_SNOW;
2564 } else {
2565 new_ground = RAIL_GROUND_ICE_DESERT;
2566 }
2567 goto set_ground;
2568 }
2569 break;
2570 }
2571
2572 case LT_TROPIC:
2573 if (GetTropicZone(tile) == TROPICZONE_DESERT) {
2574 new_ground = RAIL_GROUND_ICE_DESERT;
2575 goto set_ground;
2576 }
2577 break;
2578 }
2579
2580 new_ground = RAIL_GROUND_GRASS;
2581
2582 if (IsPlainRail(tile) && old_ground != RAIL_GROUND_BARREN) { // wait until bottom is green
2583 /* determine direction of fence */
2584 TrackBits rail = GetTrackBits(tile);
2585
2586 Owner owner = GetTileOwner(tile);
2587 byte fences = 0;
2588
2589 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
2590 static const TrackBits dir_to_trackbits[DIAGDIR_END] = {TRACK_BIT_3WAY_NE, TRACK_BIT_3WAY_SE, TRACK_BIT_3WAY_SW, TRACK_BIT_3WAY_NW};
2591
2592 /* Track bit on this edge => no fence. */
2593 if ((rail & dir_to_trackbits[d]) != TRACK_BIT_NONE) continue;
2594
2595 TileIndex tile2 = tile + TileOffsByDiagDir(d);
2596
2597 /* Show fences if it's a house, industry, object, road, tunnelbridge or not owned by us. */
2598 if (!IsValidTile(tile2) || IsTileType(tile2, MP_HOUSE) || IsTileType(tile2, MP_INDUSTRY) ||
2599 IsTileType(tile2, MP_ROAD) || (IsTileType(tile2, MP_OBJECT) && !IsObjectType(tile2, OBJECT_OWNED_LAND)) || IsTileType(tile2, MP_TUNNELBRIDGE) || !IsTileOwner(tile2, owner)) {
2600 fences |= 1 << d;
2601 }
2602 }
2603
2604 switch (fences) {
2605 case 0: break;
2606 case (1 << DIAGDIR_NE): new_ground = RAIL_GROUND_FENCE_NE; break;
2607 case (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_SE; break;
2608 case (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_SW; break;
2609 case (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_NW; break;
2610 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_NESW; break;
2611 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_SENW; break;
2612 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_VERT1; break;
2613 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_HORIZ2; break;
2614 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_HORIZ1; break;
2615 case (1 << DIAGDIR_SW) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_VERT2; break;
2616 default: NOT_REACHED();
2617 }
2618 }
2619
2620 set_ground:
2621 if (old_ground != new_ground) {
2622 SetRailGroundType(tile, new_ground);
2623 MarkTileDirtyByTile(tile);
2624 }
2625 }
2626
2627
2628 static TrackStatus GetTileTrackStatus_Track(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
2629 {
2630 /* Case of half tile slope with water. */
2631 if (mode == TRANSPORT_WATER && IsPlainRail(tile) && GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(GetTileSlope(tile))) {
2632 TrackBits tb = GetTrackBits(tile);
2633 switch (tb) {
2634 default: NOT_REACHED();
2635 case TRACK_BIT_UPPER: tb = TRACK_BIT_LOWER; break;
2636 case TRACK_BIT_LOWER: tb = TRACK_BIT_UPPER; break;
2637 case TRACK_BIT_LEFT: tb = TRACK_BIT_RIGHT; break;
2638 case TRACK_BIT_RIGHT: tb = TRACK_BIT_LEFT; break;
2639 }
2640 return CombineTrackStatus(TrackBitsToTrackdirBits(tb), TRACKDIR_BIT_NONE);
2641 }
2642
2643 if (mode != TRANSPORT_RAIL) return 0;
2644
2645 TrackBits trackbits = TRACK_BIT_NONE;
2646 TrackdirBits red_signals = TRACKDIR_BIT_NONE;
2647
2648 switch (GetRailTileType(tile)) {
2649 default: NOT_REACHED();
2650 case RAIL_TILE_NORMAL:
2651 trackbits = GetTrackBits(tile);
2652 break;
2653
2654 case RAIL_TILE_SIGNALS: {
2655 trackbits = GetTrackBits(tile);
2656 byte a = GetPresentSignals(tile);
2657 uint b = GetSignalStates(tile);
2658
2659 b &= a;
2660
2661 /* When signals are not present (in neither direction),
2662 * we pretend them to be green. Otherwise, it depends on
2663 * the signal type. For signals that are only active from
2664 * one side, we set the missing signals explicitly to
2665 * `green'. Otherwise, they implicitly become `red'. */
2666 if (!IsOnewaySignal(tile, TRACK_UPPER) || (a & SignalOnTrack(TRACK_UPPER)) == 0) b |= ~a & SignalOnTrack(TRACK_UPPER);
2667 if (!IsOnewaySignal(tile, TRACK_LOWER) || (a & SignalOnTrack(TRACK_LOWER)) == 0) b |= ~a & SignalOnTrack(TRACK_LOWER);
2668
2669 if ((b & 0x8) == 0) red_signals |= (TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_UPPER_E);
2670 if ((b & 0x4) == 0) red_signals |= (TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_UPPER_W);
2671 if ((b & 0x2) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_E);
2672 if ((b & 0x1) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LOWER_W);
2673
2674 break;
2675 }
2676
2677 case RAIL_TILE_DEPOT: {
2678 DiagDirection dir = GetRailDepotDirection(tile);
2679
2680 if (side != INVALID_DIAGDIR && side != dir) break;
2681
2682 trackbits = DiagDirToDiagTrackBits(dir);
2683 break;
2684 }
2685 }
2686
2687 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), red_signals);
2688 }
2689
2690 static bool ClickTile_Track(TileIndex tile)
2691 {
2692 if (!IsRailDepot(tile)) return false;
2693
2694 ShowDepotWindow(tile, VEH_TRAIN);
2695 return true;
2696 }
2697
2698 static void GetTileDesc_Track(TileIndex tile, TileDesc *td)
2699 {
2700 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
2701 td->rail_speed = rti->max_speed;
2702 td->owner[0] = GetTileOwner(tile);
2703 SetDParamX(td->dparam, 0, rti->strings.name);
2704 switch (GetRailTileType(tile)) {
2705 case RAIL_TILE_NORMAL:
2706 td->str = STR_LAI_RAIL_DESCRIPTION_TRACK;
2707 break;
2708
2709 case RAIL_TILE_SIGNALS: {
2710 static const StringID signal_type[6][6] = {
2711 {
2712 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_SIGNALS,
2713 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
2714 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
2715 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
2716 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
2717 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS
2718 },
2719 {
2720 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
2721 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRESIGNALS,
2722 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
2723 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
2724 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
2725 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS
2726 },
2727 {
2728 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
2729 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
2730 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXITSIGNALS,
2731 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
2732 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
2733 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS
2734 },
2735 {
2736 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
2737 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
2738 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
2739 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBOSIGNALS,
2740 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
2741 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS
2742 },
2743 {
2744 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
2745 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
2746 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
2747 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
2748 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBSSIGNALS,
2749 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS
2750 },
2751 {
2752 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS,
2753 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS,
2754 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS,
2755 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS,
2756 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS,
2757 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRYSIGNALS
2758 }
2759 };
2760
2761 SignalType primary_signal;
2762 SignalType secondary_signal;
2763 if (HasSignalOnTrack(tile, TRACK_UPPER)) {
2764 primary_signal = GetSignalType(tile, TRACK_UPPER);
2765 secondary_signal = HasSignalOnTrack(tile, TRACK_LOWER) ? GetSignalType(tile, TRACK_LOWER) : primary_signal;
2766 } else {
2767 secondary_signal = primary_signal = GetSignalType(tile, TRACK_LOWER);
2768 }
2769
2770 td->str = signal_type[secondary_signal][primary_signal];
2771 break;
2772 }
2773
2774 case RAIL_TILE_DEPOT:
2775 td->str = STR_LAI_RAIL_DESCRIPTION_TRAIN_DEPOT;
2776 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) {
2777 if (td->rail_speed > 0) {
2778 td->rail_speed = min(td->rail_speed, 61);
2779 } else {
2780 td->rail_speed = 61;
2781 }
2782 }
2783 td->build_date = Depot::GetByTile(tile)->build_date;
2784 break;
2785
2786 default:
2787 NOT_REACHED();
2788 }
2789 }
2790
2791 static void ChangeTileOwner_Track(TileIndex tile, Owner old_owner, Owner new_owner)
2792 {
2793 if (!IsTileOwner(tile, old_owner)) return;
2794
2795 if (new_owner != INVALID_OWNER) {
2796 /* Update company infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
2797 uint num_pieces = 1;
2798 if (IsPlainRail(tile)) {
2799 TrackBits bits = GetTrackBits(tile);
2800 num_pieces = CountBits(bits);
2801 if (TracksOverlap(bits)) num_pieces *= num_pieces;
2802 }
2803 RailType rt = GetRailType(tile);
2804 Company::Get(old_owner)->infrastructure.rail[rt] -= num_pieces;
2805 Company::Get(new_owner)->infrastructure.rail[rt] += num_pieces;
2806
2807 if (HasSignals(tile)) {
2808 uint num_sigs = CountBits(GetPresentSignals(tile));
2809 Company::Get(old_owner)->infrastructure.signal -= num_sigs;
2810 Company::Get(new_owner)->infrastructure.signal += num_sigs;
2811 }
2812
2813 SetTileOwner(tile, new_owner);
2814 } else {
2815 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
2816 }
2817 }
2818
2819 static const byte _fractcoords_behind[4] = { 0x8F, 0x8, 0x80, 0xF8 };
2820 static const byte _fractcoords_enter[4] = { 0x8A, 0x48, 0x84, 0xA8 };
2821 static const int8 _deltacoord_leaveoffset[8] = {
2822 -1, 0, 1, 0, /* x */
2823 0, 1, 0, -1 /* y */
2824 };
2825
2826
2833 int TicksToLeaveDepot(const Train *v)
2834 {
2835 DiagDirection dir = GetRailDepotDirection(v->tile);
2836 int length = v->CalcNextVehicleOffset();
2837
2838 switch (dir) {
2839 case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) - (length + 1)));
2840 case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) + (length + 1)));
2841 case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) + (length + 1)));
2842 default:
2843 case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) - (length + 1)));
2844 }
2845
2846 return 0; // make compilers happy
2847 }
2848
2853 static VehicleEnterTileStatus VehicleEnter_Track(Vehicle *u, TileIndex tile, int x, int y)
2854 {
2855 /* this routine applies only to trains in depot tiles */
2856 if (u->type != VEH_TRAIN || !IsRailDepotTile(tile)) return VETSB_CONTINUE;
2857
2858 Train *v = Train::From(u);
2859
2860 /* depot direction */
2861 DiagDirection dir = GetRailDepotDirection(tile);
2862
2863 /* Calculate the point where the following wagon should be activated. */
2864 int length = v->CalcNextVehicleOffset();
2865
2866 byte fract_coord_leave =
2867 ((_fractcoords_enter[dir] & 0x0F) + // x
2868 (length + 1) * _deltacoord_leaveoffset[dir]) +
2869 (((_fractcoords_enter[dir] >> 4) + // y
2870 ((length + 1) * _deltacoord_leaveoffset[dir + 4])) << 4);
2871
2872 byte fract_coord = (x & 0xF) + ((y & 0xF) << 4);
2873
2874 if (_fractcoords_behind[dir] == fract_coord) {
2875 /* make sure a train is not entering the tile from behind */
2876 return VETSB_CANNOT_ENTER;
2877 } else if (_fractcoords_enter[dir] == fract_coord) {
2878 if (DiagDirToDir(ReverseDiagDir(dir)) == v->direction) {
2879 /* enter the depot */
2880 v->track = TRACK_BIT_DEPOT,
2881 v->vehstatus |= VS_HIDDEN; // hide it
2882 v->direction = ReverseDir(v->direction);
2883 if (v->Next() == NULL) VehicleEnterDepot(v->First());
2884 v->tile = tile;
2885
2886 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2887 return VETSB_ENTERED_WORMHOLE;
2888 }
2889 } else if (fract_coord_leave == fract_coord) {
2890 if (DiagDirToDir(dir) == v->direction) {
2891 /* leave the depot? */
2892 if ((v = v->Next()) != NULL) {
2893 v->vehstatus &= ~VS_HIDDEN;
2894 v->track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
2895 }
2896 }
2897 }
2898
2899 return VETSB_CONTINUE;
2900 }
2901
2913 static CommandCost TestAutoslopeOnRailTile(TileIndex tile, uint flags, int z_old, Slope tileh_old, int z_new, Slope tileh_new, TrackBits rail_bits)
2914 {
2915 if (!_settings_game.construction.build_on_slopes || !AutoslopeEnabled()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2916
2917 /* Is the slope-rail_bits combination valid in general? I.e. is it safe to call GetRailFoundation() ? */
2918 if (CheckRailSlope(tileh_new, rail_bits, TRACK_BIT_NONE, tile).Failed()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2919
2920 /* Get the slopes on top of the foundations */
2921 z_old += ApplyFoundationToSlope(GetRailFoundation(tileh_old, rail_bits), &tileh_old);
2922 z_new += ApplyFoundationToSlope(GetRailFoundation(tileh_new, rail_bits), &tileh_new);
2923
2924 Corner track_corner;
2925 switch (rail_bits) {
2926 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
2927 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
2928 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
2929 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
2930
2931 /* Surface slope must not be changed */
2932 default:
2933 if (z_old != z_new || tileh_old != tileh_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2934 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2935 }
2936
2937 /* The height of the track_corner must not be changed. The rest ensures GetRailFoundation() already. */
2938 z_old += GetSlopeZInCorner(RemoveHalftileSlope(tileh_old), track_corner);
2939 z_new += GetSlopeZInCorner(RemoveHalftileSlope(tileh_new), track_corner);
2940 if (z_old != z_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2941
2942 CommandCost cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2943 /* Make the ground dirty, if surface slope has changed */
2944 if (tileh_old != tileh_new) {
2945 /* If there is flat water on the lower halftile add the cost for clearing it */
2946 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old)) cost.AddCost(_price[PR_CLEAR_WATER]);
2947 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
2948 }
2949 return cost;
2950 }
2951
2955 static Vehicle *EnsureNoShipProc(Vehicle *v, void *data)
2956 {
2957 return v->type == VEH_SHIP ? v : NULL;
2958 }
2959
2960 static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
2961 {
2962 int z_old;
2963 Slope tileh_old = GetTileSlope(tile, &z_old);
2964 if (IsPlainRail(tile)) {
2965 TrackBits rail_bits = GetTrackBits(tile);
2966 /* Is there flat water on the lower halftile that must be cleared expensively? */
2967 bool was_water = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old));
2968
2969 /* Allow clearing the water only if there is no ship */
2970 if (was_water && HasVehicleOnPos(tile, NULL, &EnsureNoShipProc)) return_cmd_error(STR_ERROR_SHIP_IN_THE_WAY);
2971
2972 /* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
2973 CommandCost autoslope_result = TestAutoslopeOnRailTile(tile, flags, z_old, tileh_old, z_new, tileh_new, rail_bits);
2974
2975 /* When there is only a single horizontal/vertical track, one corner can be terraformed. */
2976 Corner allowed_corner;
2977 switch (rail_bits) {
2978 case TRACK_BIT_RIGHT: allowed_corner = CORNER_W; break;
2979 case TRACK_BIT_UPPER: allowed_corner = CORNER_S; break;
2980 case TRACK_BIT_LEFT: allowed_corner = CORNER_E; break;
2981 case TRACK_BIT_LOWER: allowed_corner = CORNER_N; break;
2982 default: return autoslope_result;
2983 }
2984
2985 Foundation f_old = GetRailFoundation(tileh_old, rail_bits);
2986
2987 /* Do not allow terraforming if allowed_corner is part of anti-zig-zag foundations */
2988 if (tileh_old != SLOPE_NS && tileh_old != SLOPE_EW && IsSpecialRailFoundation(f_old)) return autoslope_result;
2989
2990 /* Everything is valid, which only changes allowed_corner */
2991 for (Corner corner = (Corner)0; corner < CORNER_END; corner = (Corner)(corner + 1)) {
2992 if (allowed_corner == corner) continue;
2993 if (z_old + GetSlopeZInCorner(tileh_old, corner) != z_new + GetSlopeZInCorner(tileh_new, corner)) return autoslope_result;
2994 }
2995
2996 /* Make the ground dirty */
2997 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
2998
2999 /* allow terraforming */
3000 return CommandCost(EXPENSES_CONSTRUCTION, was_water ? _price[PR_CLEAR_WATER] : (Money)0);
3001 } else if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() &&
3002 AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRailDepotDirection(tile))) {
3003 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3004 }
3005 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3006 }
3007
3008
3009 extern const TileTypeProcs _tile_type_rail_procs = {
3010 DrawTile_Track, // draw_tile_proc
3011 GetSlopePixelZ_Track, // get_slope_z_proc
3012 ClearTile_Track, // clear_tile_proc
3013 NULL, // add_accepted_cargo_proc
3014 GetTileDesc_Track, // get_tile_desc_proc
3015 GetTileTrackStatus_Track, // get_tile_track_status_proc
3016 ClickTile_Track, // click_tile_proc
3017 NULL, // animate_tile_proc
3018 TileLoop_Track, // tile_loop_proc
3019 ChangeTileOwner_Track, // change_tile_owner_proc
3020 NULL, // add_produced_cargo_proc
3021 VehicleEnter_Track, // vehicle_enter_tile_proc
3022 GetFoundation_Track, // get_foundation_proc
3023 TerraformTile_Track, // terraform_tile_proc
3024 };