Fix some daylength issues, possible division by zero in main menu.
[openttd-joker.git] / src / tunnelbridge_cmd.cpp
blobe238e82cf5d51de64c8b38f11f09c49279410603
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 != NULL) {
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 == NULL || bridge->sprite_table[table] == NULL) {
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 CMD_ERROR;
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 CMD_ERROR;
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_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
249 if (bridge_type >= MAX_BRIDGES) return CMD_ERROR;
251 const BridgeSpec *b = GetBridgeSpec(bridge_type);
252 if (b->avail_year > _cur_year) return CMD_ERROR;
254 uint max = min(b->max_length, _settings_game.construction.max_bridge_length);
256 if (b->min_length > bridge_len) return CMD_ERROR;
257 if (bridge_len <= max) return CommandCost();
258 return_cmd_error(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_cmd_error(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 CMD_ERROR;
292 break;
294 case TRANSPORT_RAIL:
295 railtype = Extract<RailType, 8, 5>(p2);
296 if (!ValParamRailtype(railtype)) return CMD_ERROR;
297 break;
299 case TRANSPORT_WATER:
300 break;
302 default:
303 /* Airports don't have bridges. */
304 return CMD_ERROR;
306 TileIndex tile_start = p1;
307 TileIndex tile_end = end_tile;
309 if (company == OWNER_DEITY) {
310 if (transport_type != TRANSPORT_ROAD) return CMD_ERROR;
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 == NULL || 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_cmd_error(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_cmd_error(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_cmd_error(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_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
356 if (z_start != z_end) return_cmd_error(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_cmd_error(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 == NULL) {
379 return CMD_ERROR;
380 } else {
381 SetDParam(0, t->index);
382 return_cmd_error(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_cmd_error(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_cmd_error(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_cmd_error(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_cmd_error(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_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
447 if (z_start + 1 == GetBridgeHeight(north_head)) {
448 return_cmd_error(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_cmd_error(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_cmd_error(STR_ERROR_BRIDGE_TOO_HIGH_FOR_TERRAIN);
467 if (IsBridgeAbove(tile)) {
468 /* Disallow crossing bridges for the time being */
469 return_cmd_error(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 != NULL) 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 != NULL) {
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 != NULL) 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 != NULL && 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 != NULL) 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_cmd_error(STR_ERROR_CHUNNEL_ONLY_OVER_SEA);
646 const TileIndexDiff delta = TileOffsByDiagDir(direction);
647 for (;;) {
648 tile += delta;
649 if (!IsValidTile(tile)) return_cmd_error(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_cmd_error(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_cmd_error(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_cmd_error(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY);
682 tile += delta;
683 if (!IsValidTile(tile)) return_cmd_error(STR_ERROR_CHUNNEL_THROUGH_MAP_BORDER);
684 _build_tunnel_endtile = tile;
685 sea_tiles++;
687 if (!crossed_sea) return_cmd_error(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_cmd_error(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 CMD_ERROR;
728 break;
730 case TRANSPORT_ROAD:
731 rts = Extract<RoadTypes, 0, 2>(p1);
732 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(company, rts)) return CMD_ERROR;
733 break;
735 default: return CMD_ERROR;
738 if (company == OWNER_DEITY) {
739 if (transport_type != TRANSPORT_ROAD) return CMD_ERROR;
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 == NULL || 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_cmd_error(STR_ERROR_SITE_UNSUITABLE_FOR_TUNNEL);
756 if (HasTileWaterGround(start_tile)) return_cmd_error(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_cmd_error(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_cmd_error(STR_ERROR_TUNNEL_TOO_LONG);
827 if (HasTileWaterGround(end_tile)) return_cmd_error(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_cmd_error(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 == NULL) {
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_cmd_error(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_cmd_error(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 != NULL) 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 != NULL) {
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 = NULL;
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 = NULL;
991 if (HasTunnelBridgeReservation(tile)) {
992 v = GetTrainForReservation(tile, track);
993 if (v != NULL) 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 != NULL) 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 != NULL) {
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 = NULL;
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 = NULL;
1085 if (rail && HasTunnelBridgeReservation(tile)) {
1086 v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
1087 if (v != NULL) 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 != NULL) 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_cmd_error(STR_ERROR_MUST_DEMOLISH_TUNNEL_FIRST);
1146 return DoClearTunnel(tile, flags);
1147 } else { // IsBridge(tile)
1148 if (flags & DC_AUTO) return_cmd_error(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, NULL);
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);
1361 /* Draws a signal on tunnel / bridge entrance tile. */
1362 static void DrawBrigeSignalOnMiddlePart(const TileInfo *ti, TileIndex bridge_start_tile, uint z)
1365 uint bridge_signal_position = 0;
1366 int m2_position = 0;
1368 uint bridge_section = GetTunnelBridgeLength(ti->tile, bridge_start_tile) + 1;
1370 while (bridge_signal_position <= bridge_section) {
1371 bridge_signal_position += _settings_game.construction.simulated_wormhole_signals;
1372 if (bridge_signal_position == bridge_section) {
1373 bool side = (_settings_game.vehicle.road_side != 0) && _settings_game.construction.train_signal_side;
1375 static const Point SignalPositions[2][4] = {
1376 { /* X X Y Y Signals on the left side */
1377 {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
1378 }, {/* X X Y Y Signals on the right side */
1379 {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
1383 uint position;
1385 switch (GetTunnelBridgeDirection(bridge_start_tile)) {
1386 default: NOT_REACHED();
1387 case DIAGDIR_NE: position = 0; break;
1388 case DIAGDIR_SE: position = 2; break;
1389 case DIAGDIR_SW: position = 1; break;
1390 case DIAGDIR_NW: position = 3; break;
1393 uint x = TileX(ti->tile) * TILE_SIZE + SignalPositions[side][position].x;
1394 uint y = TileY(ti->tile) * TILE_SIZE + SignalPositions[side][position].y;
1395 z += 5;
1397 SignalVariant variant = IsTunnelBridgeSemaphore(bridge_start_tile) ? SIG_SEMAPHORE : SIG_ELECTRIC;
1399 SpriteID sprite = (GetBridgeEntranceSimulatedSignalState(bridge_start_tile, m2_position) == SIGNAL_STATE_GREEN);
1401 if (variant == SIG_ELECTRIC) {
1402 /* Normal electric signals are picked from original sprites. */
1403 sprite += SPR_ORIGINAL_SIGNALS_BASE + (position << 1);
1404 } else {
1405 /* All other signals are picked from add on sprites. */
1406 sprite += SPR_SIGNALS_BASE + (SIGTYPE_NORMAL - 1) * 16 + variant * 64 + (position << 1);
1409 AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, TILE_HEIGHT, z, false, 0, 0, BB_Z_SEPARATOR);
1411 m2_position++;
1416 * Draws a tunnel of bridge tile.
1417 * For tunnels, this is rather simple, as you only need to draw the entrance.
1418 * Bridges are a bit more complex. base_offset is where the sprite selection comes into play
1419 * and it works a bit like a bitmask.<p> For bridge heads:
1420 * @param ti TileInfo of the structure to draw
1421 * <ul><li>Bit 0: direction</li>
1422 * <li>Bit 1: northern or southern heads</li>
1423 * <li>Bit 2: Set if the bridge head is sloped</li>
1424 * <li>Bit 3 and more: Railtype Specific subset</li>
1425 * </ul>
1426 * Please note that in this code, "roads" are treated as railtype 1, whilst the real railtypes are 0, 2 and 3
1428 static void DrawTile_TunnelBridge(TileInfo *ti)
1430 TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
1431 DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
1433 if (IsTunnel(ti->tile)) {
1434 /* Front view of tunnel bounding boxes:
1436 * 122223 <- BB_Z_SEPARATOR
1437 * 1 3
1438 * 1 3 1,3 = empty helper BB
1439 * 1 3 2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
1443 static const int _tunnel_BB[4][12] = {
1444 /* tunnnel-roof | Z-separator | tram-catenary
1445 * w h bb_x bb_y| x y w h |bb_x bb_y w h */
1446 { 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // NE
1447 { 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // SE
1448 { 1, 0, -15, -14, 0, 15, 16, 1, 0, 1, 16, 15 }, // SW
1449 { 0, 1, -14, -15, 15, 0, 1, 16, 1, 0, 15, 16 }, // NW
1451 const int *BB_data = _tunnel_BB[tunnelbridge_direction];
1453 bool catenary = false;
1455 SpriteID image;
1456 SpriteID railtype_overlay = 0;
1457 if (transport_type == TRANSPORT_RAIL) {
1458 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1459 image = rti->base_sprites.tunnel;
1460 if (rti->UsesOverlay()) {
1461 /* Check if the railtype has custom tunnel portals. */
1462 railtype_overlay = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL_PORTAL);
1463 if (railtype_overlay != 0) image = SPR_RAILTYPE_TUNNEL_BASE; // Draw blank grass tunnel base.
1465 } else {
1466 image = SPR_TUNNEL_ENTRY_REAR_ROAD;
1469 if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += railtype_overlay != 0 ? 8 : 32;
1471 image += tunnelbridge_direction * 2;
1472 DrawGroundSprite(image, PAL_NONE);
1474 if (transport_type == TRANSPORT_ROAD) {
1475 RoadTypes rts = GetRoadTypes(ti->tile);
1477 if (HasBit(rts, ROADTYPE_TRAM)) {
1478 static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, { 5, 76, 77, 4 } };
1480 DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
1482 /* Do not draw wires if they are invisible */
1483 if (!IsInvisibilitySet(TO_CATENARY)) {
1484 catenary = true;
1485 StartSpriteCombine();
1486 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);
1489 } else {
1490 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1491 if (rti->UsesOverlay()) {
1492 SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL);
1493 if (surface != 0) DrawGroundSprite(surface + tunnelbridge_direction, PAL_NONE);
1496 DrawOverlay(ti, MP_TUNNELBRIDGE);
1498 /* PBS debugging, draw reserved tracks darker */
1499 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
1500 if (rti->UsesOverlay()) {
1501 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1502 DrawGroundSprite(overlay + RTO_X + DiagDirToAxis(tunnelbridge_direction), PALETTE_CRASH);
1503 } else {
1504 DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
1508 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) {
1509 /* Maybe draw pylons on the entry side */
1510 DrawRailCatenary(ti);
1512 catenary = true;
1513 StartSpriteCombine();
1514 /* Draw wire above the ramp */
1515 DrawRailCatenaryOnTunnel(ti);
1519 if (railtype_overlay != 0 && !catenary) StartSpriteCombine();
1521 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);
1522 /* Draw railtype tunnel portal overlay if defined. */
1523 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);
1525 if (catenary || railtype_overlay != 0) EndSpriteCombine();
1527 /* Add helper BB for sprite sorting that separates the tunnel from things beside of it. */
1528 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x, ti->y, BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
1529 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);
1531 /* Draw signals for tunnel. */
1532 if (IsTunnelBridgeWithSignalSimulation(ti->tile)) DrawTunnelBridgeRampSignal(ti);
1534 DrawBridgeMiddle(ti);
1535 } else { // IsBridge(ti->tile)
1536 if (transport_type == TRANSPORT_ROAD && IsRoadCustomBridgeHead(ti->tile)) {
1537 DrawRoadBits(ti);
1538 DrawBridgeMiddle(ti);
1539 return;
1542 const PalSpriteID *psid;
1543 int base_offset;
1544 bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
1546 if (transport_type == TRANSPORT_RAIL) {
1547 base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
1548 assert(base_offset != 8); // This one is used for roads
1549 } else {
1550 base_offset = 8;
1553 /* as the lower 3 bits are used for other stuff, make sure they are clear */
1554 assert( (base_offset & 0x07) == 0x00);
1556 DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
1558 /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
1559 base_offset += (6 - tunnelbridge_direction) % 4;
1561 /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
1562 if (transport_type != TRANSPORT_WATER) {
1563 if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
1564 psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
1565 } else {
1566 psid = _aqueduct_sprites + base_offset;
1569 if (!ice) {
1570 TileIndex next = ti->tile + TileOffsByDiagDir(tunnelbridge_direction);
1571 if (ti->tileh != SLOPE_FLAT && ti->z == 0 && HasTileWaterClass(next) && GetWaterClass(next) == WATER_CLASS_SEA) {
1572 DrawShoreTile(ti->tileh);
1573 } else {
1574 DrawClearLandTile(ti, 3);
1576 } else {
1577 DrawGroundSprite(SPR_FLAT_SNOW_DESERT_TILE + SlopeToSpriteOffset(ti->tileh), PAL_NONE);
1580 /* draw ramp */
1582 /* Draw Trambits and PBS Reservation as SpriteCombine */
1583 if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
1585 /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
1586 * it doesn't disappear behind it
1588 /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
1589 AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
1591 if (transport_type == TRANSPORT_ROAD) {
1592 RoadTypes rts = GetRoadTypes(ti->tile);
1594 if (HasBit(rts, ROADTYPE_TRAM)) {
1595 uint offset = tunnelbridge_direction;
1596 int z = ti->z;
1597 if (ti->tileh != SLOPE_FLAT) {
1598 offset = (offset + 1) & 1;
1599 z += TILE_HEIGHT;
1600 } else {
1601 offset += 2;
1603 /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
1604 DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
1606 EndSpriteCombine();
1607 } else if (transport_type == TRANSPORT_RAIL) {
1608 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1609 if (rti->UsesOverlay()) {
1610 SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_BRIDGE);
1611 if (surface != 0) {
1612 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1613 AddSortableSpriteToDraw(surface + ((DiagDirToAxis(tunnelbridge_direction) == AXIS_X) ? RTBO_X : RTBO_Y), PAL_NONE, ti->x, ti->y, 16, 16, 0, ti->z + 8);
1614 } else {
1615 AddSortableSpriteToDraw(surface + RTBO_SLOPE + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, 16, 16, 8, ti->z);
1618 /* Don't fallback to non-overlay sprite -- the spec states that
1619 * if an overlay is present then the bridge surface must be
1620 * present. */
1623 /* PBS debugging, draw reserved tracks darker */
1624 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
1625 if (rti->UsesOverlay()) {
1626 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1627 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1628 AddSortableSpriteToDraw(overlay + RTO_X + DiagDirToAxis(tunnelbridge_direction), PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 8);
1629 } else {
1630 AddSortableSpriteToDraw(overlay + RTO_SLOPE_NE + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
1632 } else {
1633 if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
1634 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);
1635 } else {
1636 AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
1641 EndSpriteCombine();
1642 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) {
1643 DrawRailCatenary(ti);
1647 /* Draw signals for bridge. */
1648 if (IsTunnelBridgeWithSignalSimulation(ti->tile)) DrawTunnelBridgeRampSignal(ti);
1650 DrawBridgeMiddle(ti);
1656 * Compute bridge piece. Computes the bridge piece to display depending on the position inside the bridge.
1657 * bridges pieces sequence (middle parts).
1658 * Note that it is not covering the bridge heads, which are always referenced by the same sprite table.
1659 * bridge len 1: BRIDGE_PIECE_NORTH
1660 * bridge len 2: BRIDGE_PIECE_NORTH BRIDGE_PIECE_SOUTH
1661 * bridge len 3: BRIDGE_PIECE_NORTH BRIDGE_PIECE_MIDDLE_ODD BRIDGE_PIECE_SOUTH
1662 * bridge len 4: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1663 * bridge len 5: BRIDGE_PIECE_NORTH BRIDGE_PIECE_INNER_NORTH BRIDGE_PIECE_MIDDLE_EVEN BRIDGE_PIECE_INNER_SOUTH BRIDGE_PIECE_SOUTH
1664 * 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
1665 * 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
1666 * #0 - always as first, #1 - always as last (if len>1)
1667 * #2,#3 are to pair in order
1668 * for odd bridges: #5 is going in the bridge middle if on even position, #4 on odd (counting from 0)
1669 * @param north Northernmost tile of bridge
1670 * @param south Southernmost tile of bridge
1671 * @return Index of bridge piece
1673 static BridgePieces CalcBridgePiece(uint north, uint south)
1675 if (north == 1) {
1676 return BRIDGE_PIECE_NORTH;
1677 } else if (south == 1) {
1678 return BRIDGE_PIECE_SOUTH;
1679 } else if (north < south) {
1680 return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
1681 } else if (north > south) {
1682 return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
1683 } else {
1684 return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
1689 * Draw the middle bits of a bridge.
1690 * @param ti Tile information of the tile to draw it on.
1692 void DrawBridgeMiddle(const TileInfo *ti)
1694 /* Sectional view of bridge bounding boxes:
1696 * 1 2 1,2 = SpriteCombine of Bridge front/(back&floor) and RoadCatenary
1697 * 1 2 3 = empty helper BB
1698 * 1 7 2 4,5 = pillars under higher bridges
1699 * 1 6 88888 6 2 6 = elrail-pylons
1700 * 1 6 88888 6 2 7 = elrail-wire
1701 * 1 6 88888 6 2 <- TILE_HEIGHT 8 = rail-vehicle on bridge
1702 * 3333333333333 <- BB_Z_SEPARATOR
1703 * <- unused
1704 * 4 5 <- BB_HEIGHT_UNDER_BRIDGE
1705 * 4 5
1706 * 4 5
1710 if (!IsBridgeAbove(ti->tile)) return;
1712 TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
1713 TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
1714 TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
1716 Axis axis = GetBridgeAxis(ti->tile);
1717 BridgePieces piece = CalcBridgePiece(
1718 GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
1719 GetTunnelBridgeLength(ti->tile, rampsouth) + 1
1722 const PalSpriteID *psid;
1723 bool drawfarpillar;
1724 if (transport_type != TRANSPORT_WATER) {
1725 BridgeType type = GetBridgeType(rampsouth);
1726 drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
1728 uint base_offset;
1729 if (transport_type == TRANSPORT_RAIL) {
1730 base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
1731 } else {
1732 base_offset = 8;
1735 psid = base_offset + GetBridgeSpriteTable(type, piece);
1736 } else {
1737 drawfarpillar = true;
1738 psid = _aqueduct_sprites;
1741 if (axis != AXIS_X) psid += 4;
1743 int x = ti->x;
1744 int y = ti->y;
1745 uint bridge_z = GetBridgePixelHeight(rampsouth);
1746 int z = bridge_z - BRIDGE_Z_START;
1748 /* Add a bounding box that separates the bridge from things below it. */
1749 AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
1751 /* Draw Trambits as SpriteCombine */
1752 if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
1754 /* Draw floor and far part of bridge*/
1755 if (!IsInvisibilitySet(TO_BRIDGES)) {
1756 if (axis == AXIS_X) {
1757 AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
1758 } else {
1759 AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
1763 psid++;
1765 if (transport_type == TRANSPORT_ROAD) {
1766 const RoadTypes rts = GetRoadTypes(rampsouth);
1768 bool has_tram = HasBit(rts, ROADTYPE_TRAM);
1769 bool has_road = HasBit(rts, ROADTYPE_ROAD);
1770 if (IsRoadCustomBridgeHeadTile(rampsouth)) {
1771 RoadBits entrance_bit = DiagDirToRoadBits(GetTunnelBridgeDirection(rampsouth));
1772 has_tram = has_tram && (GetCustomBridgeHeadRoadBits(rampsouth, ROADTYPE_TRAM) & entrance_bit);
1773 has_road = has_road && (GetCustomBridgeHeadRoadBits(rampsouth, ROADTYPE_ROAD) & entrance_bit);
1776 if (has_tram) {
1777 /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
1778 DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, has_road, false);
1779 } else {
1780 EndSpriteCombine();
1781 StartSpriteCombine();
1783 } else if (transport_type == TRANSPORT_RAIL) {
1784 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(rampsouth));
1785 if (rti->UsesOverlay() && !IsInvisibilitySet(TO_BRIDGES)) {
1786 SpriteID surface = GetCustomRailSprite(rti, rampsouth, RTSG_BRIDGE, TCX_ON_BRIDGE);
1787 if (surface != 0) {
1788 AddSortableSpriteToDraw(surface + axis, PAL_NONE, x, y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
1792 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && !IsInvisibilitySet(TO_BRIDGES) && HasTunnelBridgeReservation(rampnorth)
1793 && !IsTunnelBridgeWithSignalSimulation(rampnorth)) {
1794 if (rti->UsesOverlay()) {
1795 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
1796 AddSortableSpriteToDraw(overlay + RTO_X + axis, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
1797 } else {
1798 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));
1802 EndSpriteCombine();
1804 if (HasRailCatenaryDrawn(GetRailType(rampsouth))) {
1805 DrawRailCatenaryOnBridge(ti);
1809 /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
1810 if (!IsInvisibilitySet(TO_BRIDGES)) {
1811 if (axis == AXIS_X) {
1812 y += 12;
1813 if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
1814 } else {
1815 x += 12;
1816 if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
1820 /* Draw TramFront as SpriteCombine */
1821 if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
1823 /* Do not draw anything more if bridges are invisible */
1824 if (IsInvisibilitySet(TO_BRIDGES)) return;
1826 psid++;
1827 if (ti->z + 5 == z) {
1828 /* draw poles below for small bridges */
1829 if (psid->sprite != 0) {
1830 SpriteID image = psid->sprite;
1831 SpriteID pal = psid->pal;
1832 if (IsTransparencySet(TO_BRIDGES)) {
1833 SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
1834 pal = PALETTE_TO_TRANSPARENT;
1837 DrawGroundSpriteAt(image, pal, x - ti->x, y - ti->y, z - ti->z);
1839 } else {
1840 /* draw pillars below for high bridges */
1841 DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
1846 static int GetSlopePixelZ_TunnelBridge(TileIndex tile, uint x, uint y)
1848 int z;
1849 Slope tileh = GetTilePixelSlope(tile, &z);
1851 x &= 0xF;
1852 y &= 0xF;
1854 if (IsTunnel(tile)) {
1855 uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
1857 /* In the tunnel entrance? */
1858 if (5 <= pos && pos <= 10) return z;
1859 } else { // IsBridge(tile)
1860 if (IsRoadCustomBridgeHeadTile(tile)) {
1861 return z + TILE_HEIGHT + (IsSteepSlope(tileh) ? TILE_HEIGHT : 0);
1864 DiagDirection dir = GetTunnelBridgeDirection(tile);
1865 uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
1867 z += ApplyPixelFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
1869 /* On the bridge ramp? */
1870 if (5 <= pos && pos <= 10) {
1871 int delta;
1873 if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
1875 switch (dir) {
1876 default: NOT_REACHED();
1877 case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
1878 case DIAGDIR_SE: delta = y / 2; break;
1879 case DIAGDIR_SW: delta = x / 2; break;
1880 case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
1882 return z + 1 + delta;
1886 return z + GetPartialPixelZ(x, y, tileh);
1889 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
1891 if (IsRoadCustomBridgeHeadTile(tile)) return FOUNDATION_LEVELED;
1892 return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
1895 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
1897 TransportType tt = GetTunnelBridgeTransportType(tile);
1899 if (IsTunnel(tile)) {
1900 if (Tunnel::GetByTile(tile)->is_chunnel) {
1901 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;
1902 } else {
1903 td->str = (tt == TRANSPORT_RAIL) ? IsTunnelBridgeWithSignalSimulation(tile) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD_SIGNAL : STR_LAI_TUNNEL_DESCRIPTION_RAILROAD : STR_LAI_TUNNEL_DESCRIPTION_ROAD;
1905 } else { // IsBridge(tile)
1906 td->str = (tt == TRANSPORT_WATER) ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT : IsTunnelBridgeWithSignalSimulation(tile) ? STR_LAI_BRIDGE_DESCRIPTION_RAILROAD_SIGNAL : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
1908 td->owner[0] = GetTileOwner(tile);
1910 Owner road_owner = INVALID_OWNER;
1911 Owner tram_owner = INVALID_OWNER;
1912 RoadTypes rts = GetRoadTypes(tile);
1913 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
1914 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
1916 /* Is there a mix of owners? */
1917 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
1918 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
1919 uint i = 1;
1920 if (road_owner != INVALID_OWNER) {
1921 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
1922 td->owner[i] = road_owner;
1923 i++;
1925 if (tram_owner != INVALID_OWNER) {
1926 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
1927 td->owner[i] = tram_owner;
1931 if (tt == TRANSPORT_RAIL) {
1932 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
1933 td->rail_speed = rti->max_speed;
1934 td->railtype = rti->strings.name;
1936 if (!IsTunnel(tile)) {
1937 uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
1938 if (td->rail_speed == 0 || spd < td->rail_speed) {
1939 td->rail_speed = spd;
1942 } else if (tt == TRANSPORT_ROAD && !IsTunnel(tile)) {
1943 td->road_speed = GetBridgeSpec(GetBridgeType(tile))->speed;
1948 static void TileLoop_TunnelBridge(TileIndex tile)
1950 bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
1951 switch (_settings_game.game_creation.landscape) {
1952 case LT_ARCTIC: {
1953 /* As long as we do not have a snow density, we want to use the density
1954 * from the entry edge. */
1955 int z = GetTileMaxZ(tile);
1956 if (snow_or_desert != (z > GetSnowLine())) {
1957 SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
1958 MarkTileDirtyByTile(tile);
1960 break;
1963 case LT_TROPIC:
1964 if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
1965 SetTunnelBridgeSnowOrDesert(tile, true);
1966 MarkTileDirtyByTile(tile);
1968 break;
1970 default:
1971 break;
1975 static bool ClickTile_TunnelBridge(TileIndex tile)
1977 /* Show vehicles found in tunnel. */
1978 if (IsTunnelTile(tile)) {
1979 int count = 0;
1980 const Train *t;
1981 TileIndex tile_end = GetOtherTunnelBridgeEnd(tile);
1982 FOR_ALL_TRAINS(t) {
1983 if (!t->IsFrontEngine()) continue;
1984 if (tile == t->tile || tile_end == t->tile) {
1985 ShowVehicleViewWindow(t);
1986 count++;
1988 if (count > 19) break; // no more than 20 windows open
1990 if (count > 0) return true;
1992 return false;
1995 extern const TrackBits _road_trackbits[16];
1997 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
1999 TransportType transport_type = GetTunnelBridgeTransportType(tile);
2001 if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
2003 DiagDirection dir = GetTunnelBridgeDirection(tile);
2005 if (mode == TRANSPORT_ROAD && IsRoadCustomBridgeHeadTile(tile)) {
2006 if (side != INVALID_DIAGDIR && side == dir) return 0;
2007 TrackBits bits = TRACK_BIT_NONE;
2008 if (sub_mode & ROADTYPES_TRAM) bits |= _road_trackbits[GetCustomBridgeHeadRoadBits(tile, ROADTYPE_TRAM)];
2009 if (sub_mode & ROADTYPES_ROAD) bits |= _road_trackbits[GetCustomBridgeHeadRoadBits(tile, ROADTYPE_ROAD)];
2010 return CombineTrackStatus(TrackBitsToTrackdirBits(bits), TRACKDIR_BIT_NONE);
2013 if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
2015 return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
2018 static void UpdateRoadTunnelBridgeInfrastructure(TileIndex begin, TileIndex end, bool add) {
2019 /* A full diagonal road has two road bits. */
2020 const uint middle_len = 2 * GetTunnelBridgeLength(begin, end) * TUNNELBRIDGE_TRACKBIT_FACTOR;
2021 const uint len = middle_len + (4 * TUNNELBRIDGE_TRACKBIT_FACTOR);
2023 /* Iterate all present road types as each can have a different owner. */
2024 RoadType rt;
2025 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(begin)) {
2026 Company * const c = Company::GetIfValid(GetRoadOwner(begin, rt));
2027 if (c != NULL) {
2028 uint infra = 0;
2029 if (IsBridge(begin)) {
2030 const RoadBits bits = GetCustomBridgeHeadRoadBits(begin, rt);
2031 infra += CountBits(bits) * TUNNELBRIDGE_TRACKBIT_FACTOR;
2032 if (bits & DiagDirToRoadBits(GetTunnelBridgeDirection(begin))) {
2033 infra += middle_len;
2035 } else {
2036 infra += len;
2038 if (add) {
2039 c->infrastructure.road[rt] += infra;
2040 } else {
2041 c->infrastructure.road[rt] -= infra;
2045 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(end)) {
2046 Company * const c = Company::GetIfValid(GetRoadOwner(end, rt));
2047 if (c != NULL) {
2048 uint infra = 0;
2049 if (IsBridge(end)) {
2050 const RoadBits bits = GetCustomBridgeHeadRoadBits(end, rt);
2051 infra += CountBits(bits) * TUNNELBRIDGE_TRACKBIT_FACTOR;
2053 if (add) {
2054 c->infrastructure.road[rt] += infra;
2055 } else {
2056 c->infrastructure.road[rt] -= infra;
2062 void AddRoadTunnelBridgeInfrastructure(TileIndex begin, TileIndex end) {
2063 UpdateRoadTunnelBridgeInfrastructure(begin, end, true);
2066 void SubtractRoadTunnelBridgeInfrastructure(TileIndex begin, TileIndex end) {
2067 UpdateRoadTunnelBridgeInfrastructure(begin, end, false);
2070 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
2072 const TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
2073 /* Set number of pieces to zero if it's the southern tile as we
2074 * don't want to update the infrastructure counts twice. */
2075 const uint num_pieces = tile < other_end ? (GetTunnelBridgeLength(tile, other_end) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR : 0;
2076 const TransportType tt = GetTunnelBridgeTransportType(tile);
2078 if (tt == TRANSPORT_ROAD) SubtractRoadTunnelBridgeInfrastructure(tile, other_end);
2080 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
2081 /* Update all roadtypes, no matter if they are present */
2082 if (GetRoadOwner(tile, rt) == old_owner) {
2083 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
2087 if (tt == TRANSPORT_ROAD) AddRoadTunnelBridgeInfrastructure(tile, other_end);
2089 if (!IsTileOwner(tile, old_owner)) return;
2091 /* Update company infrastructure counts for rail and water as well.
2092 * No need to dirty windows here, we'll redraw the whole screen anyway. */
2093 Company *old = Company::Get(old_owner);
2094 if (tt == TRANSPORT_RAIL) {
2095 old->infrastructure.rail[GetRailType(tile)] -= num_pieces;
2096 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += num_pieces;
2097 } else if (tt == TRANSPORT_WATER) {
2098 old->infrastructure.water -= num_pieces;
2099 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.water += num_pieces;
2102 if (IsTunnelBridgeWithSignalSimulation(tile) && IsTunnelBridgeSignalSimulationEntrance(tile)) {
2103 uint num_sigs = GetTunnelBridgeSignalSimulationSignalCount(tile, other_end);
2104 Company::Get(old_owner)->infrastructure.signal -= num_sigs;
2105 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.signal += num_sigs;
2108 if (new_owner != INVALID_OWNER) {
2109 SetTileOwner(tile, new_owner);
2110 } else {
2111 if (tt == TRANSPORT_RAIL) {
2112 /* Since all of our vehicles have been removed, it is safe to remove the rail
2113 * bridge / tunnel. */
2114 CommandCost ret = DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
2115 assert(ret.Succeeded());
2116 } else {
2117 /* In any other case, we can safely reassign the ownership to OWNER_NONE. */
2118 SetTileOwner(tile, OWNER_NONE);
2124 * Frame when the 'enter tunnel' sound should be played. This is the second
2125 * frame on a tile, so the sound is played shortly after entering the tunnel
2126 * tile, while the vehicle is still visible.
2128 static const byte TUNNEL_SOUND_FRAME = 1;
2131 * Frame when a vehicle should be hidden in a tunnel with a certain direction.
2132 * This differs per direction, because of visibility / bounding box issues.
2133 * Note that direction, in this case, is the direction leading into the tunnel.
2134 * When entering a tunnel, hide the vehicle when it reaches the given frame.
2135 * When leaving a tunnel, show the vehicle when it is one frame further
2136 * to the 'outside', i.e. at (TILE_SIZE-1) - (frame) + 1
2138 extern const byte _tunnel_visibility_frame[DIAGDIR_END] = {12, 8, 8, 12};
2140 extern const byte _tunnel_turnaround_pre_visibility_frame[DIAGDIR_END] = { 31, 27, 27, 31 };
2142 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
2144 int z = GetSlopePixelZ(x, y) - v->z_pos;
2146 if (abs(z) > 2) return VETSB_CANNOT_ENTER;
2147 /* Direction into the wormhole */
2148 const DiagDirection dir = GetTunnelBridgeDirection(tile);
2149 /* Direction of the vehicle */
2150 const DiagDirection vdir = DirToDiagDir(v->direction);
2151 /* New position of the vehicle on the tile */
2152 byte pos = (DiagDirToAxis(vdir) == AXIS_X ? x : y) & TILE_UNIT_MASK;
2153 /* Number of units moved by the vehicle since entering the tile */
2154 byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2156 if (IsTunnel(tile)) {
2157 if (v->type == VEH_TRAIN) {
2158 Train *t = Train::From(v);
2160 if (t->track != TRACK_BIT_WORMHOLE && dir == vdir) {
2161 if (t->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
2162 if (!PlayVehicleSound(t, VSE_TUNNEL) && RailVehInfo(t->engine_type)->engclass == 0) {
2163 SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
2165 return VETSB_CONTINUE;
2167 if (frame == _tunnel_visibility_frame[dir]) {
2168 t->tile = tile;
2169 t->track = TRACK_BIT_WORMHOLE;
2170 if (Tunnel::GetByTile(tile)->is_chunnel) SetBit(t->gv_flags, GVF_CHUNNEL_BIT);
2171 t->vehstatus |= VS_HIDDEN;
2172 return VETSB_ENTERED_WORMHOLE;
2176 if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
2177 /* We're at the tunnel exit ?? */
2178 if (t->tile != tile && GetOtherTunnelEnd(t->tile) != tile) return VETSB_CONTINUE; // In chunnel
2179 t->tile = tile;
2180 t->track = DiagDirToDiagTrackBits(vdir);
2181 assert(t->track);
2182 t->vehstatus &= ~VS_HIDDEN;
2183 return VETSB_ENTERED_WORMHOLE;
2185 } else if (v->type == VEH_ROAD) {
2186 RoadVehicle *rv = RoadVehicle::From(v);
2188 /* Enter tunnel? */
2189 if (rv->state != RVSB_WORMHOLE && dir == vdir) {
2190 if (frame == _tunnel_visibility_frame[dir]) {
2191 /* Frame should be equal to the next frame number in the RV's movement */
2192 assert_msg(frame == rv->frame + 1 || rv->frame == _tunnel_turnaround_pre_visibility_frame[dir],
2193 +"frame: %u, rv->frame: %u, dir: %u, _tunnel_turnaround_pre_visibility_frame[dir]: %u", frame, rv->frame, dir, _tunnel_turnaround_pre_visibility_frame[dir]);
2194 rv->tile = tile;
2195 rv->state = RVSB_WORMHOLE;
2196 if (Tunnel::GetByTile(tile)->is_chunnel) SetBit(rv->gv_flags, GVF_CHUNNEL_BIT);
2197 rv->vehstatus |= VS_HIDDEN;
2198 return VETSB_ENTERED_WORMHOLE;
2199 } else {
2200 return VETSB_CONTINUE;
2204 /* We're at the tunnel exit ?? */
2205 if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
2206 if (rv->tile != tile && GetOtherTunnelEnd(rv->tile) != tile) return VETSB_CONTINUE; // In chunnel
2207 rv->tile = tile;
2208 rv->state = DiagDirToDiagTrackdir(vdir);
2209 rv->frame = frame;
2210 rv->vehstatus &= ~VS_HIDDEN;
2211 return VETSB_ENTERED_WORMHOLE;
2214 } else { // IsBridge(tile)
2215 if (v->vehstatus & VS_HIDDEN) return VETSB_CONTINUE; // Building bridges between chunnel portals allowed.
2216 if (v->type != VEH_SHIP) {
2217 /* modify speed of vehicle */
2218 uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
2220 if (v->type == VEH_ROAD) spd *= 2;
2221 Vehicle *first = v->First();
2222 first->cur_speed = min(first->cur_speed, spd);
2225 if (vdir == dir) {
2226 /* Vehicle enters bridge at the last frame inside this tile. */
2227 if (frame != TILE_SIZE - 1) return VETSB_CONTINUE;
2228 switch (v->type) {
2229 case VEH_TRAIN: {
2230 Train *t = Train::From(v);
2231 t->track = TRACK_BIT_WORMHOLE;
2232 ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
2233 ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
2234 break;
2237 case VEH_ROAD: {
2238 RoadVehicle *rv = RoadVehicle::From(v);
2239 if (IsRoadCustomBridgeHeadTile(tile)) {
2240 RoadBits bits = ROAD_NONE;
2241 if (rv->compatible_roadtypes & ROADTYPES_TRAM) bits |= GetCustomBridgeHeadRoadBits(tile, ROADTYPE_TRAM);
2242 if (rv->compatible_roadtypes & ROADTYPES_ROAD) bits |= GetCustomBridgeHeadRoadBits(tile, ROADTYPE_ROAD);
2243 if (!(bits & DiagDirToRoadBits(GetTunnelBridgeDirection(tile)))) return VETSB_CONTINUE;
2245 rv->state = RVSB_WORMHOLE;
2246 /* There are no slopes inside bridges / tunnels. */
2247 ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
2248 ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
2249 break;
2252 case VEH_SHIP:
2253 Ship::From(v)->state = TRACK_BIT_WORMHOLE;
2254 break;
2256 default: NOT_REACHED();
2258 return VETSB_ENTERED_WORMHOLE;
2259 } else if (vdir == ReverseDiagDir(dir)) {
2260 v->tile = tile;
2261 switch (v->type) {
2262 case VEH_TRAIN: {
2263 Train *t = Train::From(v);
2264 if (t->track == TRACK_BIT_WORMHOLE) {
2265 t->track = DiagDirToDiagTrackBits(vdir);
2266 return VETSB_ENTERED_WORMHOLE;
2268 break;
2271 case VEH_ROAD: {
2272 RoadVehicle *rv = RoadVehicle::From(v);
2273 if (rv->state == RVSB_WORMHOLE) {
2274 rv->state = DiagDirToDiagTrackdir(vdir);
2275 rv->frame = 0;
2276 return VETSB_ENTERED_WORMHOLE;
2278 break;
2281 case VEH_SHIP: {
2282 Ship *ship = Ship::From(v);
2283 if (ship->state == TRACK_BIT_WORMHOLE) {
2284 ship->state = DiagDirToDiagTrackBits(vdir);
2285 return VETSB_ENTERED_WORMHOLE;
2287 break;
2290 default: NOT_REACHED();
2294 return VETSB_CONTINUE;
2297 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
2299 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
2300 DiagDirection direction = GetTunnelBridgeDirection(tile);
2301 Axis axis = DiagDirToAxis(direction);
2302 CommandCost res;
2303 int z_old;
2304 Slope tileh_old = GetTileSlope(tile, &z_old);
2306 if (IsRoadCustomBridgeHeadTile(tile)) {
2307 const RoadBits pieces = GetCustomBridgeHeadAllRoadBits(tile);
2308 const RoadBits entrance_piece = DiagDirToRoadBits(direction);
2310 /* Steep slopes behave the same as slopes with one corner raised. */
2311 const Slope normalised_tileh_new = IsSteepSlope(tileh_new) ? SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh_new)) : tileh_new;
2313 if ((_invalid_tileh_slopes_road[0][normalised_tileh_new & SLOPE_ELEVATED] & (pieces & ~entrance_piece)) != ROAD_NONE) {
2314 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2318 /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
2319 if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
2320 CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
2321 res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
2322 } else {
2323 CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
2324 res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
2327 /* Surface slope is valid and remains unchanged? */
2328 if (res.Succeeded() && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2331 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2334 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
2335 DrawTile_TunnelBridge, // draw_tile_proc
2336 GetSlopePixelZ_TunnelBridge, // get_slope_z_proc
2337 ClearTile_TunnelBridge, // clear_tile_proc
2338 NULL, // add_accepted_cargo_proc
2339 GetTileDesc_TunnelBridge, // get_tile_desc_proc
2340 GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
2341 ClickTile_TunnelBridge, // click_tile_proc
2342 NULL, // animate_tile_proc
2343 TileLoop_TunnelBridge, // tile_loop_proc
2344 ChangeTileOwner_TunnelBridge, // change_tile_owner_proc
2345 NULL, // add_produced_cargo_proc
2346 VehicleEnter_TunnelBridge, // vehicle_enter_tile_proc
2347 GetFoundation_TunnelBridge, // get_foundation_proc
2348 TerraformTile_TunnelBridge, // terraform_tile_proc