Make it possible to stop road vehicles from slowing down in curves so "diagonal"...
[openttd-joker.git] / src / tunnelbridge_cmd.cpp
blob2c4f6ed05f264efefe67c85fd023b703492745df
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /**
11 * @file tunnelbridge_cmd.cpp
12 * This file deals with tunnels and bridges (non-gui stuff)
13 * @todo separate this file into two
16 #include "stdafx.h"
17 #include "newgrf_object.h"
18 #include "viewport_func.h"
19 #include "cmd_helper.h"
20 #include "command_func.h"
21 #include "town.h"
22 #include "train.h"
23 #include "ship.h"
24 #include "roadveh.h"
25 #include "pathfinder/yapf/yapf_cache.h"
26 #include "newgrf_sound.h"
27 #include "autoslope.h"
28 #include "tunnelbridge_map.h"
29 #include "bridge_signal_map.h"
30 #include "tunnel_base.h"
31 #include "strings_func.h"
32 #include "date_func.h"
33 #include "clear_func.h"
34 #include "vehicle_func.h"
35 #include "vehicle_gui.h"
36 #include "sound_func.h"
37 #include "tunnelbridge.h"
38 #include "cheat_type.h"
39 #include "elrail_func.h"
40 #include "pbs.h"
41 #include "company_base.h"
42 #include "newgrf_railtype.h"
43 #include "object_base.h"
44 #include "water.h"
45 #include "company_gui.h"
46 #include "viewport_func.h"
47 #include "station_map.h"
48 #include "industry_map.h"
50 #include "table/strings.h"
51 #include "table/bridge_land.h"
53 #include "safeguards.h"
55 BridgeSpec _bridge[MAX_BRIDGES]; ///< The specification of all bridges.
56 TileIndex _build_tunnel_endtile; ///< The end of a tunnel; as hidden return from the tunnel build command for GUI purposes.
58 /** Z position of the bridge sprites relative to bridge height (downwards) */
59 static const int BRIDGE_Z_START = 3;
61 extern void DrawRoadBits(TileInfo *ti);
62 extern const RoadBits _invalid_tileh_slopes_road[2][15];
65 /**
66 * Mark bridge tiles dirty.
67 * Note: The bridge does not need to exist, everything is passed via parameters.
68 * @param begin Start tile.
69 * @param end End tile.
70 * @param direction Direction from \a begin to \a end.
71 * @param bridge_height Bridge height level.
73 void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height, const ZoomLevel mark_dirty_if_zoomlevel_is_below)
75 TileIndexDiff delta = TileOffsByDiagDir(direction);
76 for (TileIndex t = begin; t != end; t += delta) {
77 MarkTileDirtyByTile(t, mark_dirty_if_zoomlevel_is_below, bridge_height - TileHeight(t));
79 MarkTileDirtyByTile(end, mark_dirty_if_zoomlevel_is_below);
82 /**
83 * Mark bridge tiles dirty.
84 * @param tile Bridge head.
86 void MarkBridgeDirty(TileIndex tile, const ZoomLevel mark_dirty_if_zoomlevel_is_below)
88 MarkBridgeDirty(tile, GetOtherTunnelBridgeEnd(tile), GetTunnelBridgeDirection(tile), GetBridgeHeight(tile), mark_dirty_if_zoomlevel_is_below);
91 /**
92 * Mark bridge or tunnel tiles dirty.
93 * @param tile Bridge head or tunnel entrance.
95 void MarkBridgeOrTunnelDirty(TileIndex tile, const ZoomLevel mark_dirty_if_zoomlevel_is_below)
97 if (IsBridge(tile)) {
98 MarkBridgeDirty(tile, mark_dirty_if_zoomlevel_is_below);
99 } else {
100 MarkTileDirtyByTile(tile);
101 MarkTileDirtyByTile(GetOtherTunnelBridgeEnd(tile));
106 * Get number of signals on bridge or tunnel with signal simulation.
107 * @param length Length of bridge/tunnel middle
108 * @return Number of signals on signalled bridge/tunnel of this length
110 uint GetTunnelBridgeSignalSimulationSignalCount(uint length)
112 return 2 + (length / _settings_game.construction.simulated_wormhole_signals);
115 /** Reset the data been eventually changed by the grf loaded. */
116 void ResetBridges()
118 /* First, free sprite table data */
119 for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
120 if (_bridge[i].sprite_table != nullptr) {
121 for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
122 free(_bridge[i].sprite_table);
126 /* Then, wipe out current bridges */
127 memset(&_bridge, 0, sizeof(_bridge));
128 /* And finally, reinstall default data */
129 memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
133 * Calculate the price factor for building a long bridge.
134 * Basically the cost delta is 1,1, 1, 2,2, 3,3,3, 4,4,4,4, 5,5,5,5,5, 6,6,6,6,6,6, 7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8,
135 * @param length Length of the bridge.
136 * @return Price factor for the bridge.
138 int CalcBridgeLenCostFactor(int length)
140 if (length < 2) return length;
142 length -= 2;
143 int sum = 2;
144 for (int delta = 1;; delta++) {
145 for (int count = 0; count < delta; count++) {
146 if (length == 0) return sum;
147 sum += delta;
148 length--;
154 * Get the foundation for a bridge.
155 * @param tileh The slope to build the bridge on.
156 * @param axis The axis of the bridge entrance.
157 * @return The foundation required.
159 Foundation GetBridgeFoundation(Slope tileh, Axis axis)
161 if (tileh == SLOPE_FLAT ||
162 ((tileh == SLOPE_NE || tileh == SLOPE_SW) && axis == AXIS_X) ||
163 ((tileh == SLOPE_NW || tileh == SLOPE_SE) && axis == AXIS_Y)) return FOUNDATION_NONE;
165 return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
169 * Determines if the track on a bridge ramp is flat or goes up/down.
171 * @param tileh Slope of the tile under the bridge head
172 * @param axis Orientation of bridge
173 * @return true iff the track is flat.
175 bool HasBridgeFlatRamp(Slope tileh, Axis axis)
177 ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
178 /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
179 return (tileh != SLOPE_FLAT);
182 static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
184 const BridgeSpec *bridge = GetBridgeSpec(index);
185 assert(table < BRIDGE_PIECE_INVALID);
186 if (bridge->sprite_table == nullptr || bridge->sprite_table[table] == nullptr) {
187 return _bridge_sprite_table[index][table];
188 } else {
189 return bridge->sprite_table[table];
195 * Determines the foundation for the north bridge head, and tests if the resulting slope is valid.
197 * @param axis Axis of the bridge
198 * @param tileh Slope of the tile under the north bridge head; returns slope on top of foundation
199 * @param z TileZ corresponding to tileh, gets modified as well
200 * @return Error or cost for bridge foundation
202 static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, int *z)
204 Foundation f = GetBridgeFoundation(*tileh, axis);
205 *z += ApplyFoundationToSlope(f, tileh);
207 Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
208 if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CommandError();
210 if (f == FOUNDATION_NONE) return CommandCost();
212 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
216 * Determines the foundation for the south bridge head, and tests if the resulting slope is valid.
218 * @param axis Axis of the bridge
219 * @param tileh Slope of the tile under the south bridge head; returns slope on top of foundation
220 * @param z TileZ corresponding to tileh, gets modified as well
221 * @return Error or cost for bridge foundation
223 static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, int *z)
225 Foundation f = GetBridgeFoundation(*tileh, axis);
226 *z += ApplyFoundationToSlope(f, tileh);
228 Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
229 if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CommandError();
231 if (f == FOUNDATION_NONE) return CommandCost();
233 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
237 * Is a bridge of the specified type and length available?
238 * @param bridge_type Wanted type of bridge.
239 * @param bridge_len Wanted length of the bridge.
240 * @return A succeeded (the requested bridge is available) or failed (it cannot be built) command.
242 CommandCost CheckBridgeAvailability(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
244 if (flags & DC_QUERY_COST) {
245 if (bridge_len <= _settings_game.construction.max_bridge_length) return CommandCost();
246 return CommandError(STR_ERROR_BRIDGE_TOO_LONG);
249 if (bridge_type >= MAX_BRIDGES) return CommandError();
251 const BridgeSpec *b = GetBridgeSpec(bridge_type);
252 if (b->avail_year > _cur_year) return CommandError();
254 uint max = min(b->max_length, _settings_game.construction.max_bridge_length);
256 if (b->min_length > bridge_len) return CommandError();
257 if (bridge_len <= max) return CommandCost();
258 return CommandError(STR_ERROR_BRIDGE_TOO_LONG);
262 * Build a Bridge
263 * @param end_tile end tile
264 * @param flags type of operation
265 * @param p1 packed start tile coords (~ dx)
266 * @param p2 various bitstuffed elements
267 * - p2 = (bit 0- 7) - bridge type (hi bh)
268 * - p2 = (bit 8-12) - rail type or road types.
269 * - p2 = (bit 15-16) - transport type.
270 * @param text unused
271 * @return the cost of this operation or an error
273 CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
275 CompanyID company = _current_company;
277 RailType railtype = INVALID_RAILTYPE;
278 RoadTypes roadtypes = ROADTYPES_NONE;
280 /* unpack parameters */
281 BridgeType bridge_type = GB(p2, 0, 8);
283 if (!IsValidTile(p1)) return CommandError(STR_ERROR_BRIDGE_THROUGH_MAP_BORDER);
285 TransportType transport_type = Extract<TransportType, 15, 2>(p2);
287 /* type of bridge */
288 switch (transport_type) {
289 case TRANSPORT_ROAD:
290 roadtypes = Extract<RoadTypes, 8, 2>(p2);
291 if (!HasExactlyOneBit(roadtypes) || !HasRoadTypesAvail(company, roadtypes)) return CommandError();
292 break;
294 case TRANSPORT_RAIL:
295 railtype = Extract<RailType, 8, 5>(p2);
296 if (!ValParamRailtype(railtype)) return CommandError();
297 break;
299 case TRANSPORT_WATER:
300 break;
302 default:
303 /* Airports don't have bridges. */
304 return CommandError();
306 TileIndex tile_start = p1;
307 TileIndex tile_end = end_tile;
309 if (company == OWNER_DEITY) {
310 if (transport_type != TRANSPORT_ROAD) return CommandError();
311 const Town *town = CalcClosestTownFromTile(tile_start);
313 company = OWNER_TOWN;
315 /* If we are not within a town, we are not owned by the town */
316 if (town == nullptr || DistanceSquare(tile_start, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
317 company = OWNER_NONE;
321 if (tile_start == tile_end) {
322 return CommandError(STR_ERROR_CAN_T_START_AND_END_ON);
325 Axis direction;
326 if (TileX(tile_start) == TileX(tile_end)) {
327 direction = AXIS_Y;
328 } else if (TileY(tile_start) == TileY(tile_end)) {
329 direction = AXIS_X;
330 } else {
331 return CommandError(STR_ERROR_START_AND_END_MUST_BE_IN);
334 if (tile_end < tile_start) Swap(tile_start, tile_end);
336 uint bridge_len = GetTunnelBridgeLength(tile_start, tile_end);
337 if (transport_type != TRANSPORT_WATER) {
338 /* set and test bridge length, availability */
339 CommandCost ret = CheckBridgeAvailability(bridge_type, bridge_len, flags);
340 if (ret.Failed()) return ret;
341 } else {
342 if (bridge_len > _settings_game.construction.max_bridge_length) return CommandError(STR_ERROR_BRIDGE_TOO_LONG);
345 int z_start;
346 int z_end;
347 Slope tileh_start = GetTileSlope(tile_start, &z_start);
348 Slope tileh_end = GetTileSlope(tile_end, &z_end);
349 bool pbs_reservation = false;
351 CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
352 CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end, &z_end);
354 /* Aqueducts can't be built of flat land. */
355 if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
356 if (z_start != z_end) return CommandError(STR_ERROR_BRIDGEHEADS_NOT_SAME_HEIGHT);
358 CommandCost cost(EXPENSES_CONSTRUCTION);
359 Owner owner;
360 bool is_new_owner;
361 bool is_upgrade = false;
362 if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
363 GetOtherBridgeEnd(tile_start) == tile_end &&
364 GetTunnelBridgeTransportType(tile_start) == transport_type) {
365 /* Replace a current bridge. */
367 /* If this is a railway bridge, make sure the railtypes match. */
368 if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
369 return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
372 /* Do not replace town bridges with lower speed bridges, unless in scenario editor. */
373 if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
374 GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed &&
375 _game_mode != GM_EDITOR) {
376 Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
378 if (t == nullptr) {
379 return CommandError();
380 } else {
381 SetDParam(0, t->index);
382 return CommandError(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
386 /* Do not replace the bridge with the same bridge type. */
387 if (!(flags & DC_QUERY_COST) && (bridge_type == GetBridgeType(tile_start)) && (transport_type != TRANSPORT_ROAD || (roadtypes & ~GetRoadTypes(tile_start)) == 0)) {
388 return CommandError(STR_ERROR_ALREADY_BUILT);
391 /* Do not allow replacing another company's bridges. */
392 if (!IsTileOwner(tile_start, company) && !IsTileOwner(tile_start, OWNER_TOWN) && !IsTileOwner(tile_start, OWNER_NONE)) {
393 return CommandError(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
396 cost.AddCost((bridge_len + 1) * _price[PR_CLEAR_BRIDGE]); // The cost of clearing the current bridge.
397 owner = GetTileOwner(tile_start);
399 /* If bridge belonged to bankrupt company, it has a new owner now */
400 is_new_owner = (owner == OWNER_NONE);
401 if (is_new_owner) owner = company;
403 switch (transport_type) {
404 case TRANSPORT_RAIL:
405 /* Keep the reservation, the path stays valid. */
406 pbs_reservation = HasTunnelBridgeReservation(tile_start);
407 break;
409 case TRANSPORT_ROAD:
410 /* Do not remove road types when upgrading a bridge */
411 roadtypes |= GetRoadTypes(tile_start);
412 break;
414 default: break;
417 is_upgrade = true;
418 } else {
419 /* Build a new bridge. */
421 bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
423 /* Try and clear the start landscape */
424 CommandCost ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
425 if (ret.Failed()) return ret;
426 cost = ret;
428 if (terraform_cost_north.Failed() || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes)) return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
429 cost.AddCost(terraform_cost_north);
431 /* Try and clear the end landscape */
432 ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
433 if (ret.Failed()) return ret;
434 cost.AddCost(ret);
436 /* false - end tile slope check */
437 if (terraform_cost_south.Failed() || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes)) return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
438 cost.AddCost(terraform_cost_south);
440 const TileIndex heads[] = {tile_start, tile_end};
441 for (int i = 0; i < 2; i++) {
442 if (IsBridgeAbove(heads[i])) {
443 TileIndex north_head = GetNorthernBridgeEnd(heads[i]);
445 if (direction == GetBridgeAxis(heads[i])) return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
447 if (z_start + 1 == GetBridgeHeight(north_head)) {
448 return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
453 TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
454 for (TileIndex tile = tile_start + delta; tile != tile_end; tile += delta) {
455 if (GetTileMaxZ(tile) > z_start) return CommandError(STR_ERROR_BRIDGE_TOO_LOW_FOR_TERRAIN);
457 if (z_start >= (GetTileZ(tile) + _settings_game.construction.max_bridge_height)) {
459 * Disallow too high bridges.
460 * Properly rendering a map where very high bridges (might) exist is expensive.
461 * See http://www.tt-forums.net/viewtopic.php?f=33&t=40844&start=980#p1131762
462 * for a detailed discussion. z_start here is one heightlevel below the bridge level.
464 return CommandError(STR_ERROR_BRIDGE_TOO_HIGH_FOR_TERRAIN);
467 if (IsBridgeAbove(tile)) {
468 /* Disallow crossing bridges for the time being */
469 return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
472 switch (GetTileType(tile)) {
473 case MP_WATER:
474 if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
475 break;
477 case MP_RAILWAY:
478 if (!IsPlainRail(tile)) goto not_valid_below;
479 break;
481 case MP_ROAD:
482 if (IsRoadDepot(tile)) goto not_valid_below;
483 break;
485 case MP_TUNNELBRIDGE:
486 if (IsTunnel(tile)) break;
487 if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
488 if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
489 break;
491 case MP_OBJECT: {
492 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
493 if ((spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) == 0) goto not_valid_below;
494 if (GetTileMaxZ(tile) + spec->height > z_start) goto not_valid_below;
495 break;
498 case MP_CLEAR:
499 break;
501 default:
502 not_valid_below:;
503 /* try and clear the middle landscape */
504 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
505 if (ret.Failed()) return ret;
506 cost.AddCost(ret);
507 break;
510 if (flags & DC_EXEC) {
511 /* We do this here because when replacing a bridge with another
512 * type calling SetBridgeMiddle isn't needed. After all, the
513 * tile already has the has_bridge_above bits set. */
514 SetBridgeMiddle(tile, direction);
518 owner = company;
519 is_new_owner = true;
522 /* do the drill? */
523 if (flags & DC_EXEC) {
524 DiagDirection dir = AxisToDiagDir(direction);
526 Company *c = Company::GetIfValid(company);
527 switch (transport_type) {
528 case TRANSPORT_RAIL:
529 /* Add to company infrastructure count if required. */
530 if (is_new_owner && c != nullptr) c->infrastructure.rail[railtype] += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
531 MakeRailBridgeRamp(tile_start, owner, bridge_type, dir, railtype, is_upgrade);
532 MakeRailBridgeRamp(tile_end, owner, bridge_type, ReverseDiagDir(dir), railtype, is_upgrade);
533 SetTunnelBridgeReservation(tile_start, pbs_reservation);
534 SetTunnelBridgeReservation(tile_end, pbs_reservation);
535 break;
537 case TRANSPORT_ROAD: {
538 RoadTypes prev_roadtypes = IsBridgeTile(tile_start) ? GetRoadTypes(tile_start) : ROADTYPES_NONE;
539 if (is_new_owner) {
540 /* Also give unowned present roadtypes to new owner */
541 if (HasBit(prev_roadtypes, ROADTYPE_ROAD) && GetRoadOwner(tile_start, ROADTYPE_ROAD) == OWNER_NONE) ClrBit(prev_roadtypes, ROADTYPE_ROAD);
542 if (HasBit(prev_roadtypes, ROADTYPE_TRAM) && GetRoadOwner(tile_start, ROADTYPE_TRAM) == OWNER_NONE) ClrBit(prev_roadtypes, ROADTYPE_TRAM);
544 if (c != nullptr) {
545 /* Add all new road types to the company infrastructure counter. */
546 RoadType new_rt;
547 FOR_EACH_SET_ROADTYPE(new_rt, roadtypes ^ prev_roadtypes) {
548 /* A full diagonal road tile has two road bits. */
549 c->infrastructure.road[new_rt] += (bridge_len + 2) * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
552 Owner owner_road = HasBit(prev_roadtypes, ROADTYPE_ROAD) ? GetRoadOwner(tile_start, ROADTYPE_ROAD) : company;
553 Owner owner_tram = HasBit(prev_roadtypes, ROADTYPE_TRAM) ? GetRoadOwner(tile_start, ROADTYPE_TRAM) : company;
554 MakeRoadBridgeRamp(tile_start, owner, owner_road, owner_tram, bridge_type, dir, roadtypes, is_upgrade);
555 MakeRoadBridgeRamp(tile_end, owner, owner_road, owner_tram, bridge_type, ReverseDiagDir(dir), roadtypes, is_upgrade);
556 break;
559 case TRANSPORT_WATER:
560 if (is_new_owner && c != nullptr) c->infrastructure.water += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
561 MakeAqueductBridgeRamp(tile_start, owner, dir);
562 MakeAqueductBridgeRamp(tile_end, owner, ReverseDiagDir(dir));
563 break;
565 default:
566 NOT_REACHED();
569 /* Mark all tiles dirty */
570 MarkBridgeDirty(tile_start, tile_end, AxisToDiagDir(direction), z_start);
571 DirtyCompanyInfrastructureWindows(company);
574 if ((flags & DC_EXEC) && transport_type == TRANSPORT_RAIL) {
575 Track track = AxisToTrack(direction);
576 AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, company);
577 YapfNotifyTrackLayoutChange(tile_start, track);
580 /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
581 * It's unnecessary to execute this command every time for every bridge. So it is done only
582 * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
584 Company *c = Company::GetIfValid(company);
585 if (!(flags & DC_QUERY_COST) || (c != nullptr && c->is_ai)) {
586 bridge_len += 2; // begin and end tiles/ramps
588 switch (transport_type) {
589 case TRANSPORT_ROAD: cost.AddCost(bridge_len * _price[PR_BUILD_ROAD] * 2 * CountBits(roadtypes)); break;
590 case TRANSPORT_RAIL: cost.AddCost(bridge_len * RailBuildCost(railtype)); break;
591 default: break;
594 if (c != nullptr) bridge_len = CalcBridgeLenCostFactor(bridge_len);
596 if (transport_type != TRANSPORT_WATER) {
597 cost.AddCost((int64)bridge_len * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8);
598 } else {
599 /* Aqueducts use a separate base cost. */
600 cost.AddCost((int64)bridge_len * _price[PR_BUILD_AQUEDUCT]);
605 return cost;
609 * Check if the amount of tiles of the chunnel ramp is between allowed limits.
610 * @param tile the actual tile.
611 * @param ramp ramp_start tile.
612 * @param delta the tile offset.
613 * @return an empty string if between limits or a formatted string for the error message.
615 static inline StringID IsRampBetweenLimits(TileIndex ramp_start, TileIndex tile, TileIndexDiff delta)
617 uint min_length = 4;
618 uint max_length = 7;
619 if (Delta(ramp_start, tile) < (uint)abs(delta) * min_length || (uint)abs(delta) * max_length < Delta(ramp_start, tile)) {
620 /* Add 1 in message to have consistency with cursor count in game. */
621 SetDParam(0, max_length + 1);
622 return STR_ERROR_CHUNNEL_RAMP;
625 return STR_NULL;
629 * See if chunnel building is possible.
630 * All chunnel related issues are tucked away in one procedure
631 * @pre only on z level 0.
632 * @param tile start tile of tunnel.
633 * @param direction the direction we want to build.
634 * @param is_chunnel pointer to set if chunnel is allowed or not.
635 * @param sea_tiles pointer for the amount of tiles used to cross a sea.
636 * @return an error message or if success the is_chunnel flag is set to true and the amount of tiles needed to cross the water is returned.
638 static inline CommandCost CanBuildChunnel(TileIndex tile, DiagDirection direction, bool &is_chunnel, int &sea_tiles)
640 const int start_z = 0;
641 bool crossed_sea = false;
642 TileIndex ramp_start = tile;
644 if (GetTileZ(tile) > 0) return CommandError(STR_ERROR_CHUNNEL_ONLY_OVER_SEA);
646 const TileIndexDiff delta = TileOffsByDiagDir(direction);
647 for (;;) {
648 tile += delta;
649 if (!IsValidTile(tile)) return CommandError(STR_ERROR_CHUNNEL_THROUGH_MAP_BORDER);
650 _build_tunnel_endtile = tile;
651 int end_z;
652 Slope end_tileh = GetTileSlope(tile, &end_z);
654 if (start_z == end_z) {
655 /* Handle chunnels only on sea level and only one time crossing. */
656 if (!crossed_sea &&
657 (IsCoastTile(tile) ||
658 (IsValidTile(tile + delta) && HasTileWaterGround(tile + delta)) ||
659 (IsValidTile(tile + delta * 2) && HasTileWaterGround(tile + delta * 2)))) {
661 /* A shore was found, check if start ramp was too short or too long. */
662 StringID err_msg = IsRampBetweenLimits(ramp_start, tile, delta);
663 if (err_msg > STR_NULL) return CommandError(err_msg);
665 /* Pass the water and find a proper shore tile that potentially
666 * could have a tunnel portal behind. */
667 for (;;) {
668 end_tileh = GetTileSlope(tile);
669 if (direction == DIAGDIR_NE && (end_tileh & SLOPE_NE) == SLOPE_NE) break;
670 if (direction == DIAGDIR_SE && (end_tileh & SLOPE_SE) == SLOPE_SE) break;
671 if (direction == DIAGDIR_SW && (end_tileh & SLOPE_SW) == SLOPE_SW) break;
672 if (direction == DIAGDIR_NW && (end_tileh & SLOPE_NW) == SLOPE_NW) break;
674 /* No drilling under oil rigs.*/
675 if ((IsTileType(tile, MP_STATION) && IsOilRig(tile)) ||
676 (IsTileType(tile, MP_INDUSTRY) &&
677 GetIndustryGfx(tile) >= GFX_OILRIG_1 &&
678 GetIndustryGfx(tile) <= GFX_OILRIG_5)) return CommandError(STR_ERROR_NO_DRILLING_ABOVE_CHUNNEL);
680 if (IsTileType(tile, MP_WATER) && IsSea(tile)) crossed_sea = true;
681 if (!_cheats.crossing_tunnels.value && IsTunnelInWay(tile, start_z)) return CommandError(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY);
682 tile += delta;
683 if (!IsValidTile(tile)) return CommandError(STR_ERROR_CHUNNEL_THROUGH_MAP_BORDER);
684 _build_tunnel_endtile = tile;
685 sea_tiles++;
687 if (!crossed_sea) return CommandError(STR_ERROR_CHUNNEL_ONLY_OVER_SEA);
688 ramp_start = tile;
689 } else {
690 /* Check if end ramp was too short or too long after crossing the sea. */
691 if (crossed_sea) {
692 StringID err_msg = IsRampBetweenLimits(ramp_start, tile, delta);
693 if (err_msg > STR_NULL) return CommandError(err_msg);
695 break;
699 is_chunnel = crossed_sea;
701 return CommandCost();
706 * Build Tunnel.
707 * @param start_tile start tile of tunnel
708 * @param flags type of operation
709 * @param p1 bit 0-4 railtype or roadtypes
710 * bit 8-9 transport type
711 * @param p2 unused
712 * @param text unused
713 * @return the cost of this operation or an error
715 CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
717 CompanyID company = _current_company;
719 TransportType transport_type = Extract<TransportType, 8, 2>(p1);
721 RailType railtype = INVALID_RAILTYPE;
722 RoadTypes rts = ROADTYPES_NONE;
723 _build_tunnel_endtile = 0;
724 switch (transport_type) {
725 case TRANSPORT_RAIL:
726 railtype = Extract<RailType, 0, 5>(p1);
727 if (!ValParamRailtype(railtype)) return CommandError();
728 break;
730 case TRANSPORT_ROAD:
731 rts = Extract<RoadTypes, 0, 2>(p1);
732 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(company, rts)) return CommandError();
733 break;
735 default: return CommandError();
738 if (company == OWNER_DEITY) {
739 if (transport_type != TRANSPORT_ROAD) return CommandError();
740 const Town *town = CalcClosestTownFromTile(start_tile);
742 company = OWNER_TOWN;
744 /* If we are not within a town, we are not owned by the town */
745 if (town == nullptr || DistanceSquare(start_tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
746 company = OWNER_NONE;
750 int start_z;
751 int end_z;
752 Slope start_tileh = GetTileSlope(start_tile, &start_z);
753 DiagDirection direction = GetInclinedSlopeDirection(start_tileh);
754 if (direction == INVALID_DIAGDIR) return CommandError(STR_ERROR_SITE_UNSUITABLE_FOR_TUNNEL);
756 if (HasTileWaterGround(start_tile)) return CommandError(STR_ERROR_CAN_T_BUILD_ON_WATER);
758 CommandCost ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
759 if (ret.Failed()) return ret;
761 /* XXX - do NOT change 'ret' in the loop, as it is used as the price
762 * for the clearing of the entrance of the tunnel. Assigning it to
763 * cost before the loop will yield different costs depending on start-
764 * position, because of increased-cost-by-length: 'cost += cost >> 3' */
766 TileIndexDiff delta = TileOffsByDiagDir(direction);
768 TileIndex end_tile = start_tile;
770 /* Tile shift coefficient. Will decrease for very long tunnels to avoid exponential growth of price*/
771 int tiles_coef = 3;
772 /* Number of tiles from start of tunnel */
773 int tiles = 0;
774 /* Number of tiles at which the cost increase coefficient per tile is halved */
775 int tiles_bump = 25;
776 /* flags for chunnels. */
777 bool is_chunnel = false;
778 bool crossed_sea = false;
779 /* Number of tiles counted for crossing sea */
780 int sea_tiles = 0;
782 if (start_z == 0 && _settings_game.construction.chunnel) {
783 CommandCost chunnel_test = CanBuildChunnel(start_tile, direction, is_chunnel, sea_tiles);
784 if (chunnel_test.Failed()) return chunnel_test;
787 Slope end_tileh;
788 for (;;) {
789 end_tile += delta;
790 if (!IsValidTile(end_tile)) return CommandError(STR_ERROR_TUNNEL_THROUGH_MAP_BORDER);
791 end_tileh = GetTileSlope(end_tile, &end_z);
793 if (start_z == end_z) {
794 if (is_chunnel && !crossed_sea) {
795 end_tile += sea_tiles * delta;
796 tiles += sea_tiles;
797 crossed_sea = true;
799 else {
800 break;
803 tiles++;
806 /* The cost of the digging. */
807 CommandCost cost(EXPENSES_CONSTRUCTION);
808 for (int i = 1; i <= tiles; i++) {
809 if (i == tiles_bump) {
810 tiles_coef++;
811 tiles_bump *= 2;
814 cost.AddCost(_price[PR_BUILD_TUNNEL]);
815 cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
818 /* Add the cost of the entrance */
819 cost.AddCost(_price[PR_BUILD_TUNNEL]);
820 cost.AddCost(ret);
822 /* if the command fails from here on we want the end tile to be highlighted */
823 _build_tunnel_endtile = end_tile;
825 if (tiles > _settings_game.construction.max_tunnel_length) return CommandError(STR_ERROR_TUNNEL_TOO_LONG);
827 if (HasTileWaterGround(end_tile)) return CommandError(STR_ERROR_CAN_T_BUILD_ON_WATER);
829 /* Clear the tile in any case */
830 ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
831 if (ret.Failed()) return CommandError(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
832 cost.AddCost(ret);
834 /* slope of end tile must be complementary to the slope of the start tile */
835 if (end_tileh != ComplementSlope(start_tileh)) {
836 /* Mark the tile as already cleared for the terraform command.
837 * Do this for all tiles (like trees), not only objects. */
838 ClearedObjectArea *coa = FindClearedObject(end_tile);
839 if (coa == nullptr) {
840 coa = _cleared_object_areas.Append();
841 coa->first_tile = end_tile;
842 coa->area = TileArea(end_tile, 1, 1);
845 /* Hide the tile from the terraforming command */
846 TileIndex old_first_tile = coa->first_tile;
847 coa->first_tile = INVALID_TILE;
848 ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
849 coa->first_tile = old_first_tile;
850 if (ret.Failed()) return CommandError(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
851 cost.AddCost(ret);
853 cost.AddCost(_price[PR_BUILD_TUNNEL]);
855 /* Pay for the rail/road in the tunnel including entrances */
856 switch (transport_type) {
857 case TRANSPORT_ROAD: cost.AddCost((tiles + 2) * _price[PR_BUILD_ROAD] * 2); break;
858 case TRANSPORT_RAIL: cost.AddCost((tiles + 2) * RailBuildCost(railtype)); break;
859 default: NOT_REACHED();
862 if (is_chunnel) cost.MultiplyCost(2);
864 if (flags & DC_EXEC) {
865 Company *c = Company::GetIfValid(company);
866 uint num_pieces = (tiles + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
868 /* The most northern tile first. */
869 TileIndex tn = start_tile;
870 TileIndex ts = end_tile;
871 if(start_tile > end_tile) Swap(tn, ts);
873 if (!Tunnel::CanAllocateItem()) return CommandError(STR_ERROR_TUNNEL_TOO_MANY);
874 const Tunnel *t = new Tunnel(tn, ts, TileHeight(tn), is_chunnel);
876 if (transport_type == TRANSPORT_RAIL) {
877 if (!IsTunnelTile(start_tile) && c != nullptr) c->infrastructure.rail[railtype] += num_pieces;
878 MakeRailTunnel(start_tile, company, t->index, direction, railtype);
879 MakeRailTunnel(end_tile, company, t->index, ReverseDiagDir(direction), railtype);
880 AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, company);
881 YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
882 } else {
883 if (c != nullptr) {
884 RoadType rt;
885 FOR_EACH_SET_ROADTYPE(rt, rts ^ (IsTunnelTile(start_tile) ? GetRoadTypes(start_tile) : ROADTYPES_NONE)) {
886 c->infrastructure.road[rt] += num_pieces * 2; // A full diagonal road has two road bits.
889 MakeRoadTunnel(start_tile, company, t->index, direction, rts);
890 MakeRoadTunnel(end_tile, company, t->index, ReverseDiagDir(direction), rts);
892 DirtyCompanyInfrastructureWindows(company);
895 return cost;
900 * Are we allowed to remove the tunnel or bridge at \a tile?
901 * @param tile End point of the tunnel or bridge.
902 * @return A succeeded command if the tunnel or bridge may be removed, a failed command otherwise.
904 static inline CommandCost CheckAllowRemoveTunnelBridge(TileIndex tile)
906 /* Floods can remove anything as well as the scenario editor */
907 if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return CommandCost();
909 switch (GetTunnelBridgeTransportType(tile)) {
910 case TRANSPORT_ROAD: {
911 RoadTypes rts = GetRoadTypes(tile);
912 Owner road_owner = _current_company;
913 Owner tram_owner = _current_company;
915 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
916 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
918 /* We can remove unowned road and if the town allows it */
919 if (road_owner == OWNER_TOWN && _current_company != OWNER_TOWN && !(_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) {
920 /* Town does not allow */
921 return CheckTileOwnership(tile);
923 if (road_owner == OWNER_NONE || road_owner == OWNER_TOWN) road_owner = _current_company;
924 if (tram_owner == OWNER_NONE) tram_owner = _current_company;
926 CommandCost ret = CheckOwnership(road_owner, tile);
927 if (ret.Succeeded()) ret = CheckOwnership(tram_owner, tile);
928 return ret;
931 case TRANSPORT_RAIL:
932 return CheckOwnership(GetTileOwner(tile));
934 case TRANSPORT_WATER: {
935 /* Always allow to remove aqueducts without owner. */
936 Owner aqueduct_owner = GetTileOwner(tile);
937 if (aqueduct_owner == OWNER_NONE) aqueduct_owner = _current_company;
938 return CheckOwnership(aqueduct_owner);
941 default: NOT_REACHED();
946 * Remove a tunnel from the game, update town rating, etc.
947 * @param tile Tile containing one of the endpoints of the tunnel.
948 * @param flags Command flags.
949 * @return Succeeded or failed command.
951 static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
953 CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
954 if (ret.Failed()) return ret;
956 TileIndex endtile = GetOtherTunnelEnd(tile);
958 ret = TunnelBridgeIsFree(tile, endtile);
959 if (ret.Failed()) return ret;
961 _build_tunnel_endtile = endtile;
963 Town *t = nullptr;
964 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
965 t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
967 /* Check if you are allowed to remove the tunnel owned by a town
968 * Removal depends on difficulty settings */
969 CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
970 if (ret.Failed()) return ret;
973 /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
974 * you have a "Poor" (0) town rating */
975 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
976 ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
979 const bool is_chunnel = Tunnel::GetByTile(tile)->is_chunnel;
981 uint len = GetTunnelBridgeLength(tile, endtile) + 2; // Don't forget the end tiles.
983 if (flags & DC_EXEC) {
984 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
985 /* We first need to request values before calling DoClearSquare */
986 DiagDirection dir = GetTunnelBridgeDirection(tile);
987 Track track = DiagDirToDiagTrack(dir);
988 Owner owner = GetTileOwner(tile);
990 Train *v = nullptr;
991 if (HasTunnelBridgeReservation(tile)) {
992 v = GetTrainForReservation(tile, track);
993 if (v != nullptr) FreeTrainTrackReservation(v);
996 if (Company::IsValidID(owner)) {
997 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
998 if (IsTunnelBridgeWithSignalSimulation(tile)) { // handle tunnel/bridge signals.
999 Company::Get(GetTileOwner(tile))->infrastructure.signal -= GetTunnelBridgeSignalSimulationSignalCount(tile, endtile);
1001 DirtyCompanyInfrastructureWindows(owner);
1004 delete Tunnel::GetByTile(tile);
1006 DoClearSquare(tile);
1007 DoClearSquare(endtile);
1009 /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
1010 AddSideToSignalBuffer(tile, ReverseDiagDir(dir), owner);
1011 AddSideToSignalBuffer(endtile, dir, owner);
1013 YapfNotifyTrackLayoutChange(tile, track);
1014 YapfNotifyTrackLayoutChange(endtile, track);
1016 if (v != nullptr) TryPathReserve(v);
1017 } else {
1018 RoadType rt;
1019 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
1020 /* A full diagonal road tile has two road bits. */
1021 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
1022 if (c != nullptr) {
1023 c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
1024 DirtyCompanyInfrastructureWindows(c->index);
1028 delete Tunnel::GetByTile(tile);
1030 DoClearSquare(tile);
1031 DoClearSquare(endtile);
1033 ViewportMapInvalidateTunnelCacheByTile(tile);
1034 ViewportMapInvalidateTunnelCacheByTile(endtile);
1036 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_TUNNEL] * len * (is_chunnel ? 2 : 1));
1041 * Remove a bridge from the game, update town rating, etc.
1042 * @param tile Tile containing one of the endpoints of the bridge.
1043 * @param flags Command flags.
1044 * @return Succeeded or failed command.
1046 static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
1048 CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
1049 if (ret.Failed()) return ret;
1051 TileIndex endtile = GetOtherBridgeEnd(tile);
1053 ret = TunnelBridgeIsFree(tile, endtile);
1054 if (ret.Failed()) return ret;
1056 DiagDirection direction = GetTunnelBridgeDirection(tile);
1057 TileIndexDiff delta = TileOffsByDiagDir(direction);
1059 Town *t = nullptr;
1060 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
1061 t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
1063 /* Check if you are allowed to remove the bridge owned by a town
1064 * Removal depends on difficulty settings */
1065 CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
1066 if (ret.Failed()) return ret;
1069 /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
1070 * you have a "Poor" (0) town rating */
1071 if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
1072 ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
1075 Money base_cost = (GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) ? _price[PR_CLEAR_BRIDGE] : _price[PR_CLEAR_AQUEDUCT];
1076 uint len = GetTunnelBridgeLength(tile, endtile) + 2; // Don't forget the end tiles.
1078 if (flags & DC_EXEC) {
1079 /* read this value before actual removal of bridge */
1080 bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
1081 Owner owner = GetTileOwner(tile);
1082 int height = GetBridgeHeight(tile);
1083 Train *v = nullptr;
1085 if (rail && HasTunnelBridgeReservation(tile)) {
1086 v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
1087 if (v != nullptr) FreeTrainTrackReservation(v);
1090 /* Update company infrastructure counts. */
1091 if (rail) {
1092 if (Company::IsValidID(owner)) {
1093 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
1094 if (IsTunnelBridgeWithSignalSimulation(tile)) { // handle tunnel/bridge signals.
1095 Company::Get(GetTileOwner(tile))->infrastructure.signal -= GetTunnelBridgeSignalSimulationSignalCount(tile, endtile);
1098 } else if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
1099 SubtractRoadTunnelBridgeInfrastructure(tile, endtile);
1100 } else { // Aqueduct
1101 if (Company::IsValidID(owner)) Company::Get(owner)->infrastructure.water -= len * TUNNELBRIDGE_TRACKBIT_FACTOR;
1103 DirtyAllCompanyInfrastructureWindows();
1105 if (IsTunnelBridgeSignalSimulationEntrance(tile)) ClearBridgeEntranceSimulatedSignals(tile);
1106 if (IsTunnelBridgeSignalSimulationEntrance(endtile)) ClearBridgeEntranceSimulatedSignals(endtile);
1108 DoClearSquare(tile);
1109 DoClearSquare(endtile);
1110 for (TileIndex c = tile + delta; c != endtile; c += delta) {
1111 /* do not let trees appear from 'nowhere' after removing bridge */
1112 if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
1113 int minz = GetTileMaxZ(c) + 3;
1114 if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
1116 ClearBridgeMiddle(c);
1117 MarkTileDirtyByTile(c, ZOOM_LVL_DRAW_MAP, height - TileHeight(c));
1120 if (rail) {
1121 /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
1122 AddSideToSignalBuffer(tile, ReverseDiagDir(direction), owner);
1123 AddSideToSignalBuffer(endtile, direction, owner);
1125 Track track = DiagDirToDiagTrack(direction);
1126 YapfNotifyTrackLayoutChange(tile, track);
1127 YapfNotifyTrackLayoutChange(endtile, track);
1129 if (v != nullptr) TryPathReserve(v, true);
1133 return CommandCost(EXPENSES_CONSTRUCTION, len * base_cost);
1137 * Remove a tunnel or a bridge from the game.
1138 * @param tile Tile containing one of the endpoints.
1139 * @param flags Command flags.
1140 * @return Succeeded or failed command.
1142 static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
1144 if (IsTunnel(tile)) {
1145 if (flags & DC_AUTO) return CommandError(STR_ERROR_MUST_DEMOLISH_TUNNEL_FIRST);
1146 return DoClearTunnel(tile, flags);
1147 } else { // IsBridge(tile)
1148 if (flags & DC_AUTO) return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1149 return DoClearBridge(tile, flags);
1154 * Draw a single pillar sprite.
1155 * @param psid Pillarsprite
1156 * @param x Pillar X
1157 * @param y Pillar Y
1158 * @param z Pillar Z
1159 * @param w Bounding box size in X direction
1160 * @param h Bounding box size in Y direction
1161 * @param subsprite Optional subsprite for drawing halfpillars
1163 static inline void DrawPillar(const PalSpriteID *psid, int x, int y, int z, int w, int h, const SubSprite *subsprite)
1165 static const int PILLAR_Z_OFFSET = TILE_HEIGHT - BRIDGE_Z_START; ///< Start offset of pillar wrt. bridge (downwards)
1166 AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, w, h, BB_HEIGHT_UNDER_BRIDGE - PILLAR_Z_OFFSET, z, IsTransparencySet(TO_BRIDGES), 0, 0, -PILLAR_Z_OFFSET, subsprite);
1170 * Draw two bridge pillars (north and south).
1171 * @param z_bottom Bottom Z
1172 * @param z_top Top Z
1173 * @param psid Pillarsprite
1174 * @param x Pillar X
1175 * @param y Pillar Y
1176 * @param w Bounding box size in X direction
1177 * @param h Bounding box size in Y direction
1178 * @return Reached Z at the bottom
1180 static int DrawPillarColumn(int z_bottom, int z_top, const PalSpriteID *psid, int x, int y, int w, int h)
1182 int cur_z;
1183 for (cur_z = z_top; cur_z >= z_bottom; cur_z -= TILE_HEIGHT) {
1184 DrawPillar(psid, x, y, cur_z, w, h, nullptr);
1186 return cur_z;
1190 * Draws the pillars under high bridges.
1192 * @param psid Image and palette of a bridge pillar.
1193 * @param ti #TileInfo of current bridge-middle-tile.
1194 * @param axis Orientation of bridge.
1195 * @param drawfarpillar Whether to draw the pillar at the back
1196 * @param x Sprite X position of front pillar.
1197 * @param y Sprite Y position of front pillar.
1198 * @param z_bridge Absolute height of bridge bottom.
1200 static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
1202 static const int bounding_box_size[2] = {16, 2}; ///< bounding box size of pillars along bridge direction
1203 static const int back_pillar_offset[2] = { 0, 9}; ///< sprite position offset of back facing pillar
1205 static const int INF = 1000; ///< big number compared to sprite size
1206 static const SubSprite half_pillar_sub_sprite[2][2] = {
1207 { { -14, -INF, INF, INF }, { -INF, -INF, -15, INF } }, // X axis, north and south
1208 { { -INF, -INF, 15, INF }, { 16, -INF, INF, INF } }, // Y axis, north and south
1211 if (psid->sprite == 0) return;
1213 /* Determine ground height under pillars */
1214 DiagDirection south_dir = AxisToDiagDir(axis);
1215 int z_front_north = ti->z;
1216 int z_back_north = ti->z;
1217 int z_front_south = ti->z;
1218 int z_back_south = ti->z;
1219 GetSlopePixelZOnEdge(ti->tileh, south_dir, &z_front_south, &z_back_south);
1220 GetSlopePixelZOnEdge(ti->tileh, ReverseDiagDir(south_dir), &z_front_north, &z_back_north);
1222 /* Shared height of pillars */
1223 int z_front = max(z_front_north, z_front_south);
1224 int z_back = max(z_back_north, z_back_south);
1226 /* x and y size of bounding-box of pillars */
1227 int w = bounding_box_size[axis];
1228 int h = bounding_box_size[OtherAxis(axis)];
1229 /* sprite position of back facing pillar */
1230 int x_back = x - back_pillar_offset[axis];
1231 int y_back = y - back_pillar_offset[OtherAxis(axis)];
1233 /* Draw front pillars */
1234 int bottom_z = DrawPillarColumn(z_front, z_bridge, psid, x, y, w, h);
1235 if (z_front_north < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
1236 if (z_front_south < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
1238 /* Draw back pillars, skip top two parts, which are hidden by the bridge */
1239 int z_bridge_back = z_bridge - 2 * (int)TILE_HEIGHT;
1240 if (drawfarpillar && (z_back_north <= z_bridge_back || z_back_south <= z_bridge_back)) {
1241 bottom_z = DrawPillarColumn(z_back, z_bridge_back, psid, x_back, y_back, w, h);
1242 if (z_back_north < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
1243 if (z_back_south < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
1248 * Draws the trambits over an already drawn (lower end) of a bridge.
1249 * @param x the x of the bridge
1250 * @param y the y of the bridge
1251 * @param z the z of the bridge
1252 * @param offset number representing whether to level or sloped and the direction
1253 * @param overlay do we want to still see the road?
1254 * @param head are we drawing bridge head?
1256 static void DrawBridgeTramBits(int x, int y, int z, int offset, bool overlay, bool head)
1258 static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
1259 static const SpriteID back_offsets[6] = { 95, 96, 99, 102, 100, 101 };
1260 static const SpriteID front_offsets[6] = { 97, 98, 103, 106, 104, 105 };
1262 static const uint size_x[6] = { 1, 16, 16, 1, 16, 1 };
1263 static const uint size_y[6] = { 16, 1, 1, 16, 1, 16 };
1264 static const uint front_bb_offset_x[6] = { 15, 0, 0, 15, 0, 15 };
1265 static const uint front_bb_offset_y[6] = { 0, 15, 15, 0, 15, 0 };
1267 /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
1268 * The bounding boxes here are the same as for bridge front/roof */
1269 if (head || !IsInvisibilitySet(TO_BRIDGES)) {
1270 AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
1271 x, y, size_x[offset], size_y[offset], 0x28, z,
1272 !head && IsTransparencySet(TO_BRIDGES));
1275 /* Do not draw catenary if it is set invisible */
1276 if (!IsInvisibilitySet(TO_CATENARY)) {
1277 AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
1278 x, y, size_x[offset], size_y[offset], 0x28, z,
1279 IsTransparencySet(TO_CATENARY));
1282 /* Start a new SpriteCombine for the front part */
1283 EndSpriteCombine();
1284 StartSpriteCombine();
1286 /* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
1287 if (!IsInvisibilitySet(TO_CATENARY)) {
1288 AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
1289 x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
1290 IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
1294 /* Draws a signal on tunnel / bridge entrance tile. */
1295 static void DrawTunnelBridgeRampSignal(const TileInfo *ti)
1297 bool side = (_settings_game.vehicle.road_side != 0) &&_settings_game.construction.train_signal_side;
1299 static const Point SignalPositions[2][4] = {
1300 { /* X X Y Y Signals on the left side */
1301 {13, 3}, { 2, 13}, { 3, 4}, {13, 14}
1302 }, {/* X X Y Y Signals on the right side */
1303 {14, 13}, { 3, 3}, {13, 2}, { 3, 13}
1307 uint position;
1308 DiagDirection dir = GetTunnelBridgeDirection(ti->tile);
1310 switch (dir) {
1311 default: NOT_REACHED();
1312 case DIAGDIR_NE: position = 0; break;
1313 case DIAGDIR_SE: position = 2; break;
1314 case DIAGDIR_SW: position = 1; break;
1315 case DIAGDIR_NW: position = 3; break;
1318 SignalType type = SIGTYPE_NORMAL;
1320 bool is_green = (GetTunnelBridgeSignalState(ti->tile) == SIGNAL_STATE_GREEN);
1321 bool show_exit;
1322 if (IsTunnelBridgeSignalSimulationExit(ti->tile)) {
1323 show_exit = true;
1324 position ^= 1;
1325 if (IsTunnelBridgePBS(ti->tile)) type = SIGTYPE_PBS_ONEWAY;
1326 } else {
1327 show_exit = false;
1330 uint x = TileX(ti->tile) * TILE_SIZE + SignalPositions[side != show_exit][position ^ (show_exit ? 1 : 0)].x;
1331 uint y = TileY(ti->tile) * TILE_SIZE + SignalPositions[side != show_exit][position ^ (show_exit ? 1 : 0)].y;
1332 uint z = ti->z;
1334 if (ti->tileh == SLOPE_FLAT && side == show_exit && dir == DIAGDIR_SE) z += 2;
1335 if (ti->tileh == SLOPE_FLAT && side != show_exit && dir == DIAGDIR_SW) z += 2;
1337 if (ti->tileh != SLOPE_FLAT && IsBridge(ti->tile)) z += 8; // sloped bridge head
1338 SignalVariant variant = IsTunnelBridgeSemaphore(ti->tile) ? SIG_SEMAPHORE : SIG_ELECTRIC;
1339 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1341 SpriteID sprite = GetCustomSignalSprite(rti, ti->tile, type, variant, is_green ? SIGNAL_STATE_GREEN : SIGNAL_STATE_RED);
1342 bool is_custom_sprite = (sprite != 0);
1344 if (is_custom_sprite) {
1345 sprite += position;
1347 else {
1348 if (variant == SIG_ELECTRIC && type == SIGTYPE_NORMAL) {
1349 /* Normal electric signals are picked from original sprites. */
1350 sprite = SPR_ORIGINAL_SIGNALS_BASE + ((position << 1) + is_green);
1352 else {
1353 /* All other signals are picked from add on sprites. */
1354 sprite = SPR_SIGNALS_BASE + ((type - 1) * 16 + variant * 64 + (position << 1) + is_green) + (type > SIGTYPE_LAST_NOPBS ? 64 : 0);
1358 AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, TILE_HEIGHT, z, false, 0, 0, BB_Z_SEPARATOR);
1362 * Draws a tunnel of bridge tile.
1363 * For tunnels, this is rather simple, as you only need to draw the entrance.
1364 * Bridges are a bit more complex. base_offset is where the sprite selection comes into play
1365 * and it works a bit like a bitmask.<p> For bridge heads:
1366 * @param ti TileInfo of the structure to draw
1367 * <ul><li>Bit 0: direction</li>
1368 * <li>Bit 1: northern or southern heads</li>
1369 * <li>Bit 2: Set if the bridge head is sloped</li>
1370 * <li>Bit 3 and more: Railtype Specific subset</li>
1371 * </ul>
1372 * Please note that in this code, "roads" are treated as railtype 1, whilst the real railtypes are 0, 2 and 3
1374 static void DrawTile_TunnelBridge(TileInfo *ti)
1376 TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
1377 DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
1379 if (IsTunnel(ti->tile)) {
1380 /* Front view of tunnel bounding boxes:
1382 * 122223 <- BB_Z_SEPARATOR
1383 * 1 3
1384 * 1 3 1,3 = empty helper BB
1385 * 1 3 2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
1389 static const int _tunnel_BB[4][12] = {
1390 /* tunnnel-roof | Z-separator | tram-catenary
1391 * w h bb_x bb_y| x y w h |bb_x bb_y w h */
1392 { 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // NE
1393 { 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // SE
1394 { 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // SW
1395 { 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // NW
1397 const int *BB_data = _tunnel_BB[tunnelbridge_direction];
1399 bool catenary = false;
1401 SpriteID image;
1402 SpriteID railtype_overlay = 0;
1403 if (transport_type == TRANSPORT_RAIL) {
1404 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1405 image = rti->base_sprites.tunnel;
1406 if (rti->UsesOverlay()) {
1407 /* Check if the railtype has custom tunnel portals. */
1408 railtype_overlay = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL_PORTAL);
1409 if (railtype_overlay != 0) image = SPR_RAILTYPE_TUNNEL_BASE; // Draw blank grass tunnel base.
1411 } else {
1412 image = SPR_TUNNEL_ENTRY_REAR_ROAD;
1415 if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += railtype_overlay != 0 ? 8 : 32;
1417 image += tunnelbridge_direction * 2;
1418 DrawGroundSprite(image, PAL_NONE);
1420 if (transport_type == TRANSPORT_ROAD) {
1421 RoadTypes rts = GetRoadTypes(ti->tile);
1423 if (HasBit(rts, ROADTYPE_TRAM)) {
1424 static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, { 5, 76, 77, 4 } };
1426 DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
1428 /* Do not draw wires if they are invisible */
1429 if (!IsInvisibilitySet(TO_CATENARY)) {
1430 catenary = true;
1431 StartSpriteCombine();
1432 AddSortableSpriteToDraw(SPR_TRAMWAY_TUNNEL_WIRES + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, BB_data[10], BB_data[11], TILE_HEIGHT, ti->z, IsTransparencySet(TO_CATENARY), BB_data[8], BB_data[9], BB_Z_SEPARATOR);
1435 } else {
1436 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1437 if (rti->UsesOverlay()) {
1438 SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL);
1439 if (surface != 0) DrawGroundSprite(surface + tunnelbridge_direction, PAL_NONE);
1442 DrawOverlay(ti, MP_TUNNELBRIDGE);
1444 /* PBS debugging, draw reserved tracks darker */
1445 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
1446 if (rti->UsesOverlay()) {
1447 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1448 DrawGroundSprite(overlay + RTO_X + DiagDirToAxis(tunnelbridge_direction), PALETTE_CRASH);
1449 } else {
1450 DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
1454 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) {
1455 /* Maybe draw pylons on the entry side */
1456 DrawRailCatenary(ti);
1458 catenary = true;
1459 StartSpriteCombine();
1460 /* Draw wire above the ramp */
1461 DrawRailCatenaryOnTunnel(ti);
1465 if (railtype_overlay != 0 && !catenary) StartSpriteCombine();
1467 AddSortableSpriteToDraw(image + 1, PAL_NONE, ti->x + TILE_SIZE - 1, ti->y + TILE_SIZE - 1, BB_data[0], BB_data[1], TILE_HEIGHT, ti->z, false, BB_data[2], BB_data[3], BB_Z_SEPARATOR);
1468 /* Draw railtype tunnel portal overlay if defined. */
1469 if (railtype_overlay != 0) AddSortableSpriteToDraw(railtype_overlay + tunnelbridge_direction, PAL_NONE, ti->x + TILE_SIZE - 1, ti->y + TILE_SIZE - 1, BB_data[0], BB_data[1], TILE_HEIGHT, ti->z, false, BB_data[2], BB_data[3], BB_Z_SEPARATOR);
1471 if (catenary || railtype_overlay != 0) EndSpriteCombine();
1473 /* Add helper BB for sprite sorting that separates the tunnel from things beside of it. */
1474 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x, ti->y, BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
1475 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x + BB_data[4], ti->y + BB_data[5], BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
1477 /* Draw signals for tunnel. */
1478 if (IsTunnelBridgeWithSignalSimulation(ti->tile)) DrawTunnelBridgeRampSignal(ti);
1480 DrawBridgeMiddle(ti);
1481 } else { // IsBridge(ti->tile)
1482 if (transport_type == TRANSPORT_ROAD && IsRoadCustomBridgeHead(ti->tile)) {
1483 DrawRoadBits(ti);
1484 DrawBridgeMiddle(ti);
1485 return;
1488 const PalSpriteID *psid;
1489 int base_offset;
1490 bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
1492 if (transport_type == TRANSPORT_RAIL) {
1493 base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
1494 assert(base_offset != 8); // This one is used for roads
1495 } else {
1496 base_offset = 8;
1499 /* as the lower 3 bits are used for other stuff, make sure they are clear */
1500 assert( (base_offset & 0x07) == 0x00);
1502 DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
1504 /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
1505 base_offset += (6 - tunnelbridge_direction) % 4;
1507 /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
1508 if (transport_type != TRANSPORT_WATER) {
1509 if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
1510 psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
1511 } else {
1512 psid = _aqueduct_sprites + base_offset;
1515 if (!ice) {
1516 TileIndex next = ti->tile + TileOffsByDiagDir(tunnelbridge_direction);
1517 if (ti->tileh != SLOPE_FLAT && ti->z == 0 && HasTileWaterClass(next) && GetWaterClass(next) == WATER_CLASS_SEA) {
1518 DrawShoreTile(ti->tileh);
1519 } else {
1520 DrawClearLandTile(ti, 3);
1522 } else {
1523 DrawGroundSprite(SPR_FLAT_SNOW_DESERT_TILE + SlopeToSpriteOffset(ti->tileh), PAL_NONE);
1526 /* draw ramp */
1528 /* Draw Trambits and PBS Reservation as SpriteCombine */
1529 if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
1531 /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
1532 * it doesn't disappear behind it
1534 /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
1535 AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
1537 if (transport_type == TRANSPORT_ROAD) {
1538 RoadTypes rts = GetRoadTypes(ti->tile);
1540 if (HasBit(rts, ROADTYPE_TRAM)) {
1541 uint offset = tunnelbridge_direction;
1542 int z = ti->z;
1543 if (ti->tileh != SLOPE_FLAT) {
1544 offset = (offset + 1) & 1;
1545 z += TILE_HEIGHT;
1546 } else {
1547 offset += 2;
1549 /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
1550 DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
1552 EndSpriteCombine();
1553 } else if (transport_type == TRANSPORT_RAIL) {
1554 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1555 if (rti->UsesOverlay()) {
1556 SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_BRIDGE);
1557 if (surface != 0) {
1558 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1559 AddSortableSpriteToDraw(surface + ((DiagDirToAxis(tunnelbridge_direction) == AXIS_X) ? RTBO_X : RTBO_Y), PAL_NONE, ti->x, ti->y, 16, 16, 0, ti->z + 8);
1560 } else {
1561 AddSortableSpriteToDraw(surface + RTBO_SLOPE + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, 16, 16, 8, ti->z);
1564 /* Don't fallback to non-overlay sprite -- the spec states that
1565 * if an overlay is present then the bridge surface must be
1566 * present. */
1569 /* PBS debugging, draw reserved tracks darker */
1570 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
1571 if (rti->UsesOverlay()) {
1572 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1573 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1574 AddSortableSpriteToDraw(overlay + RTO_X + DiagDirToAxis(tunnelbridge_direction), PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 8);
1575 } else {
1576 AddSortableSpriteToDraw(overlay + RTO_SLOPE_NE + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
1578 } else {
1579 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1580 AddSortableSpriteToDraw(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 8);
1581 } else {
1582 AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
1587 EndSpriteCombine();
1588 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) {
1589 DrawRailCatenary(ti);
1593 /* Draw signals for bridge. */
1594 if (IsTunnelBridgeWithSignalSimulation(ti->tile)) DrawTunnelBridgeRampSignal(ti);
1596 DrawBridgeMiddle(ti);
1602 * Compute bridge piece. Computes the bridge piece to display depending on the position inside the bridge.
1603 * bridges pieces sequence (middle parts).
1604 * Note that it is not covering the bridge heads, which are always referenced by the same sprite table.
1605 * bridge len 1: BRIDGE_PIECE_NORTH
1606 * bridge len 2: BRIDGE_PIECE_NORTH BRIDGE_PIECE_SOUTH
1607 * bridge len 3: BRIDGE_PIECE_NORTH BRIDGE_PIECE_MIDDLE_ODD BRIDGE_PIECE_SOUTH
1608 * bridge len 4: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1609 * bridge len 5: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_MIDDLE_EVEN BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1610 * bridge len 6: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1611 * bridge len 7: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_MIDDLE_ODD BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1612 * #0 - always as first, #1 - always as last (if len>1)
1613 * #2,#3 are to pair in order
1614 * for odd bridges: #5 is going in the bridge middle if on even position, #4 on odd (counting from 0)
1615 * @param north Northernmost tile of bridge
1616 * @param south Southernmost tile of bridge
1617 * @return Index of bridge piece
1619 static BridgePieces CalcBridgePiece(uint north, uint south)
1621 if (north == 1) {
1622 return BRIDGE_PIECE_NORTH;
1623 } else if (south == 1) {
1624 return BRIDGE_PIECE_SOUTH;
1625 } else if (north < south) {
1626 return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
1627 } else if (north > south) {
1628 return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
1629 } else {
1630 return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
1635 * Draw the middle bits of a bridge.
1636 * @param ti Tile information of the tile to draw it on.
1638 void DrawBridgeMiddle(const TileInfo *ti)
1640 /* Sectional view of bridge bounding boxes:
1642 * 1 2 1,2 = SpriteCombine of Bridge front/(back&floor) and RoadCatenary
1643 * 1 2 3 = empty helper BB
1644 * 1 7 2 4,5 = pillars under higher bridges
1645 * 1 6 88888 6 2 6 = elrail-pylons
1646 * 1 6 88888 6 2 7 = elrail-wire
1647 * 1 6 88888 6 2 <- TILE_HEIGHT 8 = rail-vehicle on bridge
1648 * 3333333333333 <- BB_Z_SEPARATOR
1649 * <- unused
1650 * 4 5 <- BB_HEIGHT_UNDER_BRIDGE
1651 * 4 5
1652 * 4 5
1656 if (!IsBridgeAbove(ti->tile)) return;
1658 TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
1659 TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
1660 TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
1662 Axis axis = GetBridgeAxis(ti->tile);
1663 BridgePieces piece = CalcBridgePiece(
1664 GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
1665 GetTunnelBridgeLength(ti->tile, rampsouth) + 1
1668 const PalSpriteID *psid;
1669 bool drawfarpillar;
1670 if (transport_type != TRANSPORT_WATER) {
1671 BridgeType type = GetBridgeType(rampsouth);
1672 drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
1674 uint base_offset;
1675 if (transport_type == TRANSPORT_RAIL) {
1676 base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
1677 } else {
1678 base_offset = 8;
1681 psid = base_offset + GetBridgeSpriteTable(type, piece);
1682 } else {
1683 drawfarpillar = true;
1684 psid = _aqueduct_sprites;
1687 if (axis != AXIS_X) psid += 4;
1689 int x = ti->x;
1690 int y = ti->y;
1691 uint bridge_z = GetBridgePixelHeight(rampsouth);
1692 int z = bridge_z - BRIDGE_Z_START;
1694 /* Add a bounding box that separates the bridge from things below it. */
1695 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
1697 /* Draw Trambits as SpriteCombine */
1698 if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
1700 /* Draw floor and far part of bridge*/
1701 if (!IsInvisibilitySet(TO_BRIDGES)) {
1702 if (axis == AXIS_X) {
1703 AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
1704 } else {
1705 AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
1709 psid++;
1711 if (transport_type == TRANSPORT_ROAD) {
1712 const RoadTypes rts = GetRoadTypes(rampsouth);
1714 bool has_tram = HasBit(rts, ROADTYPE_TRAM);
1715 bool has_road = HasBit(rts, ROADTYPE_ROAD);
1716 if (IsRoadCustomBridgeHeadTile(rampsouth)) {
1717 RoadBits entrance_bit = DiagDirToRoadBits(GetTunnelBridgeDirection(rampsouth));
1718 has_tram = has_tram && (GetCustomBridgeHeadRoadBits(rampsouth, ROADTYPE_TRAM) & entrance_bit);
1719 has_road = has_road && (GetCustomBridgeHeadRoadBits(rampsouth, ROADTYPE_ROAD) & entrance_bit);
1722 if (has_tram) {
1723 /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
1724 DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, has_road, false);
1725 } else {
1726 EndSpriteCombine();
1727 StartSpriteCombine();
1729 } else if (transport_type == TRANSPORT_RAIL) {
1730 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(rampsouth));
1731 if (rti->UsesOverlay() && !IsInvisibilitySet(TO_BRIDGES)) {
1732 SpriteID surface = GetCustomRailSprite(rti, rampsouth, RTSG_BRIDGE, TCX_ON_BRIDGE);
1733 if (surface != 0) {
1734 AddSortableSpriteToDraw(surface + axis, PAL_NONE, x, y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
1738 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && !IsInvisibilitySet(TO_BRIDGES) && HasTunnelBridgeReservation(rampnorth)
1739 && !IsTunnelBridgeWithSignalSimulation(rampnorth)) {
1740 if (rti->UsesOverlay()) {
1741 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1742 AddSortableSpriteToDraw(overlay + RTO_X + axis, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
1743 } else {
1744 AddSortableSpriteToDraw(axis == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
1748 EndSpriteCombine();
1750 if (HasRailCatenaryDrawn(GetRailType(rampsouth))) {
1751 DrawRailCatenaryOnBridge(ti);
1755 /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
1756 if (!IsInvisibilitySet(TO_BRIDGES)) {
1757 if (axis == AXIS_X) {
1758 y += 12;
1759 if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
1760 } else {
1761 x += 12;
1762 if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
1766 /* Draw TramFront as SpriteCombine */
1767 if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
1769 /* Do not draw anything more if bridges are invisible */
1770 if (IsInvisibilitySet(TO_BRIDGES)) return;
1772 psid++;
1773 if (ti->z + 5 == z) {
1774 /* draw poles below for small bridges */
1775 if (psid->sprite != 0) {
1776 SpriteID image = psid->sprite;
1777 SpriteID pal = psid->pal;
1778 if (IsTransparencySet(TO_BRIDGES)) {
1779 SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
1780 pal = PALETTE_TO_TRANSPARENT;
1783 DrawGroundSpriteAt(image, pal, x - ti->x, y - ti->y, z - ti->z);
1785 } else {
1786 /* draw pillars below for high bridges */
1787 DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
1792 static int GetSlopePixelZ_TunnelBridge(TileIndex tile, uint x, uint y)
1794 int z;
1795 Slope tileh = GetTilePixelSlope(tile, &z);
1797 x &= 0xF;
1798 y &= 0xF;
1800 if (IsTunnel(tile)) {
1801 uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
1803 /* In the tunnel entrance? */
1804 if (5 <= pos && pos <= 10) return z;
1805 } else { // IsBridge(tile)
1806 if (IsRoadCustomBridgeHeadTile(tile)) {
1807 return z + TILE_HEIGHT + (IsSteepSlope(tileh) ? TILE_HEIGHT : 0);
1810 DiagDirection dir = GetTunnelBridgeDirection(tile);
1811 uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
1813 z += ApplyPixelFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
1815 /* On the bridge ramp? */
1816 if (5 <= pos && pos <= 10) {
1817 int delta;
1819 if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
1821 switch (dir) {
1822 default: NOT_REACHED();
1823 case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
1824 case DIAGDIR_SE: delta = y / 2; break;
1825 case DIAGDIR_SW: delta = x / 2; break;
1826 case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
1828 return z + 1 + delta;
1832 return z + GetPartialPixelZ(x, y, tileh);
1835 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
1837 if (IsRoadCustomBridgeHeadTile(tile)) return FOUNDATION_LEVELED;
1838 return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
1841 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
1843 TransportType tt = GetTunnelBridgeTransportType(tile);
1845 if (IsTunnel(tile)) {
1846 if (Tunnel::GetByTile(tile)->is_chunnel) {
1847 td->str = (tt == TRANSPORT_RAIL) ? IsTunnelBridgeWithSignalSimulation(tile) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD_SIGNAL_CHUNNEL : STR_LAI_TUNNEL_DESCRIPTION_RAILROAD_CHUNNEL : STR_LAI_TUNNEL_DESCRIPTION_ROAD_CHUNNEL;
1848 } else {
1849 td->str = (tt == TRANSPORT_RAIL) ? IsTunnelBridgeWithSignalSimulation(tile) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD_SIGNAL : STR_LAI_TUNNEL_DESCRIPTION_RAILROAD : STR_LAI_TUNNEL_DESCRIPTION_ROAD;
1851 } else { // IsBridge(tile)
1852 td->str = (tt == TRANSPORT_WATER) ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT : IsTunnelBridgeWithSignalSimulation(tile) ? STR_LAI_BRIDGE_DESCRIPTION_RAILROAD_SIGNAL : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
1854 td->owner[0] = GetTileOwner(tile);
1856 Owner road_owner = INVALID_OWNER;
1857 Owner tram_owner = INVALID_OWNER;
1858 RoadTypes rts = GetRoadTypes(tile);
1859 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
1860 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
1862 /* Is there a mix of owners? */
1863 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
1864 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
1865 uint i = 1;
1866 if (road_owner != INVALID_OWNER) {
1867 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
1868 td->owner[i] = road_owner;
1869 i++;
1871 if (tram_owner != INVALID_OWNER) {
1872 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
1873 td->owner[i] = tram_owner;
1877 if (tt == TRANSPORT_RAIL) {
1878 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
1879 td->rail_speed = rti->max_speed;
1880 td->railtype = rti->strings.name;
1882 if (!IsTunnel(tile)) {
1883 uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
1884 if (td->rail_speed == 0 || spd < td->rail_speed) {
1885 td->rail_speed = spd;
1888 } else if (tt == TRANSPORT_ROAD && !IsTunnel(tile)) {
1889 td->road_speed = GetBridgeSpec(GetBridgeType(tile))->speed;
1894 static void TileLoop_TunnelBridge(TileIndex tile)
1896 bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
1897 switch (_settings_game.game_creation.landscape) {
1898 case LT_ARCTIC: {
1899 /* As long as we do not have a snow density, we want to use the density
1900 * from the entry edge. */
1901 int z = GetTileMaxZ(tile);
1902 if (snow_or_desert != (z > GetSnowLine())) {
1903 SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
1904 MarkTileDirtyByTile(tile);
1906 break;
1909 case LT_TROPIC:
1910 if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
1911 SetTunnelBridgeSnowOrDesert(tile, true);
1912 MarkTileDirtyByTile(tile);
1914 break;
1916 default:
1917 break;
1921 static bool ClickTile_TunnelBridge(TileIndex tile)
1923 /* Show vehicles found in tunnel. */
1924 if (IsTunnelTile(tile)) {
1925 int count = 0;
1926 const Train *t;
1927 TileIndex tile_end = GetOtherTunnelBridgeEnd(tile);
1928 FOR_ALL_TRAINS(t) {
1929 if (!t->IsFrontEngine()) continue;
1930 if (tile == t->tile || tile_end == t->tile) {
1931 ShowVehicleViewWindow(t);
1932 count++;
1934 if (count > 19) break; // no more than 20 windows open
1936 if (count > 0) return true;
1938 return false;
1941 extern const TrackBits _road_trackbits[16];
1943 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
1945 TransportType transport_type = GetTunnelBridgeTransportType(tile);
1947 if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
1949 DiagDirection dir = GetTunnelBridgeDirection(tile);
1951 if (mode == TRANSPORT_ROAD && IsRoadCustomBridgeHeadTile(tile)) {
1952 if (side != INVALID_DIAGDIR && side == dir) return 0;
1953 TrackBits bits = TRACK_BIT_NONE;
1954 if (sub_mode & ROADTYPES_TRAM) bits |= _road_trackbits[GetCustomBridgeHeadRoadBits(tile, ROADTYPE_TRAM)];
1955 if (sub_mode & ROADTYPES_ROAD) bits |= _road_trackbits[GetCustomBridgeHeadRoadBits(tile, ROADTYPE_ROAD)];
1956 return CombineTrackStatus(TrackBitsToTrackdirBits(bits), TRACKDIR_BIT_NONE);
1959 if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
1961 return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
1964 static void UpdateRoadTunnelBridgeInfrastructure(TileIndex begin, TileIndex end, bool add) {
1965 /* A full diagonal road has two road bits. */
1966 const uint middle_len = 2 * GetTunnelBridgeLength(begin, end) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1967 const uint len = middle_len + (4 * TUNNELBRIDGE_TRACKBIT_FACTOR);
1969 /* Iterate all present road types as each can have a different owner. */
1970 RoadType rt;
1971 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(begin)) {
1972 Company * const c = Company::GetIfValid(GetRoadOwner(begin, rt));
1973 if (c != nullptr) {
1974 uint infra = 0;
1975 if (IsBridge(begin)) {
1976 const RoadBits bits = GetCustomBridgeHeadRoadBits(begin, rt);
1977 infra += CountBits(bits) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1978 if (bits & DiagDirToRoadBits(GetTunnelBridgeDirection(begin))) {
1979 infra += middle_len;
1981 } else {
1982 infra += len;
1984 if (add) {
1985 c->infrastructure.road[rt] += infra;
1986 } else {
1987 c->infrastructure.road[rt] -= infra;
1991 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(end)) {
1992 Company * const c = Company::GetIfValid(GetRoadOwner(end, rt));
1993 if (c != nullptr) {
1994 uint infra = 0;
1995 if (IsBridge(end)) {
1996 const RoadBits bits = GetCustomBridgeHeadRoadBits(end, rt);
1997 infra += CountBits(bits) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1999 if (add) {
2000 c->infrastructure.road[rt] += infra;
2001 } else {
2002 c->infrastructure.road[rt] -= infra;
2008 void AddRoadTunnelBridgeInfrastructure(TileIndex begin, TileIndex end) {
2009 UpdateRoadTunnelBridgeInfrastructure(begin, end, true);
2012 void SubtractRoadTunnelBridgeInfrastructure(TileIndex begin, TileIndex end) {
2013 UpdateRoadTunnelBridgeInfrastructure(begin, end, false);
2016 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
2018 const TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
2019 /* Set number of pieces to zero if it's the southern tile as we
2020 * don't want to update the infrastructure counts twice. */
2021 const uint num_pieces = tile < other_end ? (GetTunnelBridgeLength(tile, other_end) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR : 0;
2022 const TransportType tt = GetTunnelBridgeTransportType(tile);
2024 if (tt == TRANSPORT_ROAD) SubtractRoadTunnelBridgeInfrastructure(tile, other_end);
2026 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
2027 /* Update all roadtypes, no matter if they are present */
2028 if (GetRoadOwner(tile, rt) == old_owner) {
2029 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
2033 if (tt == TRANSPORT_ROAD) AddRoadTunnelBridgeInfrastructure(tile, other_end);
2035 if (!IsTileOwner(tile, old_owner)) return;
2037 /* Update company infrastructure counts for rail and water as well.
2038 * No need to dirty windows here, we'll redraw the whole screen anyway. */
2039 Company *old = Company::Get(old_owner);
2040 if (tt == TRANSPORT_RAIL) {
2041 old->infrastructure.rail[GetRailType(tile)] -= num_pieces;
2042 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += num_pieces;
2043 } else if (tt == TRANSPORT_WATER) {
2044 old->infrastructure.water -= num_pieces;
2045 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.water += num_pieces;
2048 if (IsTunnelBridgeWithSignalSimulation(tile) && IsTunnelBridgeSignalSimulationEntrance(tile)) {
2049 uint num_sigs = GetTunnelBridgeSignalSimulationSignalCount(tile, other_end);
2050 Company::Get(old_owner)->infrastructure.signal -= num_sigs;
2051 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.signal += num_sigs;
2054 if (new_owner != INVALID_OWNER) {
2055 SetTileOwner(tile, new_owner);
2056 } else {
2057 if (tt == TRANSPORT_RAIL) {
2058 /* Since all of our vehicles have been removed, it is safe to remove the rail
2059 * bridge / tunnel. */
2060 CommandCost ret = DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
2061 assert(ret.Succeeded());
2062 } else {
2063 /* In any other case, we can safely reassign the ownership to OWNER_NONE. */
2064 SetTileOwner(tile, OWNER_NONE);
2070 * Frame when the 'enter tunnel' sound should be played. This is the second
2071 * frame on a tile, so the sound is played shortly after entering the tunnel
2072 * tile, while the vehicle is still visible.
2074 static const byte TUNNEL_SOUND_FRAME = 1;
2077 * Frame when a vehicle should be hidden in a tunnel with a certain direction.
2078 * This differs per direction, because of visibility / bounding box issues.
2079 * Note that direction, in this case, is the direction leading into the tunnel.
2080 * When entering a tunnel, hide the vehicle when it reaches the given frame.
2081 * When leaving a tunnel, show the vehicle when it is one frame further
2082 * to the 'outside', i.e. at (TILE_SIZE-1) - (frame) + 1
2084 extern const byte _tunnel_visibility_frame[DIAGDIR_END] = {12, 8, 8, 12};
2086 extern const byte _tunnel_turnaround_pre_visibility_frame[DIAGDIR_END] = { 31, 27, 27, 31 };
2088 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
2090 int z = GetSlopePixelZ(x, y) - v->z_pos;
2092 if (abs(z) > 2) return VETSB_CANNOT_ENTER;
2093 /* Direction into the wormhole */
2094 const DiagDirection dir = GetTunnelBridgeDirection(tile);
2095 /* Direction of the vehicle */
2096 const DiagDirection vdir = DirToDiagDir(v->direction);
2097 /* New position of the vehicle on the tile */
2098 byte pos = (DiagDirToAxis(vdir) == AXIS_X ? x : y) & TILE_UNIT_MASK;
2099 /* Number of units moved by the vehicle since entering the tile */
2100 byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2102 if (IsTunnel(tile)) {
2103 if (v->type == VEH_TRAIN) {
2104 Train *t = Train::From(v);
2106 if (t->track != TRACK_BIT_WORMHOLE && dir == vdir) {
2107 if (t->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
2108 if (!PlayVehicleSound(t, VSE_TUNNEL) && RailVehInfo(t->engine_type)->engclass == 0) {
2109 SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
2111 return VETSB_CONTINUE;
2113 if (frame == _tunnel_visibility_frame[dir]) {
2114 t->tile = tile;
2115 t->track = TRACK_BIT_WORMHOLE;
2116 if (Tunnel::GetByTile(tile)->is_chunnel) SetBit(t->gv_flags, GVF_CHUNNEL_BIT);
2117 t->vehstatus |= VS_HIDDEN;
2118 return VETSB_ENTERED_WORMHOLE;
2122 if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
2123 /* We're at the tunnel exit ?? */
2124 if (t->tile != tile && GetOtherTunnelEnd(t->tile) != tile) return VETSB_CONTINUE; // In chunnel
2125 t->tile = tile;
2126 t->track = DiagDirToDiagTrackBits(vdir);
2127 assert(t->track);
2128 t->vehstatus &= ~VS_HIDDEN;
2129 return VETSB_ENTERED_WORMHOLE;
2131 } else if (v->type == VEH_ROAD) {
2132 RoadVehicle *rv = RoadVehicle::From(v);
2134 /* Enter tunnel? */
2135 if (rv->state != RVSB_WORMHOLE && dir == vdir) {
2136 if (frame == _tunnel_visibility_frame[dir]) {
2137 /* Frame should be equal to the next frame number in the RV's movement */
2138 assert_msg(frame == rv->frame + 1 || rv->frame == _tunnel_turnaround_pre_visibility_frame[dir],
2139 +"frame: %u, rv->frame: %u, dir: %u, _tunnel_turnaround_pre_visibility_frame[dir]: %u", frame, rv->frame, dir, _tunnel_turnaround_pre_visibility_frame[dir]);
2140 rv->tile = tile;
2141 rv->state = RVSB_WORMHOLE;
2142 if (Tunnel::GetByTile(tile)->is_chunnel) SetBit(rv->gv_flags, GVF_CHUNNEL_BIT);
2143 rv->vehstatus |= VS_HIDDEN;
2144 return VETSB_ENTERED_WORMHOLE;
2145 } else {
2146 return VETSB_CONTINUE;
2150 /* We're at the tunnel exit ?? */
2151 if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
2152 if (rv->tile != tile && GetOtherTunnelEnd(rv->tile) != tile) return VETSB_CONTINUE; // In chunnel
2153 rv->tile = tile;
2154 rv->state = DiagDirToDiagTrackdir(vdir);
2155 rv->frame = frame;
2156 rv->vehstatus &= ~VS_HIDDEN;
2157 return VETSB_ENTERED_WORMHOLE;
2160 } else { // IsBridge(tile)
2161 if (v->vehstatus & VS_HIDDEN) return VETSB_CONTINUE; // Building bridges between chunnel portals allowed.
2162 if (v->type != VEH_SHIP) {
2163 /* modify speed of vehicle */
2164 uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
2166 if (v->type == VEH_ROAD) spd *= 2;
2167 Vehicle *first = v->First();
2168 first->cur_speed = min(first->cur_speed, spd);
2171 if (vdir == dir) {
2172 /* Vehicle enters bridge at the last frame inside this tile. */
2173 if (frame != TILE_SIZE - 1) return VETSB_CONTINUE;
2174 switch (v->type) {
2175 case VEH_TRAIN: {
2176 Train *t = Train::From(v);
2177 t->track = TRACK_BIT_WORMHOLE;
2178 ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
2179 ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
2180 break;
2183 case VEH_ROAD: {
2184 RoadVehicle *rv = RoadVehicle::From(v);
2185 if (IsRoadCustomBridgeHeadTile(tile)) {
2186 RoadBits bits = ROAD_NONE;
2187 if (rv->compatible_roadtypes & ROADTYPES_TRAM) bits |= GetCustomBridgeHeadRoadBits(tile, ROADTYPE_TRAM);
2188 if (rv->compatible_roadtypes & ROADTYPES_ROAD) bits |= GetCustomBridgeHeadRoadBits(tile, ROADTYPE_ROAD);
2189 if (!(bits & DiagDirToRoadBits(GetTunnelBridgeDirection(tile)))) return VETSB_CONTINUE;
2191 rv->state = RVSB_WORMHOLE;
2192 /* There are no slopes inside bridges / tunnels. */
2193 ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
2194 ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
2195 break;
2198 case VEH_SHIP:
2199 Ship::From(v)->state = TRACK_BIT_WORMHOLE;
2200 break;
2202 default: NOT_REACHED();
2204 return VETSB_ENTERED_WORMHOLE;
2205 } else if (vdir == ReverseDiagDir(dir)) {
2206 v->tile = tile;
2207 switch (v->type) {
2208 case VEH_TRAIN: {
2209 Train *t = Train::From(v);
2210 if (t->track == TRACK_BIT_WORMHOLE) {
2211 t->track = DiagDirToDiagTrackBits(vdir);
2212 return VETSB_ENTERED_WORMHOLE;
2214 break;
2217 case VEH_ROAD: {
2218 RoadVehicle *rv = RoadVehicle::From(v);
2219 if (rv->state == RVSB_WORMHOLE) {
2220 rv->state = DiagDirToDiagTrackdir(vdir);
2221 rv->frame = 0;
2222 return VETSB_ENTERED_WORMHOLE;
2224 break;
2227 case VEH_SHIP: {
2228 Ship *ship = Ship::From(v);
2229 if (ship->state == TRACK_BIT_WORMHOLE) {
2230 ship->state = DiagDirToDiagTrackBits(vdir);
2231 return VETSB_ENTERED_WORMHOLE;
2233 break;
2236 default: NOT_REACHED();
2240 return VETSB_CONTINUE;
2243 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
2245 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
2246 DiagDirection direction = GetTunnelBridgeDirection(tile);
2247 Axis axis = DiagDirToAxis(direction);
2248 CommandCost res;
2249 int z_old;
2250 Slope tileh_old = GetTileSlope(tile, &z_old);
2252 if (IsRoadCustomBridgeHeadTile(tile)) {
2253 const RoadBits pieces = GetCustomBridgeHeadAllRoadBits(tile);
2254 const RoadBits entrance_piece = DiagDirToRoadBits(direction);
2256 /* Steep slopes behave the same as slopes with one corner raised. */
2257 const Slope normalised_tileh_new = IsSteepSlope(tileh_new) ? SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh_new)) : tileh_new;
2259 if ((_invalid_tileh_slopes_road[0][normalised_tileh_new & SLOPE_ELEVATED] & (pieces & ~entrance_piece)) != ROAD_NONE) {
2260 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2264 /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
2265 if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
2266 CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
2267 res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
2268 } else {
2269 CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
2270 res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
2273 /* Surface slope is valid and remains unchanged? */
2274 if (res.Succeeded() && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2277 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2280 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
2281 DrawTile_TunnelBridge, // draw_tile_proc
2282 GetSlopePixelZ_TunnelBridge, // get_slope_z_proc
2283 ClearTile_TunnelBridge, // clear_tile_proc
2284 nullptr, // add_accepted_cargo_proc
2285 GetTileDesc_TunnelBridge, // get_tile_desc_proc
2286 GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
2287 ClickTile_TunnelBridge, // click_tile_proc
2288 nullptr, // animate_tile_proc
2289 TileLoop_TunnelBridge, // tile_loop_proc
2290 ChangeTileOwner_TunnelBridge, // change_tile_owner_proc
2291 nullptr, // add_produced_cargo_proc
2292 VehicleEnter_TunnelBridge, // vehicle_enter_tile_proc
2293 GetFoundation_TunnelBridge, // get_foundation_proc
2294 TerraformTile_TunnelBridge, // terraform_tile_proc