# tunnelbridge_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: tunnelbridge_cmd.cpp 15452 2009-02-11 18:50:47Z frosch $ */
    00002
    00008 #include "stdafx.h"
    00009 #include "openttd.h"
    00010 #include "rail_map.h"
    00011 #include "landscape.h"
    00012 #include "town_type.h"
    00013 #include "unmovable_map.h"
    00014 #include "viewport_func.h"
    00015 #include "command_func.h"
    00016 #include "town.h"
    00017 #include "variables.h"
    00018 #include "train.h"
    00019 #include "water_map.h"
    00020 #include "yapf/yapf.h"
    00021 #include "newgrf_sound.h"
    00022 #include "autoslope.h"
    00023 #include "tunnelbridge_map.h"
    00024 #include "strings_func.h"
    00025 #include "date_func.h"
    00026 #include "functions.h"
    00027 #include "vehicle_func.h"
    00028 #include "sound_func.h"
    00029 #include "tunnelbridge.h"
    00030 #include "engine_base.h"
    00031 #include "cheat_type.h"
    00032 #include "elrail_func.h"
    00033 #include "landscape_type.h"
    00034
    00035 #include "table/sprites.h"
    00036 #include "table/strings.h"
    00037 #include "table/bridge_land.h"
    00038
    00039 BridgeSpec _bridge[MAX_BRIDGES];
    00040 TileIndex _build_tunnel_endtile;
    00041
    00043 void ResetBridges()
    00044 {
    00045   /* First, free sprite table data */
    00046   for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
    00047     if (_bridge[i].sprite_table != NULL) {
    00048       for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
    00049       free(_bridge[i].sprite_table);
    00050     }
    00051   }
    00052
    00053   /* Then, wipe out current bidges */
    00054   memset(&_bridge, 0, sizeof(_bridge));
    00055   /* And finally, reinstall default data */
    00056   memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
    00057 }
    00058
    00062 int CalcBridgeLenCostFactor(int x)
    00063 {
    00064   int n;
    00065   int r;
    00066
    00067   if (x < 2) return x;
    00068   x -= 2;
    00069   for (n = 0, r = 2;; n++) {
    00070     if (x <= n) return r + x * n;
    00071     r += n * n;
    00072     x -= n;
    00073   }
    00074 }
    00075
    00076 Foundation GetBridgeFoundation(Slope tileh, Axis axis)
    00077 {
    00078   if ((tileh == SLOPE_FLAT) ||
    00079       (((tileh == SLOPE_NE) || (tileh == SLOPE_SW)) && (axis == AXIS_X)) ||
    00080       (((tileh == SLOPE_NW) || (tileh == SLOPE_SE)) && (axis == AXIS_Y))) return FOUNDATION_NONE;
    00081
    00082   return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
    00083 }
    00084
    00092 bool HasBridgeFlatRamp(Slope tileh, Axis axis)
    00093 {
    00094   ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
    00095   /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
    00096   return (tileh != SLOPE_FLAT);
    00097 }
    00098
    00099 static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
    00100 {
    00101   const BridgeSpec *bridge = GetBridgeSpec(index);
    00102   assert(table < BRIDGE_PIECE_INVALID);
    00103   if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
    00104     return _bridge_sprite_table[index][table];
    00105   } else {
    00106     return bridge->sprite_table[table];
    00107   }
    00108 }
    00109
    00110
    00119 static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, uint *z)
    00120 {
    00121   Foundation f = GetBridgeFoundation(*tileh, axis);
    00122   *z += ApplyFoundationToSlope(f, tileh);
    00123
    00124   Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
    00125   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
    00126
    00127   if (f == FOUNDATION_NONE) return CommandCost();
    00128
    00129   return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
    00130 }
    00131
    00140 static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, uint *z)
    00141 {
    00142   Foundation f = GetBridgeFoundation(*tileh, axis);
    00143   *z += ApplyFoundationToSlope(f, tileh);
    00144
    00145   Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
    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.terraform);
    00151 }
    00152
    00153 bool CheckBridge_Stuff(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
    00154 {
    00155   if (flags & DC_QUERY_COST) {
    00156     return bridge_len <= (_settings_game.construction.longbridges ? 100U : 16U);
    00157   }
    00158
    00159   if (bridge_type >= MAX_BRIDGES) return false;
    00160
    00161   const BridgeSpec *b = GetBridgeSpec(bridge_type);
    00162   if (b->avail_year > _cur_year) return false;
    00163
    00164   uint max = b->max_length;
    00165   if (max >= 16 && _settings_game.construction.longbridges) max = 100;
    00166
    00167   return b->min_length <= bridge_len && bridge_len <= max;
    00168 }
    00169
    00179 CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00180 {
    00181   BridgeType bridge_type;
    00182   RailType railtype = INVALID_RAILTYPE;
    00183   RoadTypes roadtypes = ROADTYPES_NONE;
    00184   uint x;
    00185   uint y;
    00186   uint sx;
    00187   uint sy;
    00188   TileIndex tile_start;
    00189   TileIndex tile_end;
    00190   Slope tileh_start;
    00191   Slope tileh_end;
    00192   uint z_start;
    00193   uint z_end;
    00194   TileIndex tile;
    00195   TileIndexDiff delta;
    00196   uint bridge_len;
    00197   Axis direction;
    00198   CommandCost cost(EXPENSES_CONSTRUCTION);
    00199   CommandCost ret;
    00200   bool replace_bridge = false;
    00201   BridgeType replaced_bridge_type;
    00202   TransportType transport_type;
    00203
    00204   /* unpack parameters */
    00205   bridge_type = GB(p2, 0, 8);
    00206
    00207   if (p1 >= MapSize()) return CMD_ERROR;
    00208
    00209   transport_type = (TransportType)GB(p2, 15, 2);
    00210
    00211   /* type of bridge */
    00212   switch (transport_type) {
    00213     case TRANSPORT_ROAD:
    00214       roadtypes = (RoadTypes)GB(p2, 8, 3);
    00215       if (!AreValidRoadTypes(roadtypes) || !HasRoadTypesAvail(_current_company, roadtypes)) return CMD_ERROR;
    00216       break;
    00217
    00218     case TRANSPORT_RAIL:
    00219       railtype = (RailType)GB(p2, 8, 7);
    00220       if (!ValParamRailtype(railtype)) return CMD_ERROR;
    00221       break;
    00222
    00223     case TRANSPORT_WATER:
    00224       break;
    00225
    00226     default:
    00227       /* Airports don't have tunnels. */
    00228       return CMD_ERROR;
    00229   }
    00230
    00231   x = TileX(end_tile);
    00232   y = TileY(end_tile);
    00233   sx = TileX(p1);
    00234   sy = TileY(p1);
    00235
    00236   /* check if valid, and make sure that (x,y) are smaller than (sx,sy) */
    00237   if (x == sx) {
    00238     if (y == sy) return_cmd_error(STR_5008_CANNOT_START_AND_END_ON);
    00239     direction = AXIS_Y;
    00240     if (y > sy) Swap(y, sy);
    00241   } else if (y == sy) {
    00242     direction = AXIS_X;
    00243     if (x > sx) Swap(x, sx);
    00244   } else {
    00245     return_cmd_error(STR_500A_START_AND_END_MUST_BE_IN);
    00246   }
    00247
    00248   bridge_len = sx + sy - x - y - 1;
    00249   if (transport_type != TRANSPORT_WATER) {
    00250     /* set and test bridge length, availability */
    00251     if (!CheckBridge_Stuff(bridge_type, bridge_len, flags)) return_cmd_error(STR_5015_CAN_T_BUILD_BRIDGE_HERE);
    00252   }
    00253
    00254   /* retrieve landscape height and ensure it's on land */
    00255   tile_start = TileXY(x, y);
    00256   tile_end = TileXY(sx, sy);
    00257   if (IsWaterTile(tile_start) || IsWaterTile(tile_end)) {
    00258     return_cmd_error(STR_02A0_ENDS_OF_BRIDGE_MUST_BOTH);
    00259   }
    00260
    00261   tileh_start = GetTileSlope(tile_start, &z_start);
    00262   tileh_end = GetTileSlope(tile_end, &z_end);
    00263
    00264   CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
    00265   CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end,   &z_end);
    00266
    00267   if (z_start != z_end) return_cmd_error(STR_BRIDGEHEADS_NOT_SAME_HEIGHT);
    00268
    00269   if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
    00270       GetOtherBridgeEnd(tile_start) == tile_end &&
    00271       GetTunnelBridgeTransportType(tile_start) == transport_type) {
    00272     /* Replace a current bridge. */
    00273
    00274     /* If this is a railway bridge, make sure the railtypes match. */
    00275     if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
    00276       return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
    00277     }
    00278
    00279     /* Do not replace town bridges with lower speed bridges. */
    00280     if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
    00281         GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed) {
    00282       Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
    00283
    00284       if (t == NULL) {
    00285         return CMD_ERROR;
    00286       } else {
    00287         SetDParam(0, t->index);
    00288         return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
    00289       }
    00290     }
    00291
    00292     /* Do not replace the bridge with the same bridge type. */
    00293     if (!(flags & DC_QUERY_COST) && bridge_type == GetBridgeType(tile_start)) {
    00294       return_cmd_error(STR_1007_ALREADY_BUILT);
    00295     }
    00296
    00297     /* Do not allow replacing another company's bridges. */
    00298     if (!IsTileOwner(tile_start, _current_company) && !IsTileOwner(tile_start, OWNER_TOWN)) {
    00299       return_cmd_error(STR_1024_AREA_IS_OWNED_BY_ANOTHER);
    00300     }
    00301
    00302     cost.AddCost((bridge_len + 1) * _price.clear_bridge); // The cost of clearing the current bridge.
    00303     replace_bridge = true;
    00304     replaced_bridge_type = GetBridgeType(tile_start);
    00305
    00306     /* Do not remove road types when upgrading a bridge */
    00307     roadtypes |= GetRoadTypes(tile_start);
    00308   } else {
    00309     /* Build a new bridge. */
    00310
    00311     bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
    00312
    00313     /* Try and clear the start landscape */
    00314     ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00315     if (CmdFailed(ret)) return ret;
    00316     cost = ret;
    00317
    00318     if (CmdFailed(terraform_cost_north) || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes))
    00319       return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
    00320     cost.AddCost(terraform_cost_north);
    00321
    00322     /* Try and clear the end landscape */
    00323     ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00324     if (CmdFailed(ret)) return ret;
    00325     cost.AddCost(ret);
    00326
    00327     /* false - end tile slope check */
    00328     if (CmdFailed(terraform_cost_south) || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes))
    00329       return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
    00330     cost.AddCost(terraform_cost_south);
    00331
    00332     if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
    00333   }
    00334
    00335   if (!replace_bridge) {
    00336     TileIndex Heads[] = {tile_start, tile_end};
    00337     int i;
    00338
    00339     for (i = 0; i < 2; i++) {
    00340       if (MayHaveBridgeAbove(Heads[i])) {
    00341         if (IsBridgeAbove(Heads[i])) {
    00342           TileIndex north_head = GetNorthernBridgeEnd(Heads[i]);
    00343
    00344           if (direction == GetBridgeAxis(Heads[i])) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
    00345
    00346           if (z_start + TILE_HEIGHT == GetBridgeHeight(north_head)) {
    00347             return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
    00348           }
    00349         }
    00350       }
    00351     }
    00352   }
    00353
    00354   /* do the drill? */
    00355   if (flags & DC_EXEC) {
    00356     DiagDirection dir = AxisToDiagDir(direction);
    00357     Owner owner = (replace_bridge && IsTileOwner(tile_start, OWNER_TOWN)) ? OWNER_TOWN : _current_company;
    00358
    00359     switch (transport_type) {
    00360       case TRANSPORT_RAIL:
    00361         MakeRailBridgeRamp(tile_start, owner, bridge_type, dir,                 railtype);
    00362         MakeRailBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), railtype);
    00363         break;
    00364
    00365       case TRANSPORT_ROAD:
    00366         MakeRoadBridgeRamp(tile_start, owner, bridge_type, dir,                 roadtypes);
    00367         MakeRoadBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), roadtypes);
    00368         break;
    00369
    00370       case TRANSPORT_WATER:
    00371         MakeAqueductBridgeRamp(tile_start, owner, dir);
    00372         MakeAqueductBridgeRamp(tile_end,   owner, ReverseDiagDir(dir));
    00373         break;
    00374
    00375       default:
    00376         NOT_REACHED();
    00377         break;
    00378     }
    00379     MarkTileDirtyByTile(tile_start);
    00380     MarkTileDirtyByTile(tile_end);
    00381   }
    00382
    00383   delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
    00384   for (tile = tile_start + delta; tile != tile_end; tile += delta) {
    00385     if (GetTileMaxZ(tile) > z_start) return_cmd_error(STR_BRIDGE_TOO_LOW_FOR_TERRAIN);
    00386
    00387     if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile) && !replace_bridge) {
    00388       /* Disallow crossing bridges for the time being */
    00389       return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
    00390     }
    00391
    00392     switch (GetTileType(tile)) {
    00393       case MP_WATER:
    00394         if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
    00395         break;
    00396
    00397       case MP_RAILWAY:
    00398         if (!IsPlainRailTile(tile)) goto not_valid_below;
    00399         break;
    00400
    00401       case MP_ROAD:
    00402         if (IsRoadDepot(tile)) goto not_valid_below;
    00403         break;
    00404
    00405       case MP_TUNNELBRIDGE:
    00406         if (IsTunnel(tile)) break;
    00407         if (replace_bridge) break;
    00408         if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
    00409         if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
    00410         break;
    00411
    00412       case MP_UNMOVABLE:
    00413         if (!IsOwnedLand(tile)) goto not_valid_below;
    00414         break;
    00415
    00416       case MP_CLEAR:
    00417         break;
    00418
    00419       default:
    00420 not_valid_below:;
    00421         /* try and clear the middle landscape */
    00422         ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00423         if (CmdFailed(ret)) return ret;
    00424         cost.AddCost(ret);
    00425         break;
    00426     }
    00427
    00428     if (flags & DC_EXEC) {
    00429       SetBridgeMiddle(tile, direction);
    00430       MarkTileDirtyByTile(tile);
    00431     }
    00432   }
    00433
    00434   if (flags & DC_EXEC && transport_type == TRANSPORT_RAIL) {
    00435     Track track = AxisToTrack(direction);
    00436     AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, _current_company);
    00437     YapfNotifyTrackLayoutChange(tile_start, track);
    00438   }
    00439
    00440   /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
    00441    * It's unnecessary to execute this command every time for every bridge. So it is done only
    00442    * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
    00443    */
    00444   if (!(flags & DC_QUERY_COST) || (IsValidCompanyID(_current_company) && GetCompany(_current_company)->is_ai)) {
    00445     bridge_len += 2; // begin and end tiles/ramps
    00446
    00447     if (IsValidCompanyID(_current_company))
    00448       bridge_len = CalcBridgeLenCostFactor(bridge_len);
    00449
    00450     cost.AddCost((int64)bridge_len * _price.build_bridge * GetBridgeSpec(bridge_type)->price >> 8);
    00451
    00452     /* Aqueducts are a little more expensive. */
    00453     if (transport_type == TRANSPORT_WATER) cost.AddCost((int64)bridge_len * _price.clear_water);
    00454   }
    00455
    00456   return cost;
    00457 }
    00458
    00459
    00466 CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00467 {
    00468   TileIndexDiff delta;
    00469   TileIndex end_tile;
    00470   DiagDirection direction;
    00471   Slope start_tileh;
    00472   Slope end_tileh;
    00473   TransportType transport_type = (TransportType)GB(p1, 9, 1);
    00474   uint start_z;
    00475   uint end_z;
    00476   CommandCost cost(EXPENSES_CONSTRUCTION);
    00477   CommandCost ret;
    00478
    00479   _build_tunnel_endtile = 0;
    00480   if (transport_type == TRANSPORT_RAIL) {
    00481     if (!ValParamRailtype((RailType)p1)) return CMD_ERROR;
    00482   } else {
    00483     const RoadTypes rts = (RoadTypes)GB(p1, 0, 3);
    00484     if (!AreValidRoadTypes(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
    00485   }
    00486
    00487   start_tileh = GetTileSlope(start_tile, &start_z);
    00488   direction = GetInclinedSlopeDirection(start_tileh);
    00489   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_500B_SITE_UNSUITABLE_FOR_TUNNEL);
    00490
    00491   if (IsWaterTile(start_tile)) return_cmd_error(STR_3807_CAN_T_BUILD_ON_WATER);
    00492
    00493   ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00494   if (CmdFailed(ret)) return ret;
    00495
    00496   /* XXX - do NOT change 'ret' in the loop, as it is used as the price
    00497    * for the clearing of the entrance of the tunnel. Assigning it to
    00498    * cost before the loop will yield different costs depending on start-
    00499    * position, because of increased-cost-by-length: 'cost += cost >> 3' */
    00500
    00501   delta = TileOffsByDiagDir(direction);
    00502   DiagDirection tunnel_in_way_dir;
    00503   if (DiagDirToAxis(direction) == AXIS_Y) {
    00504     tunnel_in_way_dir = (TileX(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SW : DIAGDIR_NE;
    00505   } else {
    00506     tunnel_in_way_dir = (TileY(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SE : DIAGDIR_NW;
    00507   }
    00508
    00509   end_tile = start_tile;
    00510
    00512   int tiles_coef = 3;
    00514   int tiles = 0;
    00516   int tiles_bump = 25;
    00517
    00518   for (;;) {
    00519     end_tile += delta;
    00520     if (!IsValidTile(end_tile)) return_cmd_error(STR_TUNNEL_THROUGH_MAP_BORDER);
    00521     end_tileh = GetTileSlope(end_tile, &end_z);
    00522
    00523     if (start_z == end_z) break;
    00524
    00525     if (!_cheats.crossing_tunnels.value && IsTunnelInWayDir(end_tile, start_z, tunnel_in_way_dir)) {
    00526       return_cmd_error(STR_5003_ANOTHER_TUNNEL_IN_THE_WAY);
    00527     }
    00528
    00529     tiles++;
    00530     if (tiles == tiles_bump) {
    00531       tiles_coef++;
    00532       tiles_bump *= 2;
    00533     }
    00534
    00535     cost.AddCost(_price.build_tunnel);
    00536     cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
    00537   }
    00538
    00539   /* Add the cost of the entrance */
    00540   cost.AddCost(_price.build_tunnel);
    00541   cost.AddCost(ret);
    00542
    00543   /* if the command fails from here on we want the end tile to be highlighted */
    00544   _build_tunnel_endtile = end_tile;
    00545
    00546   if (IsWaterTile(end_tile)) return_cmd_error(STR_3807_CAN_T_BUILD_ON_WATER);
    00547
    00548   /* slope of end tile must be complementary to the slope of the start tile */
    00549   if (end_tileh != ComplementSlope(start_tileh)) {
    00550     /* Check if there is a structure on the terraformed tile. Do not add the cost, that will be done by the terraforming
    00551      * Note: Currently the town rating is also affected by this clearing-test. So effectivly the player is punished twice for clearing
    00552      *       the tree on end_tile.
    00553      */
    00554     ret = DoCommand(end_tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR);
    00555     if (CmdFailed(ret)) return_cmd_error(STR_5005_UNABLE_TO_EXCAVATE_LAND);
    00556
    00557     ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
    00558     if (CmdFailed(ret)) return_cmd_error(STR_5005_UNABLE_TO_EXCAVATE_LAND);
    00559   } else {
    00560     ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00561     if (CmdFailed(ret)) return ret;
    00562   }
    00563   cost.AddCost(_price.build_tunnel);
    00564   cost.AddCost(ret);
    00565
    00566   if (flags & DC_EXEC) {
    00567     if (transport_type == TRANSPORT_RAIL) {
    00568       MakeRailTunnel(start_tile, _current_company, direction,                 (RailType)GB(p1, 0, 4));
    00569       MakeRailTunnel(end_tile,   _current_company, ReverseDiagDir(direction), (RailType)GB(p1, 0, 4));
    00570       AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, _current_company);
    00571       YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
    00572     } else {
    00573       MakeRoadTunnel(start_tile, _current_company, direction,                 (RoadTypes)GB(p1, 0, 3));
    00574       MakeRoadTunnel(end_tile,   _current_company, ReverseDiagDir(direction), (RoadTypes)GB(p1, 0, 3));
    00575     }
    00576   }
    00577
    00578   return cost;
    00579 }
    00580
    00581
    00582 static inline bool CheckAllowRemoveTunnelBridge(TileIndex tile)
    00583 {
    00584   /* Floods can remove anything as well as the scenario editor */
    00585   if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return true;
    00586   /* Obviously if the bridge/tunnel belongs to us, or no-one, we can remove it */
    00587   if (CheckTileOwnership(tile) || IsTileOwner(tile, OWNER_NONE)) return true;
    00588   /* Otherwise we can only remove town-owned stuff with extra settings, or cheat */
    00589   if (IsTileOwner(tile, OWNER_TOWN) && (_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) return true;
    00590   return false;
    00591 }
    00592
    00593 static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
    00594 {
    00595   Town *t = NULL;
    00596   TileIndex endtile;
    00597
    00598   if (!CheckAllowRemoveTunnelBridge(tile)) return CMD_ERROR;
    00599
    00600   endtile = GetOtherTunnelEnd(tile);
    00601
    00602   if (HasVehicleOnTunnelBridge(tile, endtile)) return CMD_ERROR;
    00603
    00604   _build_tunnel_endtile = endtile;
    00605
    00606   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
    00607     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
    00608
    00609     /* Check if you are allowed to remove the tunnel owned by a town
    00610      * Removal depends on difficulty settings */
    00611     if (!CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE)) {
    00612       SetDParam(0, t->index);
    00613       return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
    00614     }
    00615   }
    00616
    00617   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
    00618    * you have a "Poor" (0) town rating */
    00619   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
    00620     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
    00621   }
    00622
    00623   if (flags & DC_EXEC) {
    00624     if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
    00625       /* We first need to request values before calling DoClearSquare */
    00626       DiagDirection dir = GetTunnelBridgeDirection(tile);
    00627       Track track = DiagDirToDiagTrack(dir);
    00628       Owner owner = GetTileOwner(tile);
    00629
    00630       Vehicle *v = NULL;
    00631       if (GetTunnelBridgeReservation(tile)) {
    00632         v = GetTrainForReservation(tile, track);
    00633         if (v != NULL) FreeTrainTrackReservation(v);
    00634       }
    00635
    00636       DoClearSquare(tile);
    00637       DoClearSquare(endtile);
    00638
    00639       /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
    00640       AddSideToSignalBuffer(tile,    ReverseDiagDir(dir), owner);
    00641       AddSideToSignalBuffer(endtile, dir,                 owner);
    00642
    00643       YapfNotifyTrackLayoutChange(tile,    track);
    00644       YapfNotifyTrackLayoutChange(endtile, track);
    00645
    00646       if (v != NULL) TryPathReserve(v);
    00647     } else {
    00648       DoClearSquare(tile);
    00649       DoClearSquare(endtile);
    00650     }
    00651   }
    00652   return CommandCost(EXPENSES_CONSTRUCTION, _price.clear_tunnel * (GetTunnelBridgeLength(tile, endtile) + 2));
    00653 }
    00654
    00655
    00656 static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
    00657 {
    00658   DiagDirection direction;
    00659   TileIndexDiff delta;
    00660   TileIndex endtile;
    00661   Town *t = NULL;
    00662
    00663   if (!CheckAllowRemoveTunnelBridge(tile)) return CMD_ERROR;
    00664
    00665   endtile = GetOtherBridgeEnd(tile);
    00666
    00667   if (HasVehicleOnTunnelBridge(tile, endtile)) return CMD_ERROR;
    00668
    00669   direction = GetTunnelBridgeDirection(tile);
    00670   delta = TileOffsByDiagDir(direction);
    00671
    00672   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
    00673     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
    00674
    00675     /* Check if you are allowed to remove the bridge owned by a town
    00676      * Removal depends on difficulty settings */
    00677     if (!CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE)) {
    00678       SetDParam(0, t->index);
    00679       return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
    00680     }
    00681   }
    00682
    00683   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
    00684    * you have a "Poor" (0) town rating */
    00685   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
    00686     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
    00687   }
    00688
    00689   if (flags & DC_EXEC) {
    00690     /* read this value before actual removal of bridge */
    00691     bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
    00692     Owner owner = GetTileOwner(tile);
    00693     uint height = GetBridgeHeight(tile);
    00694     Vehicle *v = NULL;
    00695
    00696     if (rail && GetTunnelBridgeReservation(tile)) {
    00697       v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
    00698       if (v != NULL) FreeTrainTrackReservation(v);
    00699     }
    00700
    00701     DoClearSquare(tile);
    00702     DoClearSquare(endtile);
    00703     for (TileIndex c = tile + delta; c != endtile; c += delta) {
    00704       /* do not let trees appear from 'nowhere' after removing bridge */
    00705       if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
    00706         uint minz = GetTileMaxZ(c) + 3 * TILE_HEIGHT;
    00707         if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
    00708       }
    00709       ClearBridgeMiddle(c);
    00710       MarkTileDirtyByTile(c);
    00711     }
    00712
    00713     if (rail) {
    00714       /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
    00715       AddSideToSignalBuffer(tile,    ReverseDiagDir(direction), owner);
    00716       AddSideToSignalBuffer(endtile, direction,                 owner);
    00717
    00718       Track track = DiagDirToDiagTrack(direction);
    00719       YapfNotifyTrackLayoutChange(tile,    track);
    00720       YapfNotifyTrackLayoutChange(endtile, track);
    00721
    00722       if (v != NULL) TryPathReserve(v, true);
    00723     }
    00724   }
    00725
    00726   return CommandCost(EXPENSES_CONSTRUCTION, (GetTunnelBridgeLength(tile, endtile) + 2) * _price.clear_bridge);
    00727 }
    00728
    00729 static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
    00730 {
    00731   if (IsTunnel(tile)) {
    00732     if (flags & DC_AUTO) return_cmd_error(STR_5006_MUST_DEMOLISH_TUNNEL_FIRST);
    00733     return DoClearTunnel(tile, flags);
    00734   } else { // IsBridge(tile)
    00735     if (flags & DC_AUTO) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
    00736     return DoClearBridge(tile, flags);
    00737   }
    00738
    00739   return CMD_ERROR;
    00740 }
    00741
    00753 static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
    00754 {
    00755   /* Do not draw bridge pillars if they are invisible */
    00756   if (IsInvisibilitySet(TO_BRIDGES)) return;
    00757
    00758   SpriteID image = psid->sprite;
    00759
    00760   if (image != 0) {
    00761     /* "side" specifies the side the pillars stand on.
    00762      * The length of the pillars is then set to the height of the bridge over the corners of this edge.
    00763      *
    00764      *                axis==AXIS_X  axis==AXIS_Y
    00765      *   side==false      SW            NW
    00766      *   side==true       NE            SE
    00767      *
    00768      * I have no clue, why this was done this way.
    00769      */
    00770     bool side = HasBit(image, 0);
    00771
    00772     /* "dir" means the edge the pillars stand on */
    00773     DiagDirection dir = AxisToDiagDir(axis);
    00774     if (side != (axis == AXIS_Y)) dir = ReverseDiagDir(dir);
    00775
    00776     /* Determine ground height under pillars */
    00777     int front_height = ti->z;
    00778     int back_height = ti->z;
    00779     GetSlopeZOnEdge(ti->tileh, dir, &front_height, &back_height);
    00780
    00781     /* x and y size of bounding-box of pillars */
    00782     int w = (axis == AXIS_X ? 16 : 2);
    00783     int h = (axis == AXIS_X ? 2 : 16);
    00784     /* sprite position of back facing pillar */
    00785     int x_back = x - (axis == AXIS_X ? 0 : 9);
    00786     int y_back = y - (axis == AXIS_X ? 9 : 0);
    00787
    00788     for (int cur_z = z_bridge; cur_z >= front_height || cur_z >= back_height; cur_z -= TILE_HEIGHT) {
    00789       /* Draw front facing pillar */
    00790       if (cur_z >= front_height) {
    00791         AddSortableSpriteToDraw(image, psid->pal, x, y, w, h, BB_HEIGHT_UNDER_BRIDGE - 5, cur_z, IsTransparencySet(TO_BRIDGES), 0, 0, -5);
    00792       }
    00793
    00794       /* Draw back facing pillar, but not the highest part directly under the bridge-floor */
    00795       if (drawfarpillar && cur_z >= back_height && cur_z < z_bridge - TILE_HEIGHT) {
    00796         AddSortableSpriteToDraw(image, psid->pal, x_back, y_back, w, h, BB_HEIGHT_UNDER_BRIDGE - 5, cur_z, IsTransparencySet(TO_BRIDGES), 0, 0, -5);
    00797       }
    00798     }
    00799   }
    00800 }
    00801
    00811 static void DrawBridgeTramBits(int x, int y, byte z, int offset, bool overlay, bool head)
    00812 {
    00813   static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
    00814   static const SpriteID back_offsets[6]    =   {  95,  96,  99, 102, 100, 101 };
    00815   static const SpriteID front_offsets[6]   =   {  97,  98, 103, 106, 104, 105 };
    00816
    00817   static const uint size_x[6] = {  1, 16, 16,  1, 16,  1 };
    00818   static const uint size_y[6] = { 16,  1,  1, 16,  1, 16 };
    00819   static const uint front_bb_offset_x[6] = { 15,  0,  0, 15,  0, 15 };
    00820   static const uint front_bb_offset_y[6] = {  0, 15, 15,  0, 15,  0 };
    00821
    00822   /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
    00823    * The bounding boxes here are the same as for bridge front/roof */
    00824   if (head || !IsInvisibilitySet(TO_BRIDGES)) {
    00825     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
    00826       x, y, size_x[offset], size_y[offset], 0x28, z,
    00827       !head && IsTransparencySet(TO_BRIDGES));
    00828   }
    00829
    00830   /* Do not draw catenary if it is set invisible */
    00831   if (!IsInvisibilitySet(TO_CATENARY)) {
    00832     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
    00833       x, y, size_x[offset], size_y[offset], 0x28, z,
    00834       IsTransparencySet(TO_CATENARY));
    00835   }
    00836
    00837   /* Start a new SpriteCombine for the front part */
    00838   EndSpriteCombine();
    00839   StartSpriteCombine();
    00840
    00841   /* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
    00842   if (!IsInvisibilitySet(TO_CATENARY)) {
    00843     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
    00844       x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
    00845       IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
    00846   }
    00847 }
    00848
    00862 static void DrawTile_TunnelBridge(TileInfo *ti)
    00863 {
    00864   SpriteID image;
    00865   TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
    00866   DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
    00867
    00868   if (IsTunnel(ti->tile)) {
    00869     /* Front view of tunnel bounding boxes:
    00870      *
    00871      *   122223  <- BB_Z_SEPARATOR
    00872      *   1    3
    00873      *   1    3                1,3 = empty helper BB
    00874      *   1    3                  2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
    00875      *
    00876      */
    00877
    00878     static const int _tunnel_BB[4][12] = {
    00879       /*  tunnnel-roof  |  Z-separator  | tram-catenary
    00880        * w  h  bb_x bb_y| x   y   w   h |bb_x bb_y w h */
    00881       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // NE
    00882       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // SE
    00883       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // SW
    00884       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // NW
    00885     };
    00886     const int *BB_data = _tunnel_BB[tunnelbridge_direction];
    00887
    00888     bool catenary = false;
    00889
    00890     if (transport_type == TRANSPORT_RAIL) {
    00891       image = GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.tunnel;
    00892     } else {
    00893       image = SPR_TUNNEL_ENTRY_REAR_ROAD;
    00894     }
    00895
    00896     if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += 32;
    00897
    00898     image += tunnelbridge_direction * 2;
    00899     DrawGroundSprite(image, PAL_NONE);
    00900
    00901     /* PBS debugging, draw reserved tracks darker */
    00902     if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && (transport_type == TRANSPORT_RAIL && GetTunnelBridgeReservation(ti->tile))) {
    00903       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
    00904       DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_y : rti->base_sprites.single_x, PALETTE_CRASH);
    00905     }
    00906
    00907     if (transport_type == TRANSPORT_ROAD) {
    00908       RoadTypes rts = GetRoadTypes(ti->tile);
    00909
    00910       if (HasBit(rts, ROADTYPE_TRAM)) {
    00911         static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, {  5, 76, 77,  4 } };
    00912
    00913         DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
    00914
    00915         /* Do not draw wires if they are invisible */
    00916         if (!IsInvisibilitySet(TO_CATENARY)) {
    00917           catenary = true;
    00918           StartSpriteCombine();
    00919           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);
    00920         }
    00921       }
    00922     } else if (HasCatenaryDrawn(GetRailType(ti->tile))) {
    00923       /* Maybe draw pylons on the entry side */
    00924       DrawCatenary(ti);
    00925
    00926       catenary = true;
    00927       StartSpriteCombine();
    00928       /* Draw wire above the ramp */
    00929       DrawCatenaryOnTunnel(ti);
    00930     }
    00931
    00932     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);
    00933
    00934     if (catenary) EndSpriteCombine();
    00935
    00936     /* Add helper BB for sprite sorting, that separate the tunnel from things beside of it */
    00937     AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x             , ti->y             , BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
    00938     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);
    00939
    00940     DrawBridgeMiddle(ti);
    00941   } else { // IsBridge(ti->tile)
    00942     const PalSpriteID *psid;
    00943     int base_offset;
    00944     bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
    00945
    00946     if (transport_type == TRANSPORT_RAIL) {
    00947       base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
    00948       assert(base_offset != 8); // This one is used for roads
    00949     } else {
    00950       base_offset = 8;
    00951     }
    00952
    00953     /* as the lower 3 bits are used for other stuff, make sure they are clear */
    00954     assert( (base_offset & 0x07) == 0x00);
    00955
    00956     DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
    00957
    00958     /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
    00959     base_offset += (6 - tunnelbridge_direction) % 4;
    00960
    00961     if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
    00962
    00963     /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
    00964     if (transport_type != TRANSPORT_WATER) {
    00965       psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
    00966     } else {
    00967       psid = _aqueduct_sprites + base_offset;
    00968     }
    00969
    00970     if (!ice) {
    00971       DrawClearLandTile(ti, 3);
    00972     } else {
    00973       DrawGroundSprite(SPR_FLAT_SNOWY_TILE + _tileh_to_sprite[ti->tileh], PAL_NONE);
    00974     }
    00975
    00976     /* draw ramp */
    00977
    00978     /* Draw Trambits as SpriteCombine */
    00979     if (transport_type == TRANSPORT_ROAD) StartSpriteCombine();
    00980
    00981     /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
    00982      * it doesn't disappear behind it
    00983      */
    00984     /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
    00985     AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
    00986
    00987     if (_settings_client.gui.show_track_reservation && transport_type == TRANSPORT_RAIL && GetTunnelBridgeReservation(ti->tile)) {
    00988       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
    00989       if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
    00990         AddSortableSpriteToDraw(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_y : rti->base_sprites.single_x, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 8);
    00991       } else {
    00992         AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
    00993       }
    00994     }
    00995
    00996     if (transport_type == TRANSPORT_ROAD) {
    00997       RoadTypes rts = GetRoadTypes(ti->tile);
    00998
    00999       if (HasBit(rts, ROADTYPE_TRAM)) {
    01000         uint offset = tunnelbridge_direction;
    01001         uint z = ti->z;
    01002         if (ti->tileh != SLOPE_FLAT) {
    01003           offset = (offset + 1) & 1;
    01004           z += TILE_HEIGHT;
    01005         } else {
    01006           offset += 2;
    01007         }
    01008         /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
    01009         DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
    01010       }
    01011       EndSpriteCombine();
    01012     } else if (transport_type == TRANSPORT_RAIL) {
    01013       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
    01014         DrawCatenary(ti);
    01015       }
    01016     }
    01017
    01018     DrawBridgeMiddle(ti);
    01019   }
    01020 }
    01021
    01022
    01040 static BridgePieces CalcBridgePiece(uint north, uint south)
    01041 {
    01042   if (north == 1) {
    01043     return BRIDGE_PIECE_NORTH;
    01044   } else if (south == 1) {
    01045     return BRIDGE_PIECE_SOUTH;
    01046   } else if (north < south) {
    01047     return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
    01048   } else if (north > south) {
    01049     return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
    01050   } else {
    01051     return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
    01052   }
    01053 }
    01054
    01055
    01056 void DrawBridgeMiddle(const TileInfo *ti)
    01057 {
    01058   /* Sectional view of bridge bounding boxes:
    01059    *
    01060    *  1           2                                1,2 = SpriteCombine of Bridge front/(back&floor) and TramCatenary
    01061    *  1           2                                  3 = empty helper BB
    01062    *  1     7     2                                4,5 = pillars under higher bridges
    01063    *  1 6 88888 6 2                                  6 = elrail-pylons
    01064    *  1 6 88888 6 2                                  7 = elrail-wire
    01065    *  1 6 88888 6 2  <- TILE_HEIGHT                  8 = rail-vehicle on bridge
    01066    *  3333333333333  <- BB_Z_SEPARATOR
    01067    *                 <- unused
    01068    *    4       5    <- BB_HEIGHT_UNDER_BRIDGE
    01069    *    4       5
    01070    *    4       5
    01071    *
    01072    */
    01073
    01074   /* Z position of the bridge sprites relative to bridge height (downwards) */
    01075   static const int BRIDGE_Z_START = 3;
    01076
    01077   if (!IsBridgeAbove(ti->tile)) return;
    01078
    01079   TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
    01080   TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
    01081   TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
    01082
    01083   Axis axis = GetBridgeAxis(ti->tile);
    01084   BridgePieces piece = CalcBridgePiece(
    01085     GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
    01086     GetTunnelBridgeLength(ti->tile, rampsouth) + 1
    01087   );
    01088
    01089   const PalSpriteID *psid;
    01090   bool drawfarpillar;
    01091   if (transport_type != TRANSPORT_WATER) {
    01092     BridgeType type =  GetBridgeType(rampsouth);
    01093     drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
    01094
    01095     uint base_offset;
    01096     if (transport_type == TRANSPORT_RAIL) {
    01097       base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
    01098     } else {
    01099       base_offset = 8;
    01100     }
    01101
    01102     psid = base_offset + GetBridgeSpriteTable(type, piece);
    01103   } else {
    01104     drawfarpillar = true;
    01105     psid = _aqueduct_sprites;
    01106   }
    01107
    01108   if (axis != AXIS_X) psid += 4;
    01109
    01110   int x = ti->x;
    01111   int y = ti->y;
    01112   uint bridge_z = GetBridgeHeight(rampsouth);
    01113   uint z = bridge_z - BRIDGE_Z_START;
    01114
    01115   /* Add a bounding box, that separates the bridge from things below it. */
    01116   AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
    01117
    01118   /* Draw Trambits as SpriteCombine */
    01119   if (transport_type == TRANSPORT_ROAD) StartSpriteCombine();
    01120
    01121   /* Draw floor and far part of bridge*/
    01122   if (!IsInvisibilitySet(TO_BRIDGES)) {
    01123     if (axis == AXIS_X) {
    01124       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
    01125     } else {
    01126       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
    01127     }
    01128   }
    01129
    01130   psid++;
    01131
    01132   if (transport_type == TRANSPORT_ROAD) {
    01133     RoadTypes rts = GetRoadTypes(rampsouth);
    01134
    01135     if (HasBit(rts, ROADTYPE_TRAM)) {
    01136       /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
    01137       DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, HasBit(rts, ROADTYPE_ROAD), false);
    01138     } else {
    01139       EndSpriteCombine();
    01140       StartSpriteCombine();
    01141     }
    01142   } else if (transport_type == TRANSPORT_RAIL) {
    01143     if (HasCatenaryDrawn(GetRailType(rampsouth))) {
    01144       DrawCatenaryOnBridge(ti);
    01145     }
    01146   }
    01147
    01148   /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
    01149   if (!IsInvisibilitySet(TO_BRIDGES)) {
    01150     if (axis == AXIS_X) {
    01151       y += 12;
    01152       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
    01153     } else {
    01154       x += 12;
    01155       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
    01156     }
    01157   }
    01158
    01159   /* Draw TramFront as SpriteCombine */
    01160   if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
    01161
    01162   /* Do not draw anything more if bridges are invisible */
    01163   if (IsInvisibilitySet(TO_BRIDGES)) return;
    01164
    01165   psid++;
    01166   if (ti->z + 5 == z) {
    01167     /* draw poles below for small bridges */
    01168     if (psid->sprite != 0) {
    01169       SpriteID image = psid->sprite;
    01170       SpriteID pal   = psid->pal;
    01171       if (IsTransparencySet(TO_BRIDGES)) {
    01172         SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
    01173         pal = PALETTE_TO_TRANSPARENT;
    01174       }
    01175
    01176       DrawGroundSpriteAt(image, pal, x, y, z);
    01177     }
    01178   } else if (_settings_client.gui.bridge_pillars) {
    01179     /* draw pillars below for high bridges */
    01180     DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
    01181   }
    01182 }
    01183
    01184
    01185 static uint GetSlopeZ_TunnelBridge(TileIndex tile, uint x, uint y)
    01186 {
    01187   uint z;
    01188   Slope tileh = GetTileSlope(tile, &z);
    01189
    01190   x &= 0xF;
    01191   y &= 0xF;
    01192
    01193   if (IsTunnel(tile)) {
    01194     uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
    01195
    01196     /* In the tunnel entrance? */
    01197     if (5 <= pos && pos <= 10) return z;
    01198   } else { // IsBridge(tile)
    01199     DiagDirection dir = GetTunnelBridgeDirection(tile);
    01200     uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
    01201
    01202     z += ApplyFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
    01203
    01204     /* On the bridge ramp? */
    01205     if (5 <= pos && pos <= 10) {
    01206       uint delta;
    01207
    01208       if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
    01209
    01210       switch (dir) {
    01211         default: NOT_REACHED();
    01212         case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
    01213         case DIAGDIR_SE: delta = y / 2; break;
    01214         case DIAGDIR_SW: delta = x / 2; break;
    01215         case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
    01216       }
    01217       return z + 1 + delta;
    01218     }
    01219   }
    01220
    01221   return z + GetPartialZ(x, y, tileh);
    01222 }
    01223
    01224 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
    01225 {
    01226   return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
    01227 }
    01228
    01229
    01230 static void GetAcceptedCargo_TunnelBridge(TileIndex tile, AcceptedCargo ac)
    01231 {
    01232   /* not used */
    01233 }
    01234
    01235 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
    01236 {
    01237   TransportType tt = GetTunnelBridgeTransportType(tile);
    01238
    01239   if (IsTunnel(tile)) {
    01240     td->str = (tt == TRANSPORT_RAIL) ? STR_5017_RAILROAD_TUNNEL : STR_5018_ROAD_TUNNEL;
    01241   } else { // IsBridge(tile)
    01242     td->str = (tt == TRANSPORT_WATER) ? STR_AQUEDUCT : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
    01243   }
    01244   td->owner[0] = GetTileOwner(tile);
    01245 }
    01246
    01247
    01248 static void AnimateTile_TunnelBridge(TileIndex tile)
    01249 {
    01250   /* not used */
    01251 }
    01252
    01253 static void TileLoop_TunnelBridge(TileIndex tile)
    01254 {
    01255   bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
    01256   switch (_settings_game.game_creation.landscape) {
    01257     case LT_ARCTIC:
    01258       if (snow_or_desert != (GetTileZ(tile) > GetSnowLine())) {
    01259         SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
    01260         MarkTileDirtyByTile(tile);
    01261       }
    01262       break;
    01263
    01264     case LT_TROPIC:
    01265       if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
    01266         SetTunnelBridgeSnowOrDesert(tile, true);
    01267         MarkTileDirtyByTile(tile);
    01268       }
    01269       break;
    01270
    01271     default:
    01272       break;
    01273   }
    01274 }
    01275
    01276 static bool ClickTile_TunnelBridge(TileIndex tile)
    01277 {
    01278   /* not used */
    01279   return false;
    01280 }
    01281
    01282
    01283 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
    01284 {
    01285   TransportType transport_type = GetTunnelBridgeTransportType(tile);
    01286   if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
    01287
    01288   DiagDirection dir = GetTunnelBridgeDirection(tile);
    01289   if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
    01290   return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
    01291 }
    01292
    01293 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
    01294 {
    01295   if (!IsTileOwner(tile, old_owner)) return;
    01296
    01297   if (new_owner != INVALID_OWNER) {
    01298     SetTileOwner(tile, new_owner);
    01299   } else {
    01300     if (CmdFailed(DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR))) {
    01301       /* When clearing the bridge/tunnel failed there are still vehicles on/in
    01302        * the bridge/tunnel. As all *our* vehicles are already removed, they
    01303        * must be of another owner. Therefore this can't be rail tunnel/bridge.
    01304        * In that case we can safely reassign the ownership to OWNER_NONE. */
    01305       assert(GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL);
    01306       SetTileOwner(tile, OWNER_NONE);
    01307     }
    01308   }
    01309 }
    01310
    01311
    01312 static const byte _tunnel_fractcoord_1[4]    = {0x8E, 0x18, 0x81, 0xE8};
    01313 static const byte _tunnel_fractcoord_2[4]    = {0x81, 0x98, 0x87, 0x38};
    01314 static const byte _tunnel_fractcoord_3[4]    = {0x82, 0x88, 0x86, 0x48};
    01315 static const byte _exit_tunnel_track[4]      = {1, 2, 1, 2};
    01316
    01318 static const Trackdir _road_exit_tunnel_state[DIAGDIR_END] = {
    01319   TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
    01320 };
    01321 static const byte _road_exit_tunnel_frame[4] = {2, 7, 9, 4};
    01322
    01323 static const byte _tunnel_fractcoord_4[4]    = {0x52, 0x85, 0x98, 0x29};
    01324 static const byte _tunnel_fractcoord_5[4]    = {0x92, 0x89, 0x58, 0x25};
    01325 static const byte _tunnel_fractcoord_6[4]    = {0x92, 0x89, 0x56, 0x45};
    01326 static const byte _tunnel_fractcoord_7[4]    = {0x52, 0x85, 0x96, 0x49};
    01327
    01328 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
    01329 {
    01330   int z = GetSlopeZ(x, y) - v->z_pos;
    01331
    01332   if (abs(z) > 2) return VETSB_CANNOT_ENTER;
    01333   const DiagDirection dir = GetTunnelBridgeDirection(tile);
    01334
    01335   if (IsTunnel(tile)) {
    01336     byte fc;
    01337     DiagDirection vdir;
    01338
    01339     if (v->type == VEH_TRAIN) {
    01340       fc = (x & 0xF) + (y << 4);
    01341
    01342       vdir = DirToDiagDir(v->direction);
    01343
    01344       if (v->u.rail.track != TRACK_BIT_WORMHOLE && dir == vdir) {
    01345         if (IsFrontEngine(v) && fc == _tunnel_fractcoord_1[dir]) {
    01346           if (!PlayVehicleSound(v, VSE_TUNNEL) && RailVehInfo(v->engine_type)->engclass == 0) {
    01347             SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
    01348           }
    01349           return VETSB_CONTINUE;
    01350         }
    01351         if (fc == _tunnel_fractcoord_2[dir]) {
    01352           v->tile = tile;
    01353           v->u.rail.track = TRACK_BIT_WORMHOLE;
    01354           v->vehstatus |= VS_HIDDEN;
    01355           return VETSB_ENTERED_WORMHOLE;
    01356         }
    01357       }
    01358
    01359       if (dir == ReverseDiagDir(vdir) && fc == _tunnel_fractcoord_3[dir] && z == 0) {
    01360         /* We're at the tunnel exit ?? */
    01361         v->tile = tile;
    01362         v->u.rail.track = (TrackBits)_exit_tunnel_track[dir];
    01363         assert(v->u.rail.track);
    01364         v->vehstatus &= ~VS_HIDDEN;
    01365         return VETSB_ENTERED_WORMHOLE;
    01366       }
    01367     } else if (v->type == VEH_ROAD) {
    01368       fc = (x & 0xF) + (y << 4);
    01369       vdir = DirToDiagDir(v->direction);
    01370
    01371       /* Enter tunnel? */
    01372       if (v->u.road.state != RVSB_WORMHOLE && dir == vdir) {
    01373         if (fc == _tunnel_fractcoord_4[dir] ||
    01374             fc == _tunnel_fractcoord_5[dir]) {
    01375           v->tile = tile;
    01376           v->u.road.state = RVSB_WORMHOLE;
    01377           v->vehstatus |= VS_HIDDEN;
    01378           return VETSB_ENTERED_WORMHOLE;
    01379         } else {
    01380           return VETSB_CONTINUE;
    01381         }
    01382       }
    01383
    01384       if (dir == ReverseDiagDir(vdir) && (
    01385             /* We're at the tunnel exit ?? */
    01386             fc == _tunnel_fractcoord_6[dir] ||
    01387             fc == _tunnel_fractcoord_7[dir]
    01388           ) &&
    01389           z == 0) {
    01390         v->tile = tile;
    01391         v->u.road.state = _road_exit_tunnel_state[dir];
    01392         v->u.road.frame = _road_exit_tunnel_frame[dir];
    01393         v->vehstatus &= ~VS_HIDDEN;
    01394         return VETSB_ENTERED_WORMHOLE;
    01395       }
    01396     }
    01397   } else { // IsBridge(tile)
    01398
    01399     if (v->IsPrimaryVehicle() && v->type != VEH_SHIP) {
    01400       /* modify speed of vehicle */
    01401       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
    01402
    01403       if (v->type == VEH_ROAD) spd *= 2;
    01404       if (v->cur_speed > spd) v->cur_speed = spd;
    01405     }
    01406
    01407     if (DirToDiagDir(v->direction) == dir) {
    01408       switch (dir) {
    01409         default: NOT_REACHED();
    01410         case DIAGDIR_NE: if ((x & 0xF) != 0)             return VETSB_CONTINUE; break;
    01411         case DIAGDIR_SE: if ((y & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
    01412         case DIAGDIR_SW: if ((x & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
    01413         case DIAGDIR_NW: if ((y & 0xF) != 0)             return VETSB_CONTINUE; break;
    01414       }
    01415       switch (v->type) {
    01416         case VEH_TRAIN:
    01417           v->u.rail.track = TRACK_BIT_WORMHOLE;
    01418           ClrBit(v->u.rail.flags, VRF_GOINGUP);
    01419           ClrBit(v->u.rail.flags, VRF_GOINGDOWN);
    01420           break;
    01421
    01422         case VEH_ROAD:
    01423           v->u.road.state = RVSB_WORMHOLE;
    01424           break;
    01425
    01426         case VEH_SHIP:
    01427           v->u.ship.state = TRACK_BIT_WORMHOLE;
    01428           break;
    01429
    01430         default: NOT_REACHED();
    01431       }
    01432       return VETSB_ENTERED_WORMHOLE;
    01433     } else if (DirToDiagDir(v->direction) == ReverseDiagDir(dir)) {
    01434       v->tile = tile;
    01435       switch (v->type) {
    01436         case VEH_TRAIN:
    01437           if (v->u.rail.track == TRACK_BIT_WORMHOLE) {
    01438             v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
    01439             return VETSB_ENTERED_WORMHOLE;
    01440           }
    01441           break;
    01442
    01443         case VEH_ROAD:
    01444           if (v->u.road.state == RVSB_WORMHOLE) {
    01445             v->u.road.state = _road_exit_tunnel_state[dir];
    01446             v->u.road.frame = 0;
    01447             return VETSB_ENTERED_WORMHOLE;
    01448           }
    01449           break;
    01450
    01451         case VEH_SHIP:
    01452           if (v->u.ship.state == TRACK_BIT_WORMHOLE) {
    01453             v->u.ship.state = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
    01454             return VETSB_ENTERED_WORMHOLE;
    01455           }
    01456           break;
    01457
    01458         default: NOT_REACHED();
    01459       }
    01460     }
    01461   }
    01462   return VETSB_CONTINUE;
    01463 }
    01464
    01465 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
    01466 {
    01467   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
    01468     DiagDirection direction = GetTunnelBridgeDirection(tile);
    01469     Axis axis = DiagDirToAxis(direction);
    01470     CommandCost res;
    01471     uint z_old;
    01472     Slope tileh_old = GetTileSlope(tile, &z_old);
    01473
    01474     /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
    01475     if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
    01476       CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
    01477       res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
    01478     } else {
    01479       CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
    01480       res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
    01481     }
    01482
    01483     /* Surface slope is valid and remains unchanged? */
    01484     if (!CmdFailed(res) && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
    01485   }
    01486
    01487   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    01488 }
    01489
    01490 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
    01491   DrawTile_TunnelBridge,           /* draw_tile_proc */
    01492   GetSlopeZ_TunnelBridge,          /* get_slope_z_proc */
    01493   ClearTile_TunnelBridge,          /* clear_tile_proc */
    01494   GetAcceptedCargo_TunnelBridge,   /* get_accepted_cargo_proc */
    01495   GetTileDesc_TunnelBridge,        /* get_tile_desc_proc */
    01496   GetTileTrackStatus_TunnelBridge, /* get_tile_track_status_proc */
    01497   ClickTile_TunnelBridge,          /* click_tile_proc */
    01498   AnimateTile_TunnelBridge,        /* animate_tile_proc */
    01499   TileLoop_TunnelBridge,           /* tile_loop_clear */
    01500   ChangeTileOwner_TunnelBridge,    /* change_tile_owner_clear */
    01501   NULL,                            /* get_produced_cargo_proc */
    01502   VehicleEnter_TunnelBridge,       /* vehicle_enter_tile_proc */
    01503   GetFoundation_TunnelBridge,      /* get_foundation_proc */
    01504   TerraformTile_TunnelBridge,      /* terraform_tile_proc */
    01505 };