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