tunnelbridge_cmd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00016 #include "stdafx.h"
00017 #include "newgrf_object.h"
00018 #include "viewport_func.h"
00019 #include "cmd_helper.h"
00020 #include "command_func.h"
00021 #include "town.h"
00022 #include "train.h"
00023 #include "ship.h"
00024 #include "roadveh.h"
00025 #include "water_map.h"
00026 #include "pathfinder/yapf/yapf_cache.h"
00027 #include "newgrf_sound.h"
00028 #include "autoslope.h"
00029 #include "tunnelbridge_map.h"
00030 #include "strings_func.h"
00031 #include "date_func.h"
00032 #include "clear_func.h"
00033 #include "vehicle_func.h"
00034 #include "sound_func.h"
00035 #include "tunnelbridge.h"
00036 #include "cheat_type.h"
00037 #include "elrail_func.h"
00038 #include "pbs.h"
00039 #include "company_base.h"
00040 #include "newgrf_railtype.h"
00041 #include "object_base.h"
00042 #include "water.h"
00043 
00044 #include "table/sprites.h"
00045 #include "table/strings.h"
00046 #include "table/bridge_land.h"
00047 
00048 BridgeSpec _bridge[MAX_BRIDGES]; 
00049 TileIndex _build_tunnel_endtile; 
00050 
00052 static const int BRIDGE_Z_START = 3;
00053 
00055 void ResetBridges()
00056 {
00057   /* First, free sprite table data */
00058   for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
00059     if (_bridge[i].sprite_table != NULL) {
00060       for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
00061       free(_bridge[i].sprite_table);
00062     }
00063   }
00064 
00065   /* Then, wipe out current bidges */
00066   memset(&_bridge, 0, sizeof(_bridge));
00067   /* And finally, reinstall default data */
00068   memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
00069 }
00070 
00077 int CalcBridgeLenCostFactor(int length)
00078 {
00079   if (length < 2) return length;
00080 
00081   length -= 2;
00082   int sum = 2;
00083   for (int delta = 1;; delta++) {
00084     for (int count = 0; count < delta; count++) {
00085       if (length == 0) return sum;
00086       sum += delta;
00087       length--;
00088     }
00089   }
00090 }
00091 
00098 Foundation GetBridgeFoundation(Slope tileh, Axis axis)
00099 {
00100   if (tileh == SLOPE_FLAT ||
00101       ((tileh == SLOPE_NE || tileh == SLOPE_SW) && axis == AXIS_X) ||
00102       ((tileh == SLOPE_NW || tileh == SLOPE_SE) && axis == AXIS_Y)) return FOUNDATION_NONE;
00103 
00104   return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
00105 }
00106 
00114 bool HasBridgeFlatRamp(Slope tileh, Axis axis)
00115 {
00116   ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
00117   /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
00118   return (tileh != SLOPE_FLAT);
00119 }
00120 
00121 static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
00122 {
00123   const BridgeSpec *bridge = GetBridgeSpec(index);
00124   assert(table < BRIDGE_PIECE_INVALID);
00125   if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
00126     return _bridge_sprite_table[index][table];
00127   } else {
00128     return bridge->sprite_table[table];
00129   }
00130 }
00131 
00132 
00141 static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, uint *z)
00142 {
00143   Foundation f = GetBridgeFoundation(*tileh, axis);
00144   *z += ApplyFoundationToSlope(f, tileh);
00145 
00146   Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
00147   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
00148 
00149   if (f == FOUNDATION_NONE) return CommandCost();
00150 
00151   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00152 }
00153 
00162 static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, uint *z)
00163 {
00164   Foundation f = GetBridgeFoundation(*tileh, axis);
00165   *z += ApplyFoundationToSlope(f, tileh);
00166 
00167   Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
00168   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
00169 
00170   if (f == FOUNDATION_NONE) return CommandCost();
00171 
00172   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00173 }
00174 
00181 CommandCost CheckBridgeAvailability(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
00182 {
00183   if (flags & DC_QUERY_COST) {
00184     if (bridge_len <= _settings_game.construction.max_bridge_length) return CommandCost();
00185     return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00186   }
00187 
00188   if (bridge_type >= MAX_BRIDGES) return CMD_ERROR;
00189 
00190   const BridgeSpec *b = GetBridgeSpec(bridge_type);
00191   if (b->avail_year > _cur_year) return CMD_ERROR;
00192 
00193   uint max = min(b->max_length, _settings_game.construction.max_bridge_length);
00194 
00195   if (b->min_length > bridge_len) return CMD_ERROR;
00196   if (bridge_len <= max) return CommandCost();
00197   return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00198 }
00199 
00212 CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00213 {
00214   RailType railtype = INVALID_RAILTYPE;
00215   RoadTypes roadtypes = ROADTYPES_NONE;
00216 
00217   /* unpack parameters */
00218   BridgeType bridge_type = GB(p2, 0, 8);
00219 
00220   if (!IsValidTile(p1)) return_cmd_error(STR_ERROR_BRIDGE_THROUGH_MAP_BORDER);
00221 
00222   TransportType transport_type = Extract<TransportType, 15, 2>(p2);
00223 
00224   /* type of bridge */
00225   switch (transport_type) {
00226     case TRANSPORT_ROAD:
00227       roadtypes = Extract<RoadTypes, 8, 2>(p2);
00228       if (!HasExactlyOneBit(roadtypes) || !HasRoadTypesAvail(_current_company, roadtypes)) return CMD_ERROR;
00229       break;
00230 
00231     case TRANSPORT_RAIL:
00232       railtype = Extract<RailType, 8, 4>(p2);
00233       if (!ValParamRailtype(railtype)) return CMD_ERROR;
00234       break;
00235 
00236     case TRANSPORT_WATER:
00237       break;
00238 
00239     default:
00240       /* Airports don't have bridges. */
00241       return CMD_ERROR;
00242   }
00243   TileIndex tile_start = p1;
00244   TileIndex tile_end = end_tile;
00245 
00246   if (tile_start == tile_end) {
00247     return_cmd_error(STR_ERROR_CAN_T_START_AND_END_ON);
00248   }
00249 
00250   Axis direction;
00251   if (TileX(tile_start) == TileX(tile_end)) {
00252     direction = AXIS_Y;
00253   } else if (TileY(tile_start) == TileY(tile_end)) {
00254     direction = AXIS_X;
00255   } else {
00256     return_cmd_error(STR_ERROR_START_AND_END_MUST_BE_IN);
00257   }
00258 
00259   if (tile_end < tile_start) Swap(tile_start, tile_end);
00260 
00261   uint bridge_len = GetTunnelBridgeLength(tile_start, tile_end);
00262   if (transport_type != TRANSPORT_WATER) {
00263     /* set and test bridge length, availability */
00264     CommandCost ret = CheckBridgeAvailability(bridge_type, bridge_len, flags);
00265     if (ret.Failed()) return ret;
00266   } else {
00267     if (bridge_len > _settings_game.construction.max_bridge_length) return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00268   }
00269 
00270   uint z_start;
00271   uint z_end;
00272   Slope tileh_start = GetTileSlope(tile_start, &z_start);
00273   Slope tileh_end = GetTileSlope(tile_end, &z_end);
00274   bool pbs_reservation = false;
00275 
00276   CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
00277   CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end,   &z_end);
00278 
00279   /* Aqueducts can't be built of flat land. */
00280   if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00281   if (z_start != z_end) return_cmd_error(STR_ERROR_BRIDGEHEADS_NOT_SAME_HEIGHT);
00282 
00283   CommandCost cost(EXPENSES_CONSTRUCTION);
00284   Owner owner;
00285   if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
00286       GetOtherBridgeEnd(tile_start) == tile_end &&
00287       GetTunnelBridgeTransportType(tile_start) == transport_type) {
00288     /* Replace a current bridge. */
00289 
00290     /* If this is a railway bridge, make sure the railtypes match. */
00291     if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
00292       return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00293     }
00294 
00295     /* Do not replace town bridges with lower speed bridges. */
00296     if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
00297         GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed) {
00298       Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
00299 
00300       if (t == NULL) {
00301         return CMD_ERROR;
00302       } else {
00303         SetDParam(0, t->index);
00304         return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00305       }
00306     }
00307 
00308     /* Do not replace the bridge with the same bridge type. */
00309     if (!(flags & DC_QUERY_COST) && bridge_type == GetBridgeType(tile_start)) {
00310       return_cmd_error(STR_ERROR_ALREADY_BUILT);
00311     }
00312 
00313     /* Do not allow replacing another company's bridges. */
00314     if (!IsTileOwner(tile_start, _current_company) && !IsTileOwner(tile_start, OWNER_TOWN)) {
00315       return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
00316     }
00317 
00318     cost.AddCost((bridge_len + 1) * _price[PR_CLEAR_BRIDGE]); // The cost of clearing the current bridge.
00319     owner = GetTileOwner(tile_start);
00320 
00321     switch (transport_type) {
00322       case TRANSPORT_RAIL:
00323         /* Keep the reservation, the path stays valid. */
00324         pbs_reservation = HasTunnelBridgeReservation(tile_start);
00325         break;
00326 
00327       case TRANSPORT_ROAD:
00328         /* Do not remove road types when upgrading a bridge */
00329         roadtypes |= GetRoadTypes(tile_start);
00330         break;
00331 
00332       default: break;
00333     }
00334   } else {
00335     /* Build a new bridge. */
00336 
00337     bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
00338 
00339     /* Try and clear the start landscape */
00340     CommandCost ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00341     if (ret.Failed()) return ret;
00342     cost = ret;
00343 
00344     if (terraform_cost_north.Failed() || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00345     cost.AddCost(terraform_cost_north);
00346 
00347     /* Try and clear the end landscape */
00348     ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00349     if (ret.Failed()) return ret;
00350     cost.AddCost(ret);
00351 
00352     /* false - end tile slope check */
00353     if (terraform_cost_south.Failed() || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00354     cost.AddCost(terraform_cost_south);
00355 
00356     const TileIndex heads[] = {tile_start, tile_end};
00357     for (int i = 0; i < 2; i++) {
00358       if (MayHaveBridgeAbove(heads[i])) {
00359         if (IsBridgeAbove(heads[i])) {
00360           TileIndex north_head = GetNorthernBridgeEnd(heads[i]);
00361 
00362           if (direction == GetBridgeAxis(heads[i])) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00363 
00364           if (z_start + TILE_HEIGHT == GetBridgeHeight(north_head)) {
00365             return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00366           }
00367         }
00368       }
00369     }
00370 
00371     TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00372     for (TileIndex tile = tile_start + delta; tile != tile_end; tile += delta) {
00373       if (GetTileMaxZ(tile) > z_start) return_cmd_error(STR_ERROR_BRIDGE_TOO_LOW_FOR_TERRAIN);
00374 
00375       if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00376         /* Disallow crossing bridges for the time being */
00377         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00378       }
00379 
00380       switch (GetTileType(tile)) {
00381         case MP_WATER:
00382           if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
00383           break;
00384 
00385         case MP_RAILWAY:
00386           if (!IsPlainRail(tile)) goto not_valid_below;
00387           break;
00388 
00389         case MP_ROAD:
00390           if (IsRoadDepot(tile)) goto not_valid_below;
00391           break;
00392 
00393         case MP_TUNNELBRIDGE:
00394           if (IsTunnel(tile)) break;
00395           if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
00396           if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
00397           break;
00398 
00399         case MP_OBJECT: {
00400           const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
00401           if ((spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) == 0) goto not_valid_below;
00402           if (GetTileMaxZ(tile) + spec->height * TILE_HEIGHT > z_start) goto not_valid_below;
00403           break;
00404         }
00405 
00406         case MP_CLEAR:
00407           break;
00408 
00409         default:
00410   not_valid_below:;
00411           /* try and clear the middle landscape */
00412           ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00413           if (ret.Failed()) return ret;
00414           cost.AddCost(ret);
00415           break;
00416       }
00417 
00418       if (flags & DC_EXEC) {
00419         /* We do this here because when replacing a bridge with another
00420          * type calling SetBridgeMiddle isn't needed. After all, the
00421          * tile alread has the has_bridge_above bits set. */
00422         SetBridgeMiddle(tile, direction);
00423       }
00424     }
00425 
00426     owner = _current_company;
00427   }
00428 
00429   /* do the drill? */
00430   if (flags & DC_EXEC) {
00431     DiagDirection dir = AxisToDiagDir(direction);
00432 
00433     switch (transport_type) {
00434       case TRANSPORT_RAIL:
00435         MakeRailBridgeRamp(tile_start, owner, bridge_type, dir,                 railtype);
00436         MakeRailBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), railtype);
00437         SetTunnelBridgeReservation(tile_start, pbs_reservation);
00438         SetTunnelBridgeReservation(tile_end,   pbs_reservation);
00439         break;
00440 
00441       case TRANSPORT_ROAD:
00442         MakeRoadBridgeRamp(tile_start, owner, bridge_type, dir,                 roadtypes);
00443         MakeRoadBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), roadtypes);
00444         break;
00445 
00446       case TRANSPORT_WATER:
00447         MakeAqueductBridgeRamp(tile_start, owner, dir);
00448         MakeAqueductBridgeRamp(tile_end,   owner, ReverseDiagDir(dir));
00449         break;
00450 
00451       default:
00452         NOT_REACHED();
00453     }
00454 
00455     /* Mark all tiles dirty */
00456     TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00457     for (TileIndex tile = tile_start; tile <= tile_end; tile += delta) {
00458       MarkTileDirtyByTile(tile);
00459     }
00460   }
00461 
00462   if ((flags & DC_EXEC) && transport_type == TRANSPORT_RAIL) {
00463     Track track = AxisToTrack(direction);
00464     AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, _current_company);
00465     YapfNotifyTrackLayoutChange(tile_start, track);
00466   }
00467 
00468   /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
00469    * It's unnecessary to execute this command every time for every bridge. So it is done only
00470    * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
00471    */
00472   Company *c = Company::GetIfValid(_current_company);
00473   if (!(flags & DC_QUERY_COST) || (c != NULL && c->is_ai)) {
00474     bridge_len += 2; // begin and end tiles/ramps
00475 
00476     switch (transport_type) {
00477       case TRANSPORT_ROAD: cost.AddCost(bridge_len * _price[PR_BUILD_ROAD] * 2); break;
00478       case TRANSPORT_RAIL: cost.AddCost(bridge_len * RailBuildCost(railtype)); break;
00479       default: break;
00480     }
00481 
00482     if (c != NULL) bridge_len = CalcBridgeLenCostFactor(bridge_len);
00483 
00484     if (transport_type != TRANSPORT_WATER) {
00485       cost.AddCost((int64)bridge_len * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8);
00486     } else {
00487       /* Aqueducts use a separate base cost. */
00488       cost.AddCost((int64)bridge_len * _price[PR_BUILD_AQUEDUCT]);
00489     }
00490 
00491   }
00492 
00493   return cost;
00494 }
00495 
00496 
00507 CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00508 {
00509   TransportType transport_type = Extract<TransportType, 8, 2>(p1);
00510 
00511   RailType railtype = INVALID_RAILTYPE;
00512   RoadTypes rts = ROADTYPES_NONE;
00513   _build_tunnel_endtile = 0;
00514   switch (transport_type) {
00515     case TRANSPORT_RAIL:
00516       railtype = Extract<RailType, 0, 4>(p1);
00517       if (!ValParamRailtype(railtype)) return CMD_ERROR;
00518       break;
00519 
00520     case TRANSPORT_ROAD:
00521       rts = Extract<RoadTypes, 0, 2>(p1);
00522       if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
00523       break;
00524 
00525     default: return CMD_ERROR;
00526   }
00527 
00528   uint start_z;
00529   uint end_z;
00530   Slope start_tileh = GetTileSlope(start_tile, &start_z);
00531   DiagDirection direction = GetInclinedSlopeDirection(start_tileh);
00532   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE_FOR_TUNNEL);
00533 
00534   if (HasTileWaterGround(start_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00535 
00536   CommandCost ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00537   if (ret.Failed()) return ret;
00538 
00539   /* XXX - do NOT change 'ret' in the loop, as it is used as the price
00540    * for the clearing of the entrance of the tunnel. Assigning it to
00541    * cost before the loop will yield different costs depending on start-
00542    * position, because of increased-cost-by-length: 'cost += cost >> 3' */
00543 
00544   TileIndexDiff delta = TileOffsByDiagDir(direction);
00545   DiagDirection tunnel_in_way_dir;
00546   if (DiagDirToAxis(direction) == AXIS_Y) {
00547     tunnel_in_way_dir = (TileX(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SW : DIAGDIR_NE;
00548   } else {
00549     tunnel_in_way_dir = (TileY(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SE : DIAGDIR_NW;
00550   }
00551 
00552   TileIndex end_tile = start_tile;
00553 
00554   /* Tile shift coeficient. Will decrease for very long tunnels to avoid exponential growth of price*/
00555   int tiles_coef = 3;
00556   /* Number of tiles from start of tunnel */
00557   int tiles = 0;
00558   /* Number of tiles at which the cost increase coefficient per tile is halved */
00559   int tiles_bump = 25;
00560 
00561   CommandCost cost(EXPENSES_CONSTRUCTION);
00562   Slope end_tileh;
00563   for (;;) {
00564     end_tile += delta;
00565     if (!IsValidTile(end_tile)) return_cmd_error(STR_ERROR_TUNNEL_THROUGH_MAP_BORDER);
00566     end_tileh = GetTileSlope(end_tile, &end_z);
00567 
00568     if (start_z == end_z) break;
00569 
00570     if (!_cheats.crossing_tunnels.value && IsTunnelInWayDir(end_tile, start_z, tunnel_in_way_dir)) {
00571       return_cmd_error(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY);
00572     }
00573 
00574     tiles++;
00575     if (tiles == tiles_bump) {
00576       tiles_coef++;
00577       tiles_bump *= 2;
00578     }
00579 
00580     cost.AddCost(_price[PR_BUILD_TUNNEL]);
00581     cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
00582   }
00583 
00584   /* Add the cost of the entrance */
00585   cost.AddCost(_price[PR_BUILD_TUNNEL]);
00586   cost.AddCost(ret);
00587 
00588   /* if the command fails from here on we want the end tile to be highlighted */
00589   _build_tunnel_endtile = end_tile;
00590 
00591   if (tiles > _settings_game.construction.max_tunnel_length) return_cmd_error(STR_ERROR_TUNNEL_TOO_LONG);
00592 
00593   if (HasTileWaterGround(end_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00594 
00595   /* Clear the tile in any case */
00596   ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00597   if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
00598   cost.AddCost(ret);
00599 
00600   /* slope of end tile must be complementary to the slope of the start tile */
00601   if (end_tileh != ComplementSlope(start_tileh)) {
00602     /* Mark the tile as already cleared for the terraform command.
00603      * Do this for all tiles (like trees), not only objects. */
00604     ClearedObjectArea *coa = FindClearedObject(end_tile);
00605     if (coa == NULL) {
00606       coa = _cleared_object_areas.Append();
00607       coa->first_tile = end_tile;
00608       coa->area = TileArea(end_tile, 1, 1);
00609     }
00610 
00611     /* Hide the tile from the terraforming command */
00612     TileIndex old_first_tile = coa->first_tile;
00613     coa->first_tile = INVALID_TILE;
00614     ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
00615     coa->first_tile = old_first_tile;
00616     if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
00617     cost.AddCost(ret);
00618   }
00619   cost.AddCost(_price[PR_BUILD_TUNNEL]);
00620 
00621   /* Pay for the rail/road in the tunnel including entrances */
00622   switch (transport_type) {
00623     case TRANSPORT_ROAD: cost.AddCost((tiles + 2) * _price[PR_BUILD_ROAD] * 2); break;
00624     case TRANSPORT_RAIL: cost.AddCost((tiles + 2) * RailBuildCost(railtype)); break;
00625     default: break;
00626   }
00627 
00628   if (flags & DC_EXEC) {
00629     if (transport_type == TRANSPORT_RAIL) {
00630       MakeRailTunnel(start_tile, _current_company, direction,                 railtype);
00631       MakeRailTunnel(end_tile,   _current_company, ReverseDiagDir(direction), railtype);
00632       AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, _current_company);
00633       YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
00634     } else {
00635       MakeRoadTunnel(start_tile, _current_company, direction,                 rts);
00636       MakeRoadTunnel(end_tile,   _current_company, ReverseDiagDir(direction), rts);
00637     }
00638   }
00639 
00640   return cost;
00641 }
00642 
00643 
00649 static inline CommandCost CheckAllowRemoveTunnelBridge(TileIndex tile)
00650 {
00651   /* Floods can remove anything as well as the scenario editor */
00652   if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return CommandCost();
00653 
00654   switch (GetTunnelBridgeTransportType(tile)) {
00655     case TRANSPORT_ROAD: {
00656       RoadTypes rts = GetRoadTypes(tile);
00657       Owner road_owner = _current_company;
00658       Owner tram_owner = _current_company;
00659 
00660       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
00661       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
00662 
00663       /* We can remove unowned road and if the town allows it */
00664       if (road_owner == OWNER_TOWN && !(_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) {
00665         return CheckTileOwnership(tile);
00666       }
00667       if (road_owner == OWNER_NONE || road_owner == OWNER_TOWN) road_owner = _current_company;
00668       if (tram_owner == OWNER_NONE) tram_owner = _current_company;
00669 
00670       CommandCost ret = CheckOwnership(road_owner, tile);
00671       if (ret.Succeeded()) ret = CheckOwnership(tram_owner, tile);
00672       return ret;
00673     }
00674 
00675     case TRANSPORT_RAIL:
00676     case TRANSPORT_WATER:
00677       return CheckOwnership(GetTileOwner(tile));
00678 
00679     default: NOT_REACHED();
00680   }
00681 }
00682 
00689 static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
00690 {
00691   CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
00692   if (ret.Failed()) return ret;
00693 
00694   TileIndex endtile = GetOtherTunnelEnd(tile);
00695 
00696   ret = TunnelBridgeIsFree(tile, endtile);
00697   if (ret.Failed()) return ret;
00698 
00699   _build_tunnel_endtile = endtile;
00700 
00701   Town *t = NULL;
00702   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00703     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
00704 
00705     /* Check if you are allowed to remove the tunnel owned by a town
00706      * Removal depends on difficulty settings */
00707     CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
00708     if (ret.Failed()) return ret;
00709   }
00710 
00711   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
00712    * you have a "Poor" (0) town rating */
00713   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00714     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
00715   }
00716 
00717   if (flags & DC_EXEC) {
00718     if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
00719       /* We first need to request values before calling DoClearSquare */
00720       DiagDirection dir = GetTunnelBridgeDirection(tile);
00721       Track track = DiagDirToDiagTrack(dir);
00722       Owner owner = GetTileOwner(tile);
00723 
00724       Train *v = NULL;
00725       if (HasTunnelBridgeReservation(tile)) {
00726         v = GetTrainForReservation(tile, track);
00727         if (v != NULL) FreeTrainTrackReservation(v);
00728       }
00729 
00730       DoClearSquare(tile);
00731       DoClearSquare(endtile);
00732 
00733       /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
00734       AddSideToSignalBuffer(tile,    ReverseDiagDir(dir), owner);
00735       AddSideToSignalBuffer(endtile, dir,                 owner);
00736 
00737       YapfNotifyTrackLayoutChange(tile,    track);
00738       YapfNotifyTrackLayoutChange(endtile, track);
00739 
00740       if (v != NULL) TryPathReserve(v);
00741     } else {
00742       DoClearSquare(tile);
00743       DoClearSquare(endtile);
00744     }
00745   }
00746   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_TUNNEL] * (GetTunnelBridgeLength(tile, endtile) + 2));
00747 }
00748 
00749 
00756 static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
00757 {
00758   CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
00759   if (ret.Failed()) return ret;
00760 
00761   TileIndex endtile = GetOtherBridgeEnd(tile);
00762 
00763   ret = TunnelBridgeIsFree(tile, endtile);
00764   if (ret.Failed()) return ret;
00765 
00766   DiagDirection direction = GetTunnelBridgeDirection(tile);
00767   TileIndexDiff delta = TileOffsByDiagDir(direction);
00768 
00769   Town *t = NULL;
00770   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00771     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
00772 
00773     /* Check if you are allowed to remove the bridge owned by a town
00774      * Removal depends on difficulty settings */
00775     CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
00776     if (ret.Failed()) return ret;
00777   }
00778 
00779   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
00780    * you have a "Poor" (0) town rating */
00781   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00782     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
00783   }
00784 
00785   Money base_cost = (GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) ? _price[PR_CLEAR_BRIDGE] : _price[PR_CLEAR_AQUEDUCT];
00786 
00787   if (flags & DC_EXEC) {
00788     /* read this value before actual removal of bridge */
00789     bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
00790     Owner owner = GetTileOwner(tile);
00791     uint height = GetBridgeHeight(tile);
00792     Train *v = NULL;
00793 
00794     if (rail && HasTunnelBridgeReservation(tile)) {
00795       v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
00796       if (v != NULL) FreeTrainTrackReservation(v);
00797     }
00798 
00799     DoClearSquare(tile);
00800     DoClearSquare(endtile);
00801     for (TileIndex c = tile + delta; c != endtile; c += delta) {
00802       /* do not let trees appear from 'nowhere' after removing bridge */
00803       if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
00804         uint minz = GetTileMaxZ(c) + 3 * TILE_HEIGHT;
00805         if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
00806       }
00807       ClearBridgeMiddle(c);
00808       MarkTileDirtyByTile(c);
00809     }
00810 
00811     if (rail) {
00812       /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
00813       AddSideToSignalBuffer(tile,    ReverseDiagDir(direction), owner);
00814       AddSideToSignalBuffer(endtile, direction,                 owner);
00815 
00816       Track track = DiagDirToDiagTrack(direction);
00817       YapfNotifyTrackLayoutChange(tile,    track);
00818       YapfNotifyTrackLayoutChange(endtile, track);
00819 
00820       if (v != NULL) TryPathReserve(v, true);
00821     }
00822   }
00823 
00824   return CommandCost(EXPENSES_CONSTRUCTION, (GetTunnelBridgeLength(tile, endtile) + 2) * base_cost);
00825 }
00826 
00833 static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
00834 {
00835   if (IsTunnel(tile)) {
00836     if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_TUNNEL_FIRST);
00837     return DoClearTunnel(tile, flags);
00838   } else { // IsBridge(tile)
00839     if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00840     return DoClearBridge(tile, flags);
00841   }
00842 }
00843 
00854 static inline void DrawPillar(const PalSpriteID *psid, int x, int y, int z, int w, int h, const SubSprite *subsprite)
00855 {
00856   static const int PILLAR_Z_OFFSET = TILE_HEIGHT - BRIDGE_Z_START; 
00857   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);
00858 }
00859 
00871 static int DrawPillarColumn(int z_bottom, int z_top, const PalSpriteID *psid, int x, int y, int w, int h)
00872 {
00873   int cur_z;
00874   for (cur_z = z_top; cur_z >= z_bottom; cur_z -= TILE_HEIGHT) {
00875     DrawPillar(psid, x, y, cur_z, w, h, NULL);
00876   }
00877   return cur_z;
00878 }
00879 
00891 static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
00892 {
00893   static const int bounding_box_size[2]  = {16, 2}; 
00894   static const int back_pillar_offset[2] = { 0, 9}; 
00895 
00896   static const int INF = 1000; 
00897   static const SubSprite half_pillar_sub_sprite[2][2] = {
00898     { {  -14, -INF, INF, INF }, { -INF, -INF, -15, INF } }, // X axis, north and south
00899     { { -INF, -INF,  15, INF }, {   16, -INF, INF, INF } }, // Y axis, north and south
00900   };
00901 
00902   if (psid->sprite == 0) return;
00903 
00904   /* Determine ground height under pillars */
00905   DiagDirection south_dir = AxisToDiagDir(axis);
00906   int z_front_north = ti->z;
00907   int z_back_north = ti->z;
00908   int z_front_south = ti->z;
00909   int z_back_south = ti->z;
00910   GetSlopeZOnEdge(ti->tileh, south_dir, &z_front_south, &z_back_south);
00911   GetSlopeZOnEdge(ti->tileh, ReverseDiagDir(south_dir), &z_front_north, &z_back_north);
00912 
00913   /* Shared height of pillars */
00914   int z_front = max(z_front_north, z_front_south);
00915   int z_back = max(z_back_north, z_back_south);
00916 
00917   /* x and y size of bounding-box of pillars */
00918   int w = bounding_box_size[axis];
00919   int h = bounding_box_size[OtherAxis(axis)];
00920   /* sprite position of back facing pillar */
00921   int x_back = x - back_pillar_offset[axis];
00922   int y_back = y - back_pillar_offset[OtherAxis(axis)];
00923 
00924   /* Draw front pillars */
00925   int bottom_z = DrawPillarColumn(z_front, z_bridge, psid, x, y, w, h);
00926   if (z_front_north < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
00927   if (z_front_south < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
00928 
00929   /* Draw back pillars, skip top two parts, which are hidden by the bridge */
00930   int z_bridge_back = z_bridge - 2 * (int)TILE_HEIGHT;
00931   if (drawfarpillar && (z_back_north <= z_bridge_back || z_back_south <= z_bridge_back)) {
00932     bottom_z = DrawPillarColumn(z_back, z_bridge_back, psid, x_back, y_back, w, h);
00933     if (z_back_north < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
00934     if (z_back_south < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
00935   }
00936 }
00937 
00947 static void DrawBridgeTramBits(int x, int y, byte z, int offset, bool overlay, bool head)
00948 {
00949   static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
00950   static const SpriteID back_offsets[6]    =   {  95,  96,  99, 102, 100, 101 };
00951   static const SpriteID front_offsets[6]   =   {  97,  98, 103, 106, 104, 105 };
00952 
00953   static const uint size_x[6] = {  1, 16, 16,  1, 16,  1 };
00954   static const uint size_y[6] = { 16,  1,  1, 16,  1, 16 };
00955   static const uint front_bb_offset_x[6] = { 15,  0,  0, 15,  0, 15 };
00956   static const uint front_bb_offset_y[6] = {  0, 15, 15,  0, 15,  0 };
00957 
00958   /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
00959    * The bounding boxes here are the same as for bridge front/roof */
00960   if (head || !IsInvisibilitySet(TO_BRIDGES)) {
00961     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
00962       x, y, size_x[offset], size_y[offset], 0x28, z,
00963       !head && IsTransparencySet(TO_BRIDGES));
00964   }
00965 
00966   /* Do not draw catenary if it is set invisible */
00967   if (!IsInvisibilitySet(TO_CATENARY)) {
00968     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
00969       x, y, size_x[offset], size_y[offset], 0x28, z,
00970       IsTransparencySet(TO_CATENARY));
00971   }
00972 
00973   /* Start a new SpriteCombine for the front part */
00974   EndSpriteCombine();
00975   StartSpriteCombine();
00976 
00977   /* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
00978   if (!IsInvisibilitySet(TO_CATENARY)) {
00979     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
00980       x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
00981       IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
00982   }
00983 }
00984 
00998 static void DrawTile_TunnelBridge(TileInfo *ti)
00999 {
01000   TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
01001   DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
01002 
01003   if (IsTunnel(ti->tile)) {
01004     /* Front view of tunnel bounding boxes:
01005      *
01006      *   122223  <- BB_Z_SEPARATOR
01007      *   1    3
01008      *   1    3                1,3 = empty helper BB
01009      *   1    3                  2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
01010      *
01011      */
01012 
01013     static const int _tunnel_BB[4][12] = {
01014       /*  tunnnel-roof  |  Z-separator  | tram-catenary
01015        * w  h  bb_x bb_y| x   y   w   h |bb_x bb_y w h */
01016       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // NE
01017       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // SE
01018       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // SW
01019       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // NW
01020     };
01021     const int *BB_data = _tunnel_BB[tunnelbridge_direction];
01022 
01023     bool catenary = false;
01024 
01025     SpriteID image;
01026     if (transport_type == TRANSPORT_RAIL) {
01027       image = GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.tunnel;
01028     } else {
01029       image = SPR_TUNNEL_ENTRY_REAR_ROAD;
01030     }
01031 
01032     if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += 32;
01033 
01034     image += tunnelbridge_direction * 2;
01035     DrawGroundSprite(image, PAL_NONE);
01036 
01037     /* PBS debugging, draw reserved tracks darker */
01038     if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && (transport_type == TRANSPORT_RAIL && HasTunnelBridgeReservation(ti->tile))) {
01039       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01040       DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
01041     }
01042 
01043     if (transport_type == TRANSPORT_ROAD) {
01044       RoadTypes rts = GetRoadTypes(ti->tile);
01045 
01046       if (HasBit(rts, ROADTYPE_TRAM)) {
01047         static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, {  5, 76, 77,  4 } };
01048 
01049         DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
01050 
01051         /* Do not draw wires if they are invisible */
01052         if (!IsInvisibilitySet(TO_CATENARY)) {
01053           catenary = true;
01054           StartSpriteCombine();
01055           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);
01056         }
01057       }
01058     } else {
01059       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01060       if (rti->UsesOverlay()) {
01061         SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL);
01062         if (surface != 0) DrawGroundSprite(surface + tunnelbridge_direction, PAL_NONE);
01063       }
01064 
01065       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
01066         /* Maybe draw pylons on the entry side */
01067         DrawCatenary(ti);
01068 
01069         catenary = true;
01070         StartSpriteCombine();
01071         /* Draw wire above the ramp */
01072         DrawCatenaryOnTunnel(ti);
01073       }
01074     }
01075 
01076     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);
01077 
01078     if (catenary) EndSpriteCombine();
01079 
01080     /* Add helper BB for sprite sorting that separates the tunnel from things beside of it. */
01081     AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x,              ti->y,              BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
01082     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);
01083 
01084     DrawBridgeMiddle(ti);
01085   } else { // IsBridge(ti->tile)
01086     const PalSpriteID *psid;
01087     int base_offset;
01088     bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
01089 
01090     if (transport_type == TRANSPORT_RAIL) {
01091       base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
01092       assert(base_offset != 8); // This one is used for roads
01093     } else {
01094       base_offset = 8;
01095     }
01096 
01097     /* as the lower 3 bits are used for other stuff, make sure they are clear */
01098     assert( (base_offset & 0x07) == 0x00);
01099 
01100     DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
01101 
01102     /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
01103     base_offset += (6 - tunnelbridge_direction) % 4;
01104 
01105     if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
01106 
01107     /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
01108     if (transport_type != TRANSPORT_WATER) {
01109       psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
01110     } else {
01111       psid = _aqueduct_sprites + base_offset;
01112     }
01113 
01114     if (!ice) {
01115       TileIndex next = ti->tile + TileOffsByDiagDir(tunnelbridge_direction);
01116       if (ti->tileh != SLOPE_FLAT && ti->z == 0 && HasTileWaterClass(next) && GetWaterClass(next) == WATER_CLASS_SEA) {
01117         DrawShoreTile(ti->tileh);
01118       } else {
01119         DrawClearLandTile(ti, 3);
01120       }
01121     } else {
01122       DrawGroundSprite(SPR_FLAT_SNOW_DESERT_TILE + SlopeToSpriteOffset(ti->tileh), PAL_NONE);
01123     }
01124 
01125     /* draw ramp */
01126 
01127     /* Draw Trambits and PBS Reservation as SpriteCombine */
01128     if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
01129 
01130     /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
01131      * it doesn't disappear behind it
01132      */
01133     /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
01134     AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
01135 
01136     if (transport_type == TRANSPORT_ROAD) {
01137       RoadTypes rts = GetRoadTypes(ti->tile);
01138 
01139       if (HasBit(rts, ROADTYPE_TRAM)) {
01140         uint offset = tunnelbridge_direction;
01141         uint z = ti->z;
01142         if (ti->tileh != SLOPE_FLAT) {
01143           offset = (offset + 1) & 1;
01144           z += TILE_HEIGHT;
01145         } else {
01146           offset += 2;
01147         }
01148         /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01149         DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
01150       }
01151       EndSpriteCombine();
01152     } else if (transport_type == TRANSPORT_RAIL) {
01153       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01154       if (rti->UsesOverlay()) {
01155         SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_BRIDGE);
01156         if (surface != 0) {
01157           if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
01158             AddSortableSpriteToDraw(surface + ((DiagDirToAxis(tunnelbridge_direction) == AXIS_X) ? RTBO_X : RTBO_Y), PAL_NONE, ti->x, ti->y, 16, 16, 0, ti->z + 8);
01159           } else {
01160             AddSortableSpriteToDraw(surface + RTBO_SLOPE + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, 16, 16, 8, ti->z);
01161           }
01162         }
01163         /* Don't fallback to non-overlay sprite -- the spec states that
01164          * if an overlay is present then the bridge surface must be
01165          * present. */
01166       } else if (_game_mode != GM_MENU &&_settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
01167         if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
01168           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);
01169         } else {
01170           AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
01171         }
01172       }
01173       EndSpriteCombine();
01174       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
01175         DrawCatenary(ti);
01176       }
01177     }
01178 
01179     DrawBridgeMiddle(ti);
01180   }
01181 }
01182 
01183 
01202 static BridgePieces CalcBridgePiece(uint north, uint south)
01203 {
01204   if (north == 1) {
01205     return BRIDGE_PIECE_NORTH;
01206   } else if (south == 1) {
01207     return BRIDGE_PIECE_SOUTH;
01208   } else if (north < south) {
01209     return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
01210   } else if (north > south) {
01211     return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
01212   } else {
01213     return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
01214   }
01215 }
01216 
01221 void DrawBridgeMiddle(const TileInfo *ti)
01222 {
01223   /* Sectional view of bridge bounding boxes:
01224    *
01225    *  1           2                                1,2 = SpriteCombine of Bridge front/(back&floor) and TramCatenary
01226    *  1           2                                  3 = empty helper BB
01227    *  1     7     2                                4,5 = pillars under higher bridges
01228    *  1 6 88888 6 2                                  6 = elrail-pylons
01229    *  1 6 88888 6 2                                  7 = elrail-wire
01230    *  1 6 88888 6 2  <- TILE_HEIGHT                  8 = rail-vehicle on bridge
01231    *  3333333333333  <- BB_Z_SEPARATOR
01232    *                 <- unused
01233    *    4       5    <- BB_HEIGHT_UNDER_BRIDGE
01234    *    4       5
01235    *    4       5
01236    *
01237    */
01238 
01239   if (!IsBridgeAbove(ti->tile)) return;
01240 
01241   TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
01242   TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
01243   TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
01244 
01245   Axis axis = GetBridgeAxis(ti->tile);
01246   BridgePieces piece = CalcBridgePiece(
01247     GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
01248     GetTunnelBridgeLength(ti->tile, rampsouth) + 1
01249   );
01250 
01251   const PalSpriteID *psid;
01252   bool drawfarpillar;
01253   if (transport_type != TRANSPORT_WATER) {
01254     BridgeType type =  GetBridgeType(rampsouth);
01255     drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
01256 
01257     uint base_offset;
01258     if (transport_type == TRANSPORT_RAIL) {
01259       base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
01260     } else {
01261       base_offset = 8;
01262     }
01263 
01264     psid = base_offset + GetBridgeSpriteTable(type, piece);
01265   } else {
01266     drawfarpillar = true;
01267     psid = _aqueduct_sprites;
01268   }
01269 
01270   if (axis != AXIS_X) psid += 4;
01271 
01272   int x = ti->x;
01273   int y = ti->y;
01274   uint bridge_z = GetBridgeHeight(rampsouth);
01275   uint z = bridge_z - BRIDGE_Z_START;
01276 
01277   /* Add a bounding box that separates the bridge from things below it. */
01278   AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
01279 
01280   /* Draw Trambits as SpriteCombine */
01281   if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
01282 
01283   /* Draw floor and far part of bridge*/
01284   if (!IsInvisibilitySet(TO_BRIDGES)) {
01285     if (axis == AXIS_X) {
01286       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01287     } else {
01288       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01289     }
01290   }
01291 
01292   psid++;
01293 
01294   if (transport_type == TRANSPORT_ROAD) {
01295     RoadTypes rts = GetRoadTypes(rampsouth);
01296 
01297     if (HasBit(rts, ROADTYPE_TRAM)) {
01298       /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01299       DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, HasBit(rts, ROADTYPE_ROAD), false);
01300     } else {
01301       EndSpriteCombine();
01302       StartSpriteCombine();
01303     }
01304   } else if (transport_type == TRANSPORT_RAIL) {
01305     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(rampsouth));
01306     if (rti->UsesOverlay()) {
01307       SpriteID surface = GetCustomRailSprite(rti, rampsouth, RTSG_BRIDGE, TCX_ON_BRIDGE);
01308       if (surface != 0) {
01309         AddSortableSpriteToDraw(surface + axis, PAL_NONE, x, y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
01310       }
01311     }
01312     EndSpriteCombine();
01313 
01314     if (HasCatenaryDrawn(GetRailType(rampsouth))) {
01315       DrawCatenaryOnBridge(ti);
01316     }
01317   }
01318 
01319   /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
01320   if (!IsInvisibilitySet(TO_BRIDGES)) {
01321     if (axis == AXIS_X) {
01322       y += 12;
01323       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
01324     } else {
01325       x += 12;
01326       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
01327     }
01328   }
01329 
01330   /* Draw TramFront as SpriteCombine */
01331   if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
01332 
01333   /* Do not draw anything more if bridges are invisible */
01334   if (IsInvisibilitySet(TO_BRIDGES)) return;
01335 
01336   psid++;
01337   if (ti->z + 5 == z) {
01338     /* draw poles below for small bridges */
01339     if (psid->sprite != 0) {
01340       SpriteID image = psid->sprite;
01341       SpriteID pal   = psid->pal;
01342       if (IsTransparencySet(TO_BRIDGES)) {
01343         SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
01344         pal = PALETTE_TO_TRANSPARENT;
01345       }
01346 
01347       DrawGroundSpriteAt(image, pal, x - ti->x, y - ti->y, z - ti->z);
01348     }
01349   } else {
01350     /* draw pillars below for high bridges */
01351     DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
01352   }
01353 }
01354 
01355 
01356 static uint GetSlopeZ_TunnelBridge(TileIndex tile, uint x, uint y)
01357 {
01358   uint z;
01359   Slope tileh = GetTileSlope(tile, &z);
01360 
01361   x &= 0xF;
01362   y &= 0xF;
01363 
01364   if (IsTunnel(tile)) {
01365     uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
01366 
01367     /* In the tunnel entrance? */
01368     if (5 <= pos && pos <= 10) return z;
01369   } else { // IsBridge(tile)
01370     DiagDirection dir = GetTunnelBridgeDirection(tile);
01371     uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
01372 
01373     z += ApplyFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
01374 
01375     /* On the bridge ramp? */
01376     if (5 <= pos && pos <= 10) {
01377       uint delta;
01378 
01379       if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
01380 
01381       switch (dir) {
01382         default: NOT_REACHED();
01383         case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
01384         case DIAGDIR_SE: delta = y / 2; break;
01385         case DIAGDIR_SW: delta = x / 2; break;
01386         case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
01387       }
01388       return z + 1 + delta;
01389     }
01390   }
01391 
01392   return z + GetPartialZ(x, y, tileh);
01393 }
01394 
01395 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
01396 {
01397   return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
01398 }
01399 
01400 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
01401 {
01402   TransportType tt = GetTunnelBridgeTransportType(tile);
01403 
01404   if (IsTunnel(tile)) {
01405     td->str = (tt == TRANSPORT_RAIL) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD : STR_LAI_TUNNEL_DESCRIPTION_ROAD;
01406   } else { // IsBridge(tile)
01407     td->str = (tt == TRANSPORT_WATER) ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
01408   }
01409   td->owner[0] = GetTileOwner(tile);
01410 
01411   Owner road_owner = INVALID_OWNER;
01412   Owner tram_owner = INVALID_OWNER;
01413   RoadTypes rts = GetRoadTypes(tile);
01414   if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01415   if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01416 
01417   /* Is there a mix of owners? */
01418   if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
01419       (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
01420     uint i = 1;
01421     if (road_owner != INVALID_OWNER) {
01422       td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
01423       td->owner[i] = road_owner;
01424       i++;
01425     }
01426     if (tram_owner != INVALID_OWNER) {
01427       td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
01428       td->owner[i] = tram_owner;
01429     }
01430   }
01431 
01432   if (tt == TRANSPORT_RAIL) {
01433     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
01434     td->rail_speed = rti->max_speed;
01435 
01436     if (!IsTunnel(tile)) {
01437       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
01438       if (td->rail_speed == 0 || spd < td->rail_speed) {
01439         td->rail_speed = spd;
01440       }
01441     }
01442   }
01443 }
01444 
01445 
01446 static void TileLoop_TunnelBridge(TileIndex tile)
01447 {
01448   bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
01449   switch (_settings_game.game_creation.landscape) {
01450     case LT_ARCTIC: {
01451       /* As long as we do not have a snow density, we want to use the density
01452        * from the entry endge. For tunnels this is the lowest point for bridges the highest point.
01453        * (Independent of foundations) */
01454       uint z = IsBridge(tile) ? GetTileMaxZ(tile) : GetTileZ(tile);
01455       if (snow_or_desert != (z > GetSnowLine())) {
01456         SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
01457         MarkTileDirtyByTile(tile);
01458       }
01459       break;
01460     }
01461 
01462     case LT_TROPIC:
01463       if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
01464         SetTunnelBridgeSnowOrDesert(tile, true);
01465         MarkTileDirtyByTile(tile);
01466       }
01467       break;
01468 
01469     default:
01470       break;
01471   }
01472 }
01473 
01474 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
01475 {
01476   TransportType transport_type = GetTunnelBridgeTransportType(tile);
01477   if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
01478 
01479   DiagDirection dir = GetTunnelBridgeDirection(tile);
01480   if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
01481   return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
01482 }
01483 
01484 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
01485 {
01486   for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01487     /* Update all roadtypes, no matter if they are present */
01488     if (GetRoadOwner(tile, rt) == old_owner) {
01489       SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
01490     }
01491   }
01492 
01493   if (!IsTileOwner(tile, old_owner)) return;
01494 
01495   if (new_owner != INVALID_OWNER) {
01496     SetTileOwner(tile, new_owner);
01497   } else {
01498     if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
01499       /* Since all of our vehicles have been removed, it is safe to remove the rail
01500        * bridge / tunnel. */
01501       CommandCost ret = DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
01502       assert(ret.Succeeded());
01503     } else {
01504       /* In any other case, we can safely reassign the ownership to OWNER_NONE. */
01505       SetTileOwner(tile, OWNER_NONE);
01506     }
01507   }
01508 }
01509 
01515 static const byte TUNNEL_SOUND_FRAME = 1;
01516 
01525 extern const byte _tunnel_visibility_frame[DIAGDIR_END] = {12, 8, 8, 12};
01526 
01527 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
01528 {
01529   int z = GetSlopeZ(x, y) - v->z_pos;
01530 
01531   if (abs(z) > 2) return VETSB_CANNOT_ENTER;
01532   /* Direction into the wormhole */
01533   const DiagDirection dir = GetTunnelBridgeDirection(tile);
01534   /* Direction of the vehicle */
01535   const DiagDirection vdir = DirToDiagDir(v->direction);
01536   /* New position of the vehicle on the tile */
01537   byte pos = (DiagDirToAxis(vdir) == AXIS_X ? x : y) & TILE_UNIT_MASK;
01538   /* Number of units moved by the vehicle since entering the tile */
01539   byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
01540 
01541   if (IsTunnel(tile)) {
01542     if (v->type == VEH_TRAIN) {
01543       Train *t = Train::From(v);
01544 
01545       if (t->track != TRACK_BIT_WORMHOLE && dir == vdir) {
01546         if (t->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
01547           if (!PlayVehicleSound(t, VSE_TUNNEL) && RailVehInfo(t->engine_type)->engclass == 0) {
01548             SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
01549           }
01550           return VETSB_CONTINUE;
01551         }
01552         if (frame == _tunnel_visibility_frame[dir]) {
01553           t->tile = tile;
01554           t->track = TRACK_BIT_WORMHOLE;
01555           t->vehstatus |= VS_HIDDEN;
01556           return VETSB_ENTERED_WORMHOLE;
01557         }
01558       }
01559 
01560       if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
01561         /* We're at the tunnel exit ?? */
01562         t->tile = tile;
01563         t->track = DiagDirToDiagTrackBits(vdir);
01564         assert(t->track);
01565         t->vehstatus &= ~VS_HIDDEN;
01566         return VETSB_ENTERED_WORMHOLE;
01567       }
01568     } else if (v->type == VEH_ROAD) {
01569       RoadVehicle *rv = RoadVehicle::From(v);
01570 
01571       /* Enter tunnel? */
01572       if (rv->state != RVSB_WORMHOLE && dir == vdir) {
01573         if (frame == _tunnel_visibility_frame[dir]) {
01574           /* Frame should be equal to the next frame number in the RV's movement */
01575           assert(frame == rv->frame + 1);
01576           rv->tile = tile;
01577           rv->state = RVSB_WORMHOLE;
01578           rv->vehstatus |= VS_HIDDEN;
01579           return VETSB_ENTERED_WORMHOLE;
01580         } else {
01581           return VETSB_CONTINUE;
01582         }
01583       }
01584 
01585       /* We're at the tunnel exit ?? */
01586       if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
01587         rv->tile = tile;
01588         rv->state = DiagDirToDiagTrackdir(vdir);
01589         rv->frame = frame;
01590         rv->vehstatus &= ~VS_HIDDEN;
01591         return VETSB_ENTERED_WORMHOLE;
01592       }
01593     }
01594   } else { // IsBridge(tile)
01595     if (v->type != VEH_SHIP) {
01596       /* modify speed of vehicle */
01597       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
01598 
01599       if (v->type == VEH_ROAD) spd *= 2;
01600       Vehicle *first = v->First();
01601       first->cur_speed = min(first->cur_speed, spd);
01602     }
01603 
01604     if (vdir == dir) {
01605       /* Vehicle enters bridge at the last frame inside this tile. */
01606       if (frame != TILE_SIZE - 1) return VETSB_CONTINUE;
01607       switch (v->type) {
01608         case VEH_TRAIN: {
01609           Train *t = Train::From(v);
01610           t->track = TRACK_BIT_WORMHOLE;
01611           ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
01612           ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
01613           break;
01614         }
01615 
01616         case VEH_ROAD: {
01617           RoadVehicle *rv = RoadVehicle::From(v);
01618           rv->state = RVSB_WORMHOLE;
01619           /* There are no slopes inside bridges / tunnels. */
01620           ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
01621           ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
01622           break;
01623         }
01624 
01625         case VEH_SHIP:
01626           Ship::From(v)->state = TRACK_BIT_WORMHOLE;
01627           break;
01628 
01629         default: NOT_REACHED();
01630       }
01631       return VETSB_ENTERED_WORMHOLE;
01632     } else if (vdir == ReverseDiagDir(dir)) {
01633       v->tile = tile;
01634       switch (v->type) {
01635         case VEH_TRAIN: {
01636           Train *t = Train::From(v);
01637           if (t->track == TRACK_BIT_WORMHOLE) {
01638             t->track = DiagDirToDiagTrackBits(vdir);
01639             return VETSB_ENTERED_WORMHOLE;
01640           }
01641           break;
01642         }
01643 
01644         case VEH_ROAD: {
01645           RoadVehicle *rv = RoadVehicle::From(v);
01646           if (rv->state == RVSB_WORMHOLE) {
01647             rv->state = DiagDirToDiagTrackdir(vdir);
01648             rv->frame = 0;
01649             return VETSB_ENTERED_WORMHOLE;
01650           }
01651           break;
01652         }
01653 
01654         case VEH_SHIP: {
01655           Ship *ship = Ship::From(v);
01656           if (ship->state == TRACK_BIT_WORMHOLE) {
01657             ship->state = DiagDirToDiagTrackBits(vdir);
01658             return VETSB_ENTERED_WORMHOLE;
01659           }
01660           break;
01661         }
01662 
01663         default: NOT_REACHED();
01664       }
01665     }
01666   }
01667   return VETSB_CONTINUE;
01668 }
01669 
01670 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
01671 {
01672   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
01673     DiagDirection direction = GetTunnelBridgeDirection(tile);
01674     Axis axis = DiagDirToAxis(direction);
01675     CommandCost res;
01676     uint z_old;
01677     Slope tileh_old = GetTileSlope(tile, &z_old);
01678 
01679     /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
01680     if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
01681       CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
01682       res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
01683     } else {
01684       CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
01685       res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
01686     }
01687 
01688     /* Surface slope is valid and remains unchanged? */
01689     if (res.Succeeded() && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
01690   }
01691 
01692   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
01693 }
01694 
01695 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
01696   DrawTile_TunnelBridge,           // draw_tile_proc
01697   GetSlopeZ_TunnelBridge,          // get_slope_z_proc
01698   ClearTile_TunnelBridge,          // clear_tile_proc
01699   NULL,                            // add_accepted_cargo_proc
01700   GetTileDesc_TunnelBridge,        // get_tile_desc_proc
01701   GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
01702   NULL,                            // click_tile_proc
01703   NULL,                            // animate_tile_proc
01704   TileLoop_TunnelBridge,           // tile_loop_clear
01705   ChangeTileOwner_TunnelBridge,    // change_tile_owner_clear
01706   NULL,                            // add_produced_cargo_proc
01707   VehicleEnter_TunnelBridge,       // vehicle_enter_tile_proc
01708   GetFoundation_TunnelBridge,      // get_foundation_proc
01709   TerraformTile_TunnelBridge,      // terraform_tile_proc
01710 };

Generated on Fri Jun 3 05:19:01 2011 for OpenTTD by  doxygen 1.6.1